issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
timestamp[us, tz=UTC]
report_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
47,207
Bug 47207 call hierarchy: Enablement of "Search Scope" item on view menu is wrong [call hierarchy]
At least on Windows NT/2000 this item is shown as disabled until the user clicks it it which case the submenu opens. I have been looking into this problem but without any results so far. Any suggestions are welcome.
resolved fixed
675825b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T18:44:41Z
2003-11-21T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SearchScopeProjectAction.java
47,207
Bug 47207 call hierarchy: Enablement of "Search Scope" item on view menu is wrong [call hierarchy]
At least on Windows NT/2000 this item is shown as disabled until the user clicks it it which case the submenu opens. I have been looking into this problem but without any results so far. Any suggestions are welcome.
resolved fixed
675825b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T18:44:41Z
2003-11-21T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SearchScopeWorkingSetAction.java
47,207
Bug 47207 call hierarchy: Enablement of "Search Scope" item on view menu is wrong [call hierarchy]
At least on Windows NT/2000 this item is shown as disabled until the user clicks it it which case the submenu opens. I have been looking into this problem but without any results so far. Any suggestions are welcome.
resolved fixed
675825b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T18:44:41Z
2003-11-21T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SearchScopeWorkspaceAction.java
47,207
Bug 47207 call hierarchy: Enablement of "Search Scope" item on view menu is wrong [call hierarchy]
At least on Windows NT/2000 this item is shown as disabled until the user clicks it it which case the submenu opens. I have been looking into this problem but without any results so far. Any suggestions are welcome.
resolved fixed
675825b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T18:44:41Z
2003-11-21T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SearchUtil.java
47,207
Bug 47207 call hierarchy: Enablement of "Search Scope" item on view menu is wrong [call hierarchy]
At least on Windows NT/2000 this item is shown as disabled until the user clicks it it which case the submenu opens. I have been looking into this problem but without any results so far. Any suggestions are welcome.
resolved fixed
675825b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T18:44:41Z
2003-11-21T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/SelectWorkingSetAction.java
48,325
Bug 48325 introduce parameter throws NPE if there are compiler errors [refactoring]
I200312020950 in the file below introduce the "3" as a parameter. -------------------------------------------------- class A { void method() { } void method() { int x = 3; //<-- introduce 3 as a parameter } } ---------------------------------------------------- the result is: ------------------------------------------------------ java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.IntroduceParameterAction.run (IntroduceParameterAction.java:69) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:535) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:487) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:459) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run (ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun (OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.Bindings.findMethod(Bindings.java:553) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.f indAffectedCompilationUnits(IntroduceParameterRefactoring.java:412) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c hangeReferences(IntroduceParameterRefactoring.java:368) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c heckInput(IntroduceParameterRefactoring.java:327) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 49 more ----------------------------------------------
resolved fixed
321e262
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T19:20:47Z
2003-12-09T08:53:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceParameter/invalid/NoMethodBinding.java
48,325
Bug 48325 introduce parameter throws NPE if there are compiler errors [refactoring]
I200312020950 in the file below introduce the "3" as a parameter. -------------------------------------------------- class A { void method() { } void method() { int x = 3; //<-- introduce 3 as a parameter } } ---------------------------------------------------- the result is: ------------------------------------------------------ java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.IntroduceParameterAction.run (IntroduceParameterAction.java:69) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:535) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:487) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:459) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run (ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun (OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.Bindings.findMethod(Bindings.java:553) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.f indAffectedCompilationUnits(IntroduceParameterRefactoring.java:412) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c hangeReferences(IntroduceParameterRefactoring.java:368) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c heckInput(IntroduceParameterRefactoring.java:327) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 49 more ----------------------------------------------
resolved fixed
321e262
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T19:20:47Z
2003-12-09T08:53:20Z
org.eclipse.jdt.ui.tests.refactoring/test
48,325
Bug 48325 introduce parameter throws NPE if there are compiler errors [refactoring]
I200312020950 in the file below introduce the "3" as a parameter. -------------------------------------------------- class A { void method() { } void method() { int x = 3; //<-- introduce 3 as a parameter } } ---------------------------------------------------- the result is: ------------------------------------------------------ java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.IntroduceParameterAction.run (IntroduceParameterAction.java:69) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:535) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:487) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:459) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run (ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun (OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.Bindings.findMethod(Bindings.java:553) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.f indAffectedCompilationUnits(IntroduceParameterRefactoring.java:412) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c hangeReferences(IntroduceParameterRefactoring.java:368) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c heckInput(IntroduceParameterRefactoring.java:327) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 49 more ----------------------------------------------
resolved fixed
321e262
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T19:20:47Z
2003-12-09T08:53:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterTests.java
48,325
Bug 48325 introduce parameter throws NPE if there are compiler errors [refactoring]
I200312020950 in the file below introduce the "3" as a parameter. -------------------------------------------------- class A { void method() { } void method() { int x = 3; //<-- introduce 3 as a parameter } } ---------------------------------------------------- the result is: ------------------------------------------------------ java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.IntroduceParameterAction.run (IntroduceParameterAction.java:69) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:535) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:487) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:459) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run (ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun (OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.Bindings.findMethod(Bindings.java:553) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.f indAffectedCompilationUnits(IntroduceParameterRefactoring.java:412) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c hangeReferences(IntroduceParameterRefactoring.java:368) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c heckInput(IntroduceParameterRefactoring.java:327) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 49 more ----------------------------------------------
resolved fixed
321e262
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T19:20:47Z
2003-12-09T08:53:20Z
org.eclipse.jdt.ui/core
48,325
Bug 48325 introduce parameter throws NPE if there are compiler errors [refactoring]
I200312020950 in the file below introduce the "3" as a parameter. -------------------------------------------------- class A { void method() { } void method() { int x = 3; //<-- introduce 3 as a parameter } } ---------------------------------------------------- the result is: ------------------------------------------------------ java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.IntroduceParameterAction.run (IntroduceParameterAction.java:69) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:535) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:487) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:459) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2294) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1975) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run (ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.internal.boot.OSGiBootLoader.basicRun (OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.dom.Bindings.findMethod(Bindings.java:553) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.f indAffectedCompilationUnits(IntroduceParameterRefactoring.java:412) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c hangeReferences(IntroduceParameterRefactoring.java:368) at org.eclipse.jdt.internal.corext.refactoring.code.IntroduceParameterRefactoring.c heckInput(IntroduceParameterRefactoring.java:327) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 49 more ----------------------------------------------
resolved fixed
321e262
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-16T19:20:47Z
2003-12-09T08:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceParameterRefactoring.java
52,275
Bug 52275 Package Explorer error marker icon not updated
I have a custom builder which is invoked after a save (CTRL+S) that identifies problems with resources in my non-Java project and marks the resource with errors (or clears them as needed). This seems to work fine except that the problem marker icons in the Package Explorer are for some reason not automatically updated. Selecting the 'Go Into' context menu option and then navigating back again shows the correct problem marker icon state. Alternatively, closing and opening the project/eclipse displays the correct icon state. Is there something that needs to be called in order to 'refresh' the problem markers in the Package Explorer view? This is happening under Linux (RH9) using Eclipse 2.1.2 Comments from newsgroup: "The decorator handles this case the problem updater does not. "
resolved fixed
d3694f6
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T09:29:41Z
2004-02-17T17:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemMarkerManager.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.viewsupport; import java.util.HashSet; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceChangeEvent; import org.eclipse.core.resources.IResourceChangeListener; import org.eclipse.core.resources.IResourceDelta; import org.eclipse.core.resources.IResourceDeltaVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.text.source.AnnotationModelEvent; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelListener; import org.eclipse.jface.text.source.IAnnotationModelListenerExtension; import org.eclipse.jface.util.ListenerList; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitAnnotationModelEvent; import org.eclipse.jdt.internal.ui.util.SWTUtil; /** * Listens to resource deltas and filters for marker changes of type IMarker.PROBLEM * Viewers showing error ticks should register as listener to * this type. */ public class ProblemMarkerManager implements IResourceChangeListener, IAnnotationModelListener , IAnnotationModelListenerExtension { /** * Visitors used to look if the element change delta containes a marker change. */ private static class ProjectErrorVisitor implements IResourceDeltaVisitor { private HashSet fChangedElements; public ProjectErrorVisitor(HashSet changedElements) { fChangedElements= changedElements; } public boolean visit(IResourceDelta delta) throws CoreException { IResource res= delta.getResource(); if (res instanceof IProject && delta.getKind() == IResourceDelta.CHANGED) { try { IProject project= (IProject) res; if (!project.isAccessible() || !project.hasNature(JavaCore.NATURE_ID)) { // only track open Java projects return false; } } catch (CoreException e) { JavaPlugin.log(e); return false; } } checkInvalidate(delta, res); return true; } private void checkInvalidate(IResourceDelta delta, IResource resource) { int kind= delta.getKind(); if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.ADDED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { // invalidate the resource and all parents while (resource.getType() != IResource.ROOT && fChangedElements.add(resource)) { resource= resource.getParent(); } } } private boolean isErrorDelta(IResourceDelta delta) { if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) { IMarkerDelta[] markerDeltas= delta.getMarkerDeltas(); for (int i= 0; i < markerDeltas.length; i++) { if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) { int kind= markerDeltas[i].getKind(); if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) return true; int severity= markerDeltas[i].getAttribute(IMarker.SEVERITY, -1); int newSeverity= markerDeltas[i].getMarker().getAttribute(IMarker.SEVERITY, -1); if (newSeverity != severity) return true; } } } return false; } } private ListenerList fListeners; public ProblemMarkerManager() { fListeners= new ListenerList(10); } /* * @see IResourceChangeListener#resourceChanged */ public void resourceChanged(IResourceChangeEvent event) { HashSet changedElements= new HashSet(); try { IResourceDelta delta= event.getDelta(); if (delta != null) delta.accept(new ProjectErrorVisitor(changedElements)); } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } if (!changedElements.isEmpty()) { IResource[] changes= (IResource[]) changedElements.toArray(new IResource[changedElements.size()]); fireChanges(changes, true); } } /* (non-Javadoc) * @see IAnnotationModelListener#modelChanged(IAnnotationModel) */ public void modelChanged(IAnnotationModel model) { // no action } /* (non-Javadoc) * @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent) */ public void modelChanged(AnnotationModelEvent event) { if (event instanceof CompilationUnitAnnotationModelEvent) { CompilationUnitAnnotationModelEvent cuEvent= (CompilationUnitAnnotationModelEvent) event; if (cuEvent.includesProblemMarkerAnnotationChanges()) { IResource[] changes= new IResource[] { cuEvent.getUnderlyingResource() }; fireChanges(changes, false); } } } /** * Adds a listener for problem marker changes. */ public void addListener(IProblemChangedListener listener) { if (fListeners.isEmpty()) { JavaPlugin.getWorkspace().addResourceChangeListener(this); JavaPlugin.getDefault().getCompilationUnitDocumentProvider().addGlobalAnnotationModelListener(this); } fListeners.add(listener); } /** * Removes a <code>IProblemChangedListener</code>. */ public void removeListener(IProblemChangedListener listener) { fListeners.remove(listener); if (fListeners.isEmpty()) { JavaPlugin.getWorkspace().removeResourceChangeListener(this); JavaPlugin.getDefault().getCompilationUnitDocumentProvider().removeGlobalAnnotationModelListener(this); } } private void fireChanges(final IResource[] changes, final boolean isMarkerChange) { Display display= SWTUtil.getStandardDisplay(); if (display != null && !display.isDisposed()) { display.asyncExec(new Runnable() { public void run() { Object[] listeners= fListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { IProblemChangedListener curr= (IProblemChangedListener) listeners[i]; curr.problemsChanged(changes, isMarkerChange); } } }); } } }
48,482
Bug 48482 Wording on "File Search" page
I20031203 The button next to the "File Name Patterns" combo is labeled "Browse...". A more appropriate term would be "Choose..." (identical to the term used for the Scope). For me "Browsing" is more associated with exploring a network or a filesystem but not for picking an item from a list.
resolved fixed
a0b6315
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T09:44:39Z
2003-12-11T13:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
32,378
Bug 32378 Java Build Path properties page [general issue] [build path]
The Java Build Path properties page should refresh when it is opened and should also have an apply button. We are running into problems because we also contribute a properties page to Java projects that edits the build properties and it is unclear what the current state of the build path is. There are two main problems. First, the user opens our page, modifies and applies the change and then goes to the Java Build Path page where the change is not available because it is not refreshed. At this point if the user modifies the Java Build Path page and exits. The changes he first made are wiped out and replaced with current state of the Java Build Path page. Second, the user opens the Java Build Path page and modifies some information and then goes to our page; these changes are unavaible. It would be nice if the user could have applied the changes from the Java Build Path page to make them avaible to our page. We are able to handle this state (in English at least) because our page comes after the Java Build path page and is saved last. Ultimatly, the best solution would be to create an in memory copy of the Build Properties that both pages could use without these synchronization issues.
closed fixed
a0ed6d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T15:34:07Z
2003-02-20T19:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/BuildPathDialog.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.dialogs; import java.lang.reflect.InvocationTargetException; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.preferences.PreferencesMessages; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; public class BuildPathDialog extends StatusDialog { private IJavaProject fProject; private BuildPathsBlock fBlock; public BuildPathDialog(Shell parent, IJavaProject project) { super(parent); setShellStyle(getShellStyle() | SWT.RESIZE); Assert.isNotNull(project); fProject= project; } protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(JavaUIMessages.getFormattedString("BuildPathDialog.title", fProject.getElementName())); //$NON-NLS-1$ } protected Control createDialogArea(Composite parent) { IStatusChangeListener listener = new IStatusChangeListener() { public void statusChanged(IStatus status) { updateStatus(status); } }; Composite result= (Composite)super.createDialogArea(parent); fBlock= new BuildPathsBlock(listener, 0); fBlock.init(fProject, null, null); fBlock.createControl(result).setLayoutData(new GridData(GridData.FILL_BOTH)); applyDialogFont(result); return result; } protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.OK_ID) { configureBuildPath(); } super.buttonPressed(buttonId); } private void configureBuildPath() { Shell shell= getShell(); IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { fBlock.configureJavaProject(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable, fProject.getProject()); try { new ProgressMonitorDialog(shell).run(true, true, op); } catch (InvocationTargetException e) { String title= PreferencesMessages.getString("BuildPathsPropertyPage.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("BuildPathsPropertyPage.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, shell, title, message); } catch (InterruptedException e) { // cancelled } } }
32,378
Bug 32378 Java Build Path properties page [general issue] [build path]
The Java Build Path properties page should refresh when it is opened and should also have an apply button. We are running into problems because we also contribute a properties page to Java projects that edits the build properties and it is unclear what the current state of the build path is. There are two main problems. First, the user opens our page, modifies and applies the change and then goes to the Java Build Path page where the change is not available because it is not refreshed. At this point if the user modifies the Java Build Path page and exits. The changes he first made are wiped out and replaced with current state of the Java Build Path page. Second, the user opens the Java Build Path page and modifies some information and then goes to our page; these changes are unavaible. It would be nice if the user could have applied the changes from the Java Build Path page to make them avaible to our page. We are able to handle this state (in English at least) because our page comes after the Java Build path page and is saved last. Ultimatly, the best solution would be to create an in memory copy of the Build Properties that both pages could use without these synchronization issues.
closed fixed
a0ed6d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T15:34:07Z
2003-02-20T19:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/BuildPathsPropertyPage.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.dialogs.PropertyPage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * Property page for configuring the Java build path */ public class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener { private static final String PAGE_SETTINGS= "BuildPathsPropertyPage"; //$NON-NLS-1$ private static final String INDEX= "pageIndex"; //$NON-NLS-1$ private BuildPathsBlock fBuildPathsBlock; /* * @see PreferencePage#createControl(Composite) */ protected Control createContents(Composite parent) { // ensure the page has no special buttons noDefaultAndApplyButton(); IProject project= getProject(); Control result; if (project == null || !isJavaProject(project)) { result= createWithoutJava(parent); } else if (!project.isOpen()) { result= createForClosedProject(parent); } else { result= createWithJava(parent, project); } Dialog.applyDialogFont(result); return result; } /* * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.BUILD_PATH_PROPERTY_PAGE); } private IDialogSettings getSettings() { IDialogSettings javaSettings= JavaPlugin.getDefault().getDialogSettings(); IDialogSettings pageSettings= javaSettings.getSection(PAGE_SETTINGS); if (pageSettings == null) { pageSettings= javaSettings.addNewSection(PAGE_SETTINGS); pageSettings.put(INDEX, 3); } return pageSettings; } /* * Content for valid projects. */ private Control createWithJava(Composite parent, IProject project) { fBuildPathsBlock= new BuildPathsBlock(this, getSettings().getInt(INDEX)); fBuildPathsBlock.init(JavaCore.create(project), null, null); return fBuildPathsBlock.createControl(parent); } /* * Content for non-Java projects. */ private Control createWithoutJava(Composite parent) { Label label= new Label(parent, SWT.LEFT); label.setText(PreferencesMessages.getString("BuildPathsPropertyPage.no_java_project.message")); //$NON-NLS-1$ fBuildPathsBlock= null; setValid(true); return label; } /* * Content for closed projects. */ private Control createForClosedProject(Composite parent) { Label label= new Label(parent, SWT.LEFT); label.setText(PreferencesMessages.getString("BuildPathsPropertyPage.closed_project.message")); //$NON-NLS-1$ fBuildPathsBlock= null; setValid(true); return label; } private IProject getProject() { IAdaptable adaptable= getElement(); if (adaptable != null) { IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (elem instanceof IJavaProject) { return ((IJavaProject) elem).getProject(); } } return null; } private boolean isJavaProject(IProject proj) { try { return proj.hasNature(JavaCore.NATURE_ID); } catch (CoreException e) { JavaPlugin.log(e); } return false; } /* * @see IPreferencePage#performOk */ public boolean performOk() { if (fBuildPathsBlock != null) { getSettings().put(INDEX, fBuildPathsBlock.getPageIndex()); Shell shell= getControl().getShell(); IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { fBuildPathsBlock.configureJavaProject(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable, getProject()); try { new ProgressMonitorDialog(shell).run(true, true, op); } catch (InvocationTargetException e) { String title= PreferencesMessages.getString("BuildPathsPropertyPage.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("BuildPathsPropertyPage.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, shell, title, message); return false; } catch (InterruptedException e) { // cancelled return false; } } return true; } /* (non-Javadoc) * @see IStatusChangeListener#statusChanged */ public void statusChanged(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } /* (non-Javadoc) * @see org.eclipse.jface.preference.IPreferencePage#performCancel() */ public boolean performCancel() { if (fBuildPathsBlock != null) { getSettings().put(INDEX, fBuildPathsBlock.getPageIndex()); } return super.performCancel(); } }
32,378
Bug 32378 Java Build Path properties page [general issue] [build path]
The Java Build Path properties page should refresh when it is opened and should also have an apply button. We are running into problems because we also contribute a properties page to Java projects that edits the build properties and it is unclear what the current state of the build path is. There are two main problems. First, the user opens our page, modifies and applies the change and then goes to the Java Build Path page where the change is not available because it is not refreshed. At this point if the user modifies the Java Build Path page and exits. The changes he first made are wiped out and replaced with current state of the Java Build Path page. Second, the user opens the Java Build Path page and modifies some information and then goes to our page; these changes are unavaible. It would be nice if the user could have applied the changes from the Java Build Path page to make them avaible to our page. We are able to handle this state (in English at least) because our page comes after the Java Build path page and is saved last. Ultimatly, the best solution would be to create an in memory copy of the Build Properties that both pages could use without these synchronization issues.
closed fixed
a0ed6d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T15:34:07Z
2003-02-20T19:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.window.Window; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.ui.views.navigator.ResourceSorter; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModelStatus; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class BuildPathsBlock { public static interface IRemoveOldBinariesQuery { /** * Do the callback. Returns <code>true</code> if .class files should be removed from the * old output location. * @param oldOutputLocation The old output location * @return Returns true if .class files should be removed. * @throws InterruptedException */ boolean doQuery(IPath oldOutputLocation) throws InterruptedException; } private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringButtonDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fOutputFolderStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private int fPageIndex; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IStatusChangeListener context, int pageToShow) { fWorkspaceRoot= JavaPlugin.getWorkspace().getRoot(); fContext= context; fPageIndex= pageToShow; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); //$NON-NLS-1$ fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); fBuildPathDialogField= new StringButtonDialogField(adapter); fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fOutputFolderStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; PixelConverter converter= new PixelConverter(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(IDE.SharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0); int maxFieldWidth= converter.convertWidthInCharsToPixels(40); LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth); LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null)); editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); folder.setSelection(fPageIndex); fCurrPage= (BuildPathBasePage) folder.getItem(fPageIndex).getData(); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK); Dialog.applyDialogFont(composite); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param jproject The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project- the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projectExists= false; List newClassPath= null; IProject project= fCurrJProject.getProject(); projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$ if (projectExists) { if (outputLocation == null) { outputLocation= fCurrJProject.readOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.readRawClasspath(); } } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } if (classpathEntries != null) { newClassPath= getExistingEntries(classpathEntries); } if (newClassPath == null) { newClassPath= getDefaultClassPath(jproject); } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fBuildPathDialogField.enableButton(projectExists); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } private ArrayList getExistingEntries(IClasspathEntry[] classpathEntries) { ArrayList newClassPath= new ArrayList(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; newClassPath.add(CPListElement.createFromExisting(curr, fCurrJProject)); } return newClassPath; } // -------- public api -------- /** * @return Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * @return Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * @return Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } public int getPageIndex() { return fPageIndex; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String sourceFolderName= store.getString(PreferenceConstants.SRCBIN_SRCNAME); if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ) && sourceFolderName.length() > 0) { srcFolder= jproj.getProject().getFolder(sourceFolderName); } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary(); list.addAll(getExistingEntries(jreEntries)); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); if (store.getBoolean(PreferenceConstants.SRCBIN_FOLDERS_IN_NEWPROJ)) { String outputLocationName= store.getString(PreferenceConstants.SRCBIN_BINNAME); return jproj.getProject().getFullPath().append(outputLocationName); } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); } else if (field == fBuildPathDialogField) { updateOutputLocationStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fClassPathStatus, fOutputFolderStatus, fBuildPathStatus }); } /** * Validates the build path. */ public void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); CPListElement entryMissing= null; int nEntriesMissing= 0; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); if (currElement.isMissing()) { nEntriesMissing++; if (entryMissing == null) { entryMissing= currElement; } } } if (nEntriesMissing > 0) { if (nEntriesMissing == 1) { fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntryMissing", entryMissing.getPath().toString())); //$NON-NLS-1$ } else { fClassPathStatus.setWarning(NewWizardMessages.getFormattedString("BuildPathsBlock.warning.EntriesMissing", String.valueOf(nEntriesMissing))); //$NON-NLS-1$ } } /* if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } */ updateBuildPathStatus(); } /** * Validates output location & build path. */ private void updateOutputLocationStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); fOutputLocationPath= path; IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fOutputFolderStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } fOutputFolderStatus.setOK(); updateBuildPathStatus(); } private void updateBuildPathStatus() { List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); } IJavaModelStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, fOutputLocationPath); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc_project"), 10); //$NON-NLS-1$ // create the project try { if (!project.exists()) { IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName()); if (Platform.getInstanceLocation().equals(locationPath)) { locationPath= null; } desc.setLocation(locationPath); project.create(desc, monitor); monitor= null; } if (!project.isOpen()) { project.open(monitor); monitor= null; } } finally { if (monitor != null) { monitor.done(); } } } public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException { if (!project.hasNature(JavaCore.NATURE_ID)) { IProjectDescription description = project.getDescription(); String[] prevNatures= description.getNatureIds(); String[] newNatures= new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length]= JavaCore.NATURE_ID; description.setNatureIds(newNatures); project.setDescription(description, monitor); } else { monitor.worked(1); } } public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.setTaskName(NewWizardMessages.getString("BuildPathsBlock.operationdesc_java")); //$NON-NLS-1$ monitor.beginTask("", 10); //$NON-NLS-1$ try { internalConfigureJavaProject(fClassPathList.getElements(), getOutputLocation(), monitor); } finally { monitor.done(); } } /* * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void internalConfigureJavaProject(List classPathEntries, IPath outputLocation, IProgressMonitor monitor) throws CoreException, InterruptedException { // 10 monitor steps to go IRemoveOldBinariesQuery reorgQuery= getRemoveOldBinariesQuery(null); // remove old .class files if (reorgQuery != null) { IPath oldOutputLocation= fCurrJProject.getOutputLocation(); if (!outputLocation.equals(oldOutputLocation)) { IResource res= fWorkspaceRoot.findMember(oldOutputLocation); if (res instanceof IContainer && hasClassfiles(res)) { if (reorgQuery.doQuery(oldOutputLocation)) { removeOldClassfiles(res); } } } } // create and set the output path first if (!fWorkspaceRoot.exists(outputLocation)) { IFolder folder= fWorkspaceRoot.getFolder(outputLocation); CoreUtility.createFolder(folder, true, true, null); folder.setDerived(true); } monitor.worked(2); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; ArrayList paths= new ArrayList(); ArrayList urls= new ArrayList(); // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IPath folderOutput= (IPath) entry.getAttribute(CPListElement.OUTPUT); if (folderOutput != null && folderOutput.segmentCount() > 1) { IFolder folder= fWorkspaceRoot.getFolder(folderOutput); CoreUtility.createFolder(folder, true, true, null); } } classpath[i]= entry.getClasspathEntry(); collectJavaDocLocations(entry, paths, urls); } JavaUI.setLibraryJavadocLocations((IPath[]) paths.toArray(new IPath[paths.size()]), (URL[]) urls.toArray(new URL[paths.size()])); monitor.worked(1); fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7)); } private void collectJavaDocLocations(CPListElement entry, List paths, List urls) { int entryKind= entry.getEntryKind(); if (entryKind == IClasspathEntry.CPE_LIBRARY || entryKind == IClasspathEntry.CPE_VARIABLE) { URL javadocLocation= (URL) entry.getAttribute(CPListElement.JAVADOC); IPath path= entry.getPath(); if (entryKind == IClasspathEntry.CPE_VARIABLE) { path= JavaCore.getResolvedVariablePath(path); } if (path != null) { paths.add(path); urls.add(javadocLocation); } } else if (entryKind == IClasspathEntry.CPE_CONTAINER) { Object[] children= entry.getChildren(false); for (int i= 0; i < children.length; i++) { collectJavaDocLocations((CPListElement) children[i], paths, urls); } } } public static boolean hasClassfiles(IResource resource) throws CoreException { if (resource.isDerived()) { //$NON-NLS-1$ return true; } if (resource instanceof IContainer) { IResource[] members= ((IContainer) resource).members(); for (int i= 0; i < members.length; i++) { if (hasClassfiles(members[i])) { return true; } } } return false; } public static void removeOldClassfiles(IResource resource) throws CoreException { if (resource.isDerived()) { resource.delete(false, null); } else if (resource instanceof IContainer) { IResource[] members= ((IContainer) resource).members(); for (int i= 0; i < members.length; i++) { removeOldClassfiles(members[i]); } } } public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) { return new IRemoveOldBinariesQuery() { public boolean doQuery(final IPath oldOutputLocation) throws InterruptedException { final int[] res= new int[] { 1 }; Display.getDefault().syncExec(new Runnable() { public void run() { Shell sh= shell != null ? shell : JavaPlugin.getActiveWorkbenchShell(); String title= NewWizardMessages.getString("BuildPathsBlock.RemoveBinariesDialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("BuildPathsBlock.RemoveBinariesDialog.description", oldOutputLocation.toString()); //$NON-NLS-1$ MessageDialog dialog= new MessageDialog(sh, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); res[0]= dialog.open(); } }); if (res[0] == 0) { return true; } else if (res[0] == 1) { return false; } throw new InterruptedException(); } }; } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); dialog.setSorter(new ResourceSorter(ResourceSorter.NAME)); if (dialog.open() == Window.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { TabItem tabItem= (TabItem) widget; BuildPathBasePage newPage= (BuildPathBasePage) tabItem.getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; fPageIndex= tabItem.getParent().getSelectionIndex(); } } }
32,378
Bug 32378 Java Build Path properties page [general issue] [build path]
The Java Build Path properties page should refresh when it is opened and should also have an apply button. We are running into problems because we also contribute a properties page to Java projects that edits the build properties and it is unclear what the current state of the build path is. There are two main problems. First, the user opens our page, modifies and applies the change and then goes to the Java Build Path page where the change is not available because it is not refreshed. At this point if the user modifies the Java Build Path page and exits. The changes he first made are wiped out and replaced with current state of the Java Build Path page. Second, the user opens the Java Build Path page and modifies some information and then goes to our page; these changes are unavaible. It would be nice if the user could have applied the changes from the Java Build Path page to make them avaible to our page. We are able to handle this state (in English at least) because our page comes after the Java Build path page and is saved last. Ultimatly, the best solution would be to create an in memory copy of the Build Properties that both pages could use without these synchronization issues.
closed fixed
a0ed6d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T15:34:07Z
2003-02-20T19:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.net.URL; import java.util.ArrayList; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClasspathContainer; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; public class CPListElement { public static final String SOURCEATTACHMENT= "sourcepath"; //$NON-NLS-1$ public static final String SOURCEATTACHMENTROOT= "rootpath"; //$NON-NLS-1$ public static final String JAVADOC= "javadoc"; //$NON-NLS-1$ public static final String OUTPUT= "output"; //$NON-NLS-1$ public static final String EXCLUSION= "exclusion"; //$NON-NLS-1$ private IJavaProject fProject; private int fEntryKind; private IPath fPath; private IResource fResource; private boolean fIsExported; private boolean fIsMissing; private CPListElement fParentContainer; private IClasspathEntry fCachedEntry; private ArrayList fChildren; public CPListElement(IJavaProject project, int entryKind, IPath path, IResource res) { fProject= project; fEntryKind= entryKind; fPath= path; fChildren= new ArrayList(); fResource= res; fIsExported= false; fIsMissing= false; fCachedEntry= null; fParentContainer= null; switch (entryKind) { case IClasspathEntry.CPE_SOURCE: createAttributeElement(OUTPUT, null); createAttributeElement(EXCLUSION, new Path[0]); break; case IClasspathEntry.CPE_LIBRARY: case IClasspathEntry.CPE_VARIABLE: createAttributeElement(SOURCEATTACHMENT, null); createAttributeElement(JAVADOC, null); break; case IClasspathEntry.CPE_PROJECT: break; case IClasspathEntry.CPE_CONTAINER: try { IClasspathContainer container= JavaCore.getClasspathContainer(fPath, fProject); if (container != null) { IClasspathEntry[] entries= container.getClasspathEntries(); for (int i= 0; i < entries.length; i++) { CPListElement curr= createFromExisting(entries[i], fProject); curr.setParentContainer(this); fChildren.add(curr); } } } catch (JavaModelException e) { } break; default: } } public IClasspathEntry getClasspathEntry() { if (fCachedEntry == null) { fCachedEntry= newClasspathEntry(); } return fCachedEntry; } private IClasspathEntry newClasspathEntry() { switch (fEntryKind) { case IClasspathEntry.CPE_SOURCE: IPath outputLocation= (IPath) getAttribute(OUTPUT); IPath[] exclusionPattern= (IPath[]) getAttribute(EXCLUSION); return JavaCore.newSourceEntry(fPath, exclusionPattern, outputLocation); case IClasspathEntry.CPE_LIBRARY: IPath attach= (IPath) getAttribute(SOURCEATTACHMENT); return JavaCore.newLibraryEntry(fPath, attach, null, isExported()); case IClasspathEntry.CPE_PROJECT: return JavaCore.newProjectEntry(fPath, isExported()); case IClasspathEntry.CPE_CONTAINER: return JavaCore.newContainerEntry(fPath, isExported()); case IClasspathEntry.CPE_VARIABLE: IPath varAttach= (IPath) getAttribute(SOURCEATTACHMENT); return JavaCore.newVariableEntry(fPath, varAttach, null, isExported()); default: return null; } } /** * Gets the classpath entry path. * @see IClasspathEntry#getPath() */ public IPath getPath() { return fPath; } /** * Gets the classpath entry kind. * @see IClasspathEntry#getEntryKind() */ public int getEntryKind() { return fEntryKind; } /** * Entries without resource are either non existing or a variable entry * External jars do not have a resource */ public IResource getResource() { return fResource; } public CPListElementAttribute setAttribute(String key, Object value) { CPListElementAttribute attribute= findAttributeElement(key); if (attribute == null) { return null; } attribute.setValue(value); attributeChanged(key); return attribute; } private CPListElementAttribute findAttributeElement(String key) { for (int i= 0; i < fChildren.size(); i++) { Object curr= fChildren.get(i); if (curr instanceof CPListElementAttribute) { CPListElementAttribute elem= (CPListElementAttribute) curr; if (key.equals(elem.getKey())) { return elem; } } } return null; } public Object getAttribute(String key) { CPListElementAttribute attrib= findAttributeElement(key); if (attrib != null) { return attrib.getValue(); } return null; } private void createAttributeElement(String key, Object value) { fChildren.add(new CPListElementAttribute(this, key, value)); } public Object[] getChildren(boolean hideOutputFolder) { if (hideOutputFolder && fEntryKind == IClasspathEntry.CPE_SOURCE) { return new Object[] { findAttributeElement(EXCLUSION) }; } return fChildren.toArray(); } private void setParentContainer(CPListElement element) { fParentContainer= element; } public CPListElement getParentContainer() { return fParentContainer; } private void attributeChanged(String key) { fCachedEntry= null; } /* * @see Object#equals(java.lang.Object) */ public boolean equals(Object other) { if (other != null && other.getClass().equals(getClass())) { CPListElement elem= (CPListElement)other; return elem.fEntryKind == fEntryKind && elem.fPath.equals(fPath); } return false; } /* * @see Object#hashCode() */ public int hashCode() { return fPath.hashCode() + fEntryKind; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { return getClasspathEntry().toString(); } /** * Returns if a entry is missing. * @return Returns a boolean */ public boolean isMissing() { return fIsMissing; } /** * Sets the 'missing' state of the entry. */ public void setIsMissing(boolean isMissing) { fIsMissing= isMissing; } /** * Returns if a entry is exported (only applies to libraries) * @return Returns a boolean */ public boolean isExported() { return fIsExported; } /** * Sets the export state of the entry. */ public void setExported(boolean isExported) { if (isExported != fIsExported) { fIsExported = isExported; attributeChanged(null); } } /** * Gets the project. * @return Returns a IJavaProject */ public IJavaProject getJavaProject() { return fProject; } public static CPListElement createFromExisting(IClasspathEntry curr, IJavaProject project) { IPath path= curr.getPath(); IWorkspaceRoot root= project.getProject().getWorkspace().getRoot(); // get the resource IResource res= null; boolean isMissing= false; URL javaDocLocation= null; switch (curr.getEntryKind()) { case IClasspathEntry.CPE_CONTAINER: res= null; try { isMissing= (JavaCore.getClasspathContainer(path, project) == null); } catch (JavaModelException e) { isMissing= true; } break; case IClasspathEntry.CPE_VARIABLE: IPath resolvedPath= JavaCore.getResolvedVariablePath(path); res= null; isMissing= root.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile(); javaDocLocation= JavaUI.getLibraryJavadocLocation(resolvedPath); break; case IClasspathEntry.CPE_LIBRARY: res= root.findMember(path); if (res == null) { if (!ArchiveFileFilter.isArchivePath(path)) { if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK() && root.getProject(path.segment(0)).exists()) { res= root.getFolder(path); } } isMissing= !path.toFile().isFile(); // look for external JARs } javaDocLocation= JavaUI.getLibraryJavadocLocation(path); break; case IClasspathEntry.CPE_SOURCE: path= path.removeTrailingSeparator(); res= root.findMember(path); if (res == null) { if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) { res= root.getFolder(path); } isMissing= true; } break; case IClasspathEntry.CPE_PROJECT: res= root.findMember(path); isMissing= (res == null); break; } CPListElement elem= new CPListElement(project, curr.getEntryKind(), path, res); elem.setExported(curr.isExported()); elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath()); elem.setAttribute(JAVADOC, javaDocLocation); elem.setAttribute(OUTPUT, curr.getOutputLocation()); elem.setAttribute(EXCLUSION, curr.getExclusionPatterns()); if (project.exists()) { elem.setIsMissing(isMissing); } return elem; } }
32,378
Bug 32378 Java Build Path properties page [general issue] [build path]
The Java Build Path properties page should refresh when it is opened and should also have an apply button. We are running into problems because we also contribute a properties page to Java projects that edits the build properties and it is unclear what the current state of the build path is. There are two main problems. First, the user opens our page, modifies and applies the change and then goes to the Java Build Path page where the change is not available because it is not refreshed. At this point if the user modifies the Java Build Path page and exits. The changes he first made are wiped out and replaced with current state of the Java Build Path page. Second, the user opens the Java Build Path page and modifies some information and then goes to our page; these changes are unavaible. It would be nice if the user could have applied the changes from the Java Build Path page to make them avaible to our page. We are able to handle this state (in English at least) because our page comes after the Java Build path page and is saved last. Ultimatly, the best solution would be to create an in memory copy of the Build Properties that both pages could use without these synchronization issues.
closed fixed
a0ed6d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T15:34:07Z
2003-02-20T19:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/JavaCapabilityConfigurationPage.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * Standard wizard page for creating new Java projects. This page can be used in * project creation wizards. The page shows UI to configure the project with a Java * build path and output location. On finish the page will also configure the Java nature. * <p> * This is a replacement for <code>NewJavaProjectWizardPage</code> with a cleaner API. * </p> * * @since 2.0 */ public class JavaCapabilityConfigurationPage extends NewElementWizardPage { private static final String PAGE_NAME= "JavaCapabilityConfigurationPage"; //$NON-NLS-1$ private IJavaProject fJavaProject; private BuildPathsBlock fBuildPathsBlock; /** * Creates a wizard page that can be used in a Java project creation wizard. * It contains UI to configure a the classpath and the output folder. * * <p> * After constructing, a call to <code>init</code> is required * </p> */ public JavaCapabilityConfigurationPage() { super(PAGE_NAME); fJavaProject= null; setTitle(NewWizardMessages.getString("JavaCapabilityConfigurationPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("JavaCapabilityConfigurationPage.description")); //$NON-NLS-1$ IStatusChangeListener listener= new IStatusChangeListener() { public void statusChanged(IStatus status) { updateStatus(status); } }; fBuildPathsBlock= new BuildPathsBlock(listener, 0); } /** * Initializes the page with the project and default classpaths. * <p> * The default classpath entries must correspond the the given project. * </p> * <p> * The caller of this method is responsible for creating the underlying project. The page will create the output, * source and library folders if required. * </p> * <p> * The project does not have to exist at the time of initialization, but must exist when executing the runnable * obtained by <code>getRunnable()</code>. * </p> * @param jproject The Java project. * @param defaultOutputLocation The default classpath entries or <code>null</code> to let the page choose the default * @param defaultEntries The folder to be taken as the default output path or <code>null</code> to let the page choose the default * @param defaultsOverrideExistingClasspath If set to <code>true</code>, an existing '.classpath' file is ignored. If set to <code>false</code> * the given default classpath and output location is only used if no '.classpath' exists. */ public void init(IJavaProject jproject, IPath defaultOutputLocation, IClasspathEntry[] defaultEntries, boolean defaultsOverrideExistingClasspath) { if (!defaultsOverrideExistingClasspath && jproject.exists() && jproject.getProject().getFile(".classpath").exists()) { //$NON-NLS-1$ defaultOutputLocation= null; defaultEntries= null; } fBuildPathsBlock.init(jproject, defaultOutputLocation, defaultEntries); fJavaProject= jproject; } /* (non-Javadoc) * @see WizardPage#createControl */ public void createControl(Composite parent) { Control control= fBuildPathsBlock.createControl(parent); setControl(control); Dialog.applyDialogFont(control); WorkbenchHelp.setHelp(control, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE); } /** * Returns the currently configured output location. Note that the returned path * might not be a valid path. * * @return the currently configured output location */ public IPath getOutputLocation() { return fBuildPathsBlock.getOutputLocation(); } /** * Returns the currently configured classpath. Note that the classpath might * not be valid. * * @return the currently configured classpath */ public IClasspathEntry[] getRawClassPath() { return fBuildPathsBlock.getRawClassPath(); } /** * Returns the Java project that was passed in <code>init</code> or <code>null</code> if the * page has not been initialized yet. * * @return the managed Java project or <code>null</code> */ public IJavaProject getJavaProject() { return fJavaProject; } /** * Returns the runnable that will create the Java project or <code>null</code> if the page has * not been initialized. The runnable sets the project's classpath and output location to the values * configured in the page and adds the Java nature if not set yet. The method requires that the * project is created and opened. * * @return the runnable that creates the new Java project */ public IRunnableWithProgress getRunnable() { if (getJavaProject() != null) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { configureJavaProject(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } return null; } /** * Helper method to create and open a IProject . The project location * is configured. No natures are added. * * @param monitor a progress monitor to report progress or <code>null</code> if * progress reporting is not desired * @since 2.1 */ public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { BuildPathsBlock.createProject(project, locationPath, monitor); } /** * Adds the Java nature to the project (if not set yet) and configures the build classpath. * * @param monitor a progress monitor to report progress or <code>null</code> if * progress reporting is not desired */ public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } int nSteps= 6; monitor.beginTask(NewWizardMessages.getString("JavaCapabilityConfigurationPage.op_desc_java"), nSteps); //$NON-NLS-1$ try { IProject project= getJavaProject().getProject(); BuildPathsBlock.addJavaNature(project, new SubProgressMonitor(monitor, 1)); fBuildPathsBlock.configureJavaProject(new SubProgressMonitor(monitor, 5)); } finally { monitor.done(); } } }
32,378
Bug 32378 Java Build Path properties page [general issue] [build path]
The Java Build Path properties page should refresh when it is opened and should also have an apply button. We are running into problems because we also contribute a properties page to Java projects that edits the build properties and it is unclear what the current state of the build path is. There are two main problems. First, the user opens our page, modifies and applies the change and then goes to the Java Build Path page where the change is not available because it is not refreshed. At this point if the user modifies the Java Build Path page and exits. The changes he first made are wiped out and replaced with current state of the Java Build Path page. Second, the user opens the Java Build Path page and modifies some information and then goes to our page; these changes are unavaible. It would be nice if the user could have applied the changes from the Java Build Path page to make them avaible to our page. We are able to handle this state (in English at least) because our page comes after the Java Build path page and is saved last. Ultimatly, the best solution would be to create an in memory copy of the Build Properties that both pages could use without these synchronization issues.
closed fixed
a0ed6d5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T15:34:07Z
2003-02-20T19:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.Assert; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * Standard wizard page for creating new Java projects. This page can be used in * project creation wizards for projects and will configure the project with the * Java nature. This page also allows the user to configure the Java project's * output location for class files generated by the Java builder. * <p> * Whenever possible clients should use the class <code>JavaCapabilityConfigurationPage * </code> in favour of this class. * </p> */ public class NewJavaProjectWizardPage extends NewElementWizardPage { private static final String PAGE_NAME= "NewJavaProjectWizardPage"; //$NON-NLS-1$ private WizardNewProjectCreationPage fMainPage; private IPath fOutputLocation; private IClasspathEntry[] fClasspathEntries; private BuildPathsBlock fBuildPathsBlock; private boolean fProjectModified; /** * Creates a Java project wizard creation page. * <p> * The Java project wizard reads project name and location from the main page. * </p> * * @param root the workspace root * @param mainpage the main page of the wizard */ public NewJavaProjectWizardPage(IWorkspaceRoot root, WizardNewProjectCreationPage mainpage) { super(PAGE_NAME); setTitle(NewWizardMessages.getString("NewJavaProjectWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewJavaProjectWizardPage.description")); //$NON-NLS-1$ fMainPage= mainpage; IStatusChangeListener listener= new IStatusChangeListener() { public void statusChanged(IStatus status) { updateStatus(status); } }; fBuildPathsBlock= new BuildPathsBlock(listener, 0); fProjectModified= true; fOutputLocation= null; fClasspathEntries= null; } /** * Sets the default output location to be used for the new Java project. * This is the path of the folder (with the project) into which the Java builder * will generate binary class files corresponding to the project's Java source * files. * <p> * The wizard will create this folder if required. * </p> * <p> * The default classpath will be applied when <code>initBuildPaths</code> is * called. This is done automatically when the page becomes visible and * the project or the default paths have changed. * </p> * * @param path the folder to be taken as the default output path */ public void setDefaultOutputFolder(IPath path) { fOutputLocation= path; setProjectModified(); } /** * Sets the default classpath to be used for the new Java project. * <p> * The caller of this method is responsible for creating the classpath entries * for the <code>IJavaProject</code> that corresponds to the created project. * The caller is responsible for creating any new folders that might be mentioned * on the classpath. * </p> * <p> * The default output location will be applied when <code>initBuildPaths</code> is * called. This is done automatically when the page becomes visible and * the project or the default paths have changed. * </p> * * @param entries the default classpath entries * @param appendDefaultJRE <code>true</code> a variable entry for the * default JRE (specified in the preferences) will be added to the classpath. */ public void setDefaultClassPath(IClasspathEntry[] entries, boolean appendDefaultJRE) { if (entries != null && appendDefaultJRE) { IClasspathEntry[] jreEntry= NewJavaProjectPreferencePage.getDefaultJRELibrary(); IClasspathEntry[] newEntries= new IClasspathEntry[entries.length + jreEntry.length]; System.arraycopy(entries, 0, newEntries, 0, entries.length); System.arraycopy(jreEntry, 0, newEntries, entries.length, jreEntry.length); entries= newEntries; } fClasspathEntries= entries; setProjectModified(); } /** * Sets the project state to modified. Doing so will initialize the page * the next time it becomes visible. * * @since 2.0 */ public void setProjectModified() { fProjectModified= true; } /** * Returns the project handle. Subclasses should override this * method if they don't provide a main page or if they provide * their own main page implementation. * * @return the project handle */ protected IProject getProjectHandle() { Assert.isNotNull(fMainPage); return fMainPage.getProjectHandle(); } /** * Returns the project locaction path. Subclasses should override this * method if they don't provide a main page or if they provide * their own main page implementation. * * @return the project location path */ protected IPath getLocationPath() { Assert.isNotNull(fMainPage); return fMainPage.getLocationPath(); } /** * Returns the Java project handle by converting the result of * <code>getProjectHandle()</code> into a Java project. * * @return the Java project handle * @see #getProjectHandle() */ public IJavaProject getNewJavaProject() { return JavaCore.create(getProjectHandle()); } /* (non-Javadoc) * @see WizardPage#createControl */ public void createControl(Composite parent) { Control control= fBuildPathsBlock.createControl(parent); setControl(control); Dialog.applyDialogFont(control); WorkbenchHelp.setHelp(control, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE); } /** * Forces the initialization of the Java project page. Default classpath or buildpath * will be used if set. The initialization should only be performed when the project * or default paths have changed. Toggeling back and forward the pages without * changes should not re-initialize the page, as changes from the user will be * overwritten. * * @since 2.0 */ protected void initBuildPaths() { fBuildPathsBlock.init(getNewJavaProject(), fOutputLocation, fClasspathEntries); } /** * Extend this method to set a user defined default classpath or output location. * The method <code>initBuildPaths</code> is called when the page becomes * visible the first time or the project or the default paths have changed. * * @param visible if <code>true</code> the page becomes visible; otherwise * it becomes invisible */ public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { // evaluate if a initialization is required if (fProjectModified || isNewProjectHandle()) { // only initialize the project when needed initBuildPaths(); fProjectModified= false; } } } private boolean isNewProjectHandle() { IProject oldProject= fBuildPathsBlock.getJavaProject().getProject(); return !oldProject.equals(getProjectHandle()); } /** * Returns the currently configured output location. Note that the returned path * might not be valid. * * @return the configured output location * * @since 2.0 */ public IPath getOutputLocation() { return fBuildPathsBlock.getOutputLocation(); } /** * Returns the currently configured classpath. Note that the classpath might * not be valid. * * @return the configured classpath * * @since 2.0 */ public IClasspathEntry[] getRawClassPath() { return fBuildPathsBlock.getRawClassPath(); } /** * Returns the runnable that will create the Java project. The runnable will create * and open the project if needed. The runnable will add the Java nature to the * project, and set the project's classpath and output location. * <p> * To create the new java project, execute this runnable * </p> * * @return the runnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("NewJavaProjectWizardPage.op_desc"), 10); //$NON-NLS-1$ // initialize if needed if (fProjectModified || isNewProjectHandle()) { initBuildPaths(); } // create the project try { BuildPathsBlock.createProject(getProjectHandle(), getLocationPath(), new SubProgressMonitor(monitor, 2)); BuildPathsBlock.addJavaNature(getProjectHandle(), new SubProgressMonitor(monitor, 2)); fBuildPathsBlock.configureJavaProject(new SubProgressMonitor(monitor, 6)); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } }
37,513
Bug 37513 [misc] Outline tool-tip window should remember size and position
It would be very nice if the Outline window (accessible from Ctrl+O or the menu "Navigate|Show Outline") would remember its size and position like most other windows in Eclipse do.
resolved fixed
54d3604
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T16:39:44Z
2003-05-12T17:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/AbstractInformationControl.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.FontMetrics; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.TreeItem; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlExtension; import org.eclipse.jface.text.IInformationControlExtension2; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.commands.ICommand; import org.eclipse.ui.commands.ICommandManager; import org.eclipse.ui.commands.IKeySequenceBinding; import org.eclipse.ui.keys.KeySequence; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IParent; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.OpenActionUtil; import org.eclipse.jdt.internal.ui.util.StringMatcher; /** * Abstract class for Show hierarchy in light-weight controls. * * @since 2.1 */ public abstract class AbstractInformationControl implements IInformationControl, IInformationControlExtension, IInformationControlExtension2, DisposeListener { /** * The NamePatternFilter selects the elements which * match the given string patterns. * * @since 2.0 */ protected class NamePatternFilter extends ViewerFilter { public NamePatternFilter() { } /* (non-Javadoc) * Method declared on ViewerFilter. */ public boolean select(Viewer viewer, Object parentElement, Object element) { StringMatcher matcher= getMatcher(); if (matcher == null || !(viewer instanceof TreeViewer)) return true; TreeViewer treeViewer= (TreeViewer) viewer; String matchName= ((ILabelProvider) treeViewer.getLabelProvider()).getText(element); if (matchName != null && matcher.match(matchName)) return true; return hasUnfilteredChild(treeViewer, element); } private boolean hasUnfilteredChild(TreeViewer viewer, Object element) { if (element instanceof IParent) { Object[] children= ((ITreeContentProvider) viewer.getContentProvider()).getChildren(element); for (int i= 0; i < children.length; i++) if (select(viewer, element, children[i])) return true; } return false; } } private static class BorderFillLayout extends Layout { /** The border widths. */ final int fBorderSize; /** * Creates a fill layout with a border. */ public BorderFillLayout(int borderSize) { if (borderSize < 0) throw new IllegalArgumentException(); fBorderSize= borderSize; } /** * Returns the border size. */ public int getBorderSize() { return fBorderSize; } /* * @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) { 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); } } minSize.x += fBorderSize * 2 + RIGHT_MARGIN; minSize.y += fBorderSize * 2; return minSize; } /* * @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); 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); child.setLocation(fBorderSize, fBorderSize); } } } } /** Border thickness in pixels. */ private static final int BORDER= 1; /** Right margin in pixels. */ 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; /** The control height constraint */ //private int fMaxHeight= -1; /** The current string matcher */ private StringMatcher fStringMatcher; private ICommand fInvokingCommand; private Label fStatusField; private Font fStatusTextFont; // private Controle fFocusWidget; private KeySequence[] fInvokingCommandKeySequences; /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget * @param invokingCommandId the id of the command that invoked this control or <code>null</code> * @param showStatusField <code>true</code> iff the control has a status field at the bottom */ public AbstractInformationControl(Shell parent, int shellStyle, int treeStyle, String invokingCommandId, boolean showStatusField) { if (invokingCommandId != null) { ICommandManager commandManager= PlatformUI.getWorkbench().getCommandSupport().getCommandManager(); fInvokingCommand= commandManager.getCommand(invokingCommandId); if (fInvokingCommand != null && !fInvokingCommand.isDefined()) fInvokingCommand= null; } 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.setLayout(layout); fComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fFilterText= createFilterText(fComposite); fTreeViewer= createTreeViewer(fComposite, treeStyle); if (showStatusField) createStatusField(fComposite); final Tree tree= fTreeViewer.getTree(); tree.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.character == 0x1B) // ESC dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); tree.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { // do nothing } public void widgetDefaultSelected(SelectionEvent e) { gotoSelectedElement(); } }); tree.addMouseMoveListener(new MouseMoveListener() { TreeItem fLastItem= null; public void mouseMove(MouseEvent e) { if (tree.equals(e.getSource())) { Object o= tree.getItem(new Point(e.x, e.y)); if (o instanceof TreeItem) { if (!o.equals(fLastItem)) { fLastItem= (TreeItem)o; tree.setSelection(new TreeItem[] { fLastItem }); } else if (e.y < tree.getItemHeight() / 4) { // Scroll up Point p= tree.toDisplay(e.x, e.y); Item item= fTreeViewer.scrollUp(p.x, p.y); if (item instanceof TreeItem) { fLastItem= (TreeItem)item; tree.setSelection(new TreeItem[] { fLastItem }); } } else if (e.y > tree.getBounds().height - tree.getItemHeight() / 4) { // Scroll down Point p= tree.toDisplay(e.x, e.y); Item item= fTreeViewer.scrollDown(p.x, p.y); if (item instanceof TreeItem) { fLastItem= (TreeItem)item; tree.setSelection(new TreeItem[] { fLastItem }); } } } } } }); tree.addMouseListener(new MouseAdapter() { public void mouseUp(MouseEvent e) { if (tree.getSelectionCount() < 1) return; if (e.button != 1) return; if (tree.equals(e.getSource())) { Object o= tree.getItem(new Point(e.x, e.y)); TreeItem selection= tree.getSelection()[0]; if (selection.equals(o)) gotoSelectedElement(); } } }); int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER; fShell.setLayout(new BorderFillLayout(border)); fComposite.setTabList(new Control[] {fFilterText, fTreeViewer.getTree()}); setInfoSystemColor(); installFilter(); addDisposeListener(this); } /** * Creates a tree information control with the given shell as parent. The given * styles are applied to the shell and the tree widget. * * @param parent the parent shell * @param shellStyle the additional styles for the shell * @param treeStyle the additional styles for the tree widget */ public AbstractInformationControl(Shell parent, int shellStyle, int treeStyle) { this(parent, shellStyle, treeStyle, null, false); } protected abstract TreeViewer createTreeViewer(Composite parent, int style); protected TreeViewer getTreeViewer() { return fTreeViewer; } protected Text getFilterText() { return fFilterText; } protected Text createFilterText(Composite parent) { fFilterText= new Text(parent, SWT.FLAT); GridData data= new GridData(); GC gc= new GC(parent); gc.setFont(parent.getFont()); FontMetrics fontMetrics= gc.getFontMetrics(); gc.dispose(); data.heightHint= 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 gotoSelectedElement(); if (e.keyCode == SWT.ARROW_DOWN) fTreeViewer.getTree().setFocus(); if (e.keyCode == SWT.ARROW_UP) fTreeViewer.getTree().setFocus(); if (e.character == 0x1B) // ESC dispose(); } public void keyReleased(KeyEvent e) { // do nothing } }); // Horizontal separator line Label separator= new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); return fFilterText; } private void createStatusField(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(1, false); layout.marginHeight= 0; layout.marginWidth= 0; composite.setLayout(layout); composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Horizontal separator line Label separator= new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL | SWT.LINE_DOT); separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // Status field label fStatusField= new Label(parent, SWT.RIGHT); fStatusField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); fStatusField.setText(getStatusFieldText()); Font font= fStatusField.getFont(); Display display= parent.getDisplay(); FontData[] fontDatas= font.getFontData(); for (int i= 0; i < fontDatas.length; i++) fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); fStatusTextFont= new Font(display, fontDatas); fStatusField.setFont(fStatusTextFont); fStatusField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); // fStatusField= new Button(parent, SWT.CENTER | SWT.FLAT); // fStatusField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); // fStatusField.setText(getStatusFieldText()); // Font font= fStatusField.getFont(); // Display display= parent.getDisplay(); // FontData[] fontDatas= font.getFontData(); // for (int i= 0; i < fontDatas.length; i++) // fontDatas[i].setHeight(fontDatas[i].getHeight() * 9 / 10); // fStatusTextFont= new Font(display, fontDatas); // fStatusField.setFont(fStatusTextFont); // // getFilterText().addFocusListener(new FocusAdapter() { // /** // * {@inheritDoc} // */ // public void focusGained(FocusEvent e) { // fFocusWidget= getFilterText(); // } // }); // fTreeViewer.getTree().addFocusListener(new FocusAdapter() { // /** // * {@inheritDoc} // */ // public void focusGained(FocusEvent e) { // fFocusWidget= fTreeViewer.getTree(); // } // }); // // fStatusField.addSelectionListener(new SelectionAdapter() { // /** // * {@inheritDoc} // */ // public void widgetSelected(SelectionEvent e) { // handleStatusFieldClicked(); // if (fFocusWidget != null) // fFocusWidget.setFocus(); // else // getFilterText().setFocus(); // } // }); // // // Regarding the color see bug 41128 // fStatusField.setForeground(display.getSystemColor(SWT.COLOR_WIDGET_DARK_SHADOW)); } protected void updateStatusFieldText() { if (fStatusField != null) fStatusField.setText(getStatusFieldText()); } /** * Handles click in status field. * <p> * Default does nothing. * </p> */ protected void handleStatusFieldClicked() { } protected String getStatusFieldText() { return ""; //$NON-NLS-1$ } private void setInfoSystemColor() { Display display= fShell.getDisplay(); setForegroundColor(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND)); setBackgroundColor(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND)); } private void installFilter() { fFilterText.setText(""); //$NON-NLS-1$ fFilterText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { String text= ((Text) e.widget).getText(); int length= text.length(); if (length > 0 && text.charAt(length -1 ) != '*') { text= text + '*'; } setMatcherString(text); } }); } /** * The string matcher has been modified. The default implementation * refreshes the view and selects the first macthed element */ protected void stringMatcherUpdated() { // refresh viewer to refilter fTreeViewer.getControl().setRedraw(false); fTreeViewer.refresh(); fTreeViewer.expandAll(); selectFirstMatch(); fTreeViewer.getControl().setRedraw(true); } /** * Sets the patterns to filter out for the receiver. * <p> * The following characters have special meaning: * ? => any character * * => any string * </p> */ protected void setMatcherString(String pattern) { if (pattern.length() == 0) { fStringMatcher= null; } else { boolean ignoreCase= pattern.toLowerCase().equals(pattern); fStringMatcher= new StringMatcher(pattern, ignoreCase, false); } stringMatcherUpdated(); } protected StringMatcher getMatcher() { return fStringMatcher; } /** * Implementers can modify */ protected Object getSelectedElement() { return ((IStructuredSelection) fTreeViewer.getSelection()).getFirstElement(); } private void gotoSelectedElement() { Object selectedElement= getSelectedElement(); if (selectedElement != null) { try { dispose(); OpenActionUtil.open(selectedElement, true); } catch (CoreException ex) { JavaPlugin.log(ex); } } } /** * Selects the first element in the tree which * matches the current filter pattern. */ protected void selectFirstMatch() { Tree tree= fTreeViewer.getTree(); Object element= findElement(tree.getItems()); if (element != null) fTreeViewer.setSelection(new StructuredSelection(element), true); else fTreeViewer.setSelection(StructuredSelection.EMPTY); } private IJavaElement findElement(TreeItem[] items) { 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); if (fStringMatcher.match(label)) return element; } element= findElement(items[i].getItems()); if (element != null) return element; } return null; } /** * {@inheritDoc} */ public void setInformation(String information) { // this method is ignored, see IInformationControlExtension2 } /** * {@inheritDoc} */ public abstract void setInput(Object information); protected void inputChanged(Object newInput, Object newSelection) { fFilterText.setText(""); //$NON-NLS-1$ fTreeViewer.setInput(newInput); if (newSelection != null) { fTreeViewer.setSelection(new StructuredSelection(newSelection)); } } /** * {@inheritDoc} */ public void setVisible(boolean visible) { fShell.setVisible(visible); } /** * {@inheritDoc} */ public final void dispose() { if (fShell != null && !fShell.isDisposed()) fShell.dispose(); else widgetDisposed(null); } /** * {@inheritDoc} * @param event can be null * <p> * Subclasses may extend. * </p> */ public void widgetDisposed(DisposeEvent event) { if (fStatusTextFont != null && !fStatusTextFont.isDisposed()) fStatusTextFont.dispose(); fShell= null; fTreeViewer= null; fComposite= null; fFilterText= null; fStatusTextFont= null; } /** * {@inheritDoc} */ public boolean hasContents() { return fTreeViewer != null && fTreeViewer.getInput() != null; } /** * {@inheritDoc} */ public void setSizeConstraints(int maxWidth, int maxHeight) { //fMaxWidth= maxWidth; //fMaxHeight= maxHeight; } /** * {@inheritDoc} */ public Point computeSizeHint() { return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT); } /** * {@inheritDoc} */ 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); } /** * {@inheritDoc} */ public void setSize(int width, int height) { fShell.setSize(width, height); } /** * {@inheritDoc} */ public void addDisposeListener(DisposeListener listener) { fShell.addDisposeListener(listener); } /** * {@inheritDoc} */ public void removeDisposeListener(DisposeListener listener) { fShell.removeDisposeListener(listener); } /** * {@inheritDoc} */ public void setForegroundColor(Color foreground) { fTreeViewer.getTree().setForeground(foreground); fFilterText.setForeground(foreground); fComposite.setForeground(foreground); if (fStatusField != null) fStatusField.getParent().setForeground(foreground); } /** * {@inheritDoc} */ public void setBackgroundColor(Color background) { fTreeViewer.getTree().setBackground(background); fFilterText.setBackground(background); fComposite.setBackground(background); if (fStatusField != null) { fStatusField.setBackground(background); fStatusField.getParent().setBackground(background); } } /** * {@inheritDoc} */ public boolean isFocusControl() { return fTreeViewer.getControl().isFocusControl() || fFilterText.isFocusControl(); } /** * {@inheritDoc} */ public void setFocus() { fShell.forceFocus(); fFilterText.setFocus(); } /** * {@inheritDoc} */ public void addFocusListener(FocusListener listener) { fShell.addFocusListener(listener); } /** * {@inheritDoc} */ public void removeFocusListener(FocusListener listener) { fShell.removeFocusListener(listener); } final protected ICommand getInvokingCommand() { return fInvokingCommand; } final protected KeySequence[] getInvokingCommandKeySequences() { if (getInvokingCommand() != null) { List list= getInvokingCommand().getKeySequenceBindings(); if (!list.isEmpty()) { fInvokingCommandKeySequences= new KeySequence[list.size()]; for (int i= 0; i < fInvokingCommandKeySequences.length; i++) { fInvokingCommandKeySequences[i]= ((IKeySequenceBinding) list.get(i)).getKeySequence(); } return fInvokingCommandKeySequences; } } return null; } }
37,513
Bug 37513 [misc] Outline tool-tip window should remember size and position
It would be very nice if the Outline window (accessible from Ctrl+O or the menu "Navigate|Show Outline") would remember its size and position like most other windows in Eclipse do.
resolved fixed
54d3604
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T16:39:44Z
2003-05-12T17:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/text/JavaSourceViewerConfiguration.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.text; import java.util.Vector; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DefaultTextDoubleClickStrategy; import org.eclipse.jface.text.IAutoIndentStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.ITextDoubleClickStrategy; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.formatter.ContentFormatter2; import org.eclipse.jface.text.formatter.IContentFormatter; import org.eclipse.jface.text.formatter.IFormattingStrategy; import org.eclipse.jface.text.information.IInformationPresenter; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.presentation.IPresentationReconciler; import org.eclipse.jface.text.presentation.PresentationReconciler; import org.eclipse.jface.text.reconciler.IReconciler; import org.eclipse.jface.text.rules.DefaultDamagerRepairer; import org.eclipse.jface.text.rules.RuleBasedScanner; import org.eclipse.jface.text.source.IAnnotationHover; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaAnnotationHover; import org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy; import org.eclipse.jdt.internal.ui.text.JavaElementProvider; import org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl; import org.eclipse.jdt.internal.ui.text.JavaReconciler; import org.eclipse.jdt.internal.ui.text.comment.CommentFormattingStrategy; import org.eclipse.jdt.internal.ui.text.comment.JavaDocRegion; import org.eclipse.jdt.internal.ui.text.comment.JavaSnippetFormattingStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor; import org.eclipse.jdt.internal.ui.text.java.JavaDoubleClickSelector; import org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaStringAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.java.JavaStringDoubleClickSelector; import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor; import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy; import org.eclipse.jdt.internal.ui.text.java.hover.JavaInformationProvider; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocCompletionProcessor; import org.eclipse.jdt.internal.ui.text.spelling.WordCompletionProcessor; import org.eclipse.jdt.internal.ui.typehierarchy.HierarchyInformationControl; /** * Configuration for a source viewer which shows Java code. * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> */ public class JavaSourceViewerConfiguration 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; private JavaTextTools fJavaTextTools; private ITextEditor fTextEditor; private String fDocumentPartitioning; /** * Creates a new Java source viewer configuration for viewers in the given editor * using the given Java tools and the specified document partitioning. * * @param tools the Java text tools to be used * @param editor the editor in which the configured viewer(s) will reside * @param partitioning the document partitioning for this configuration * @see JavaTextTools * @since 3.0 */ public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, String partitioning) { fJavaTextTools= tools; fTextEditor= editor; fDocumentPartitioning= partitioning; } /** * 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 */ public JavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor) { this(tools, editor, null); } /** * Returns the Java source code scanner for this configuration. * * @return the Java source code scanner */ protected RuleBasedScanner getCodeScanner() { return fJavaTextTools.getCodeScanner(); } /** * Returns the Java multiline comment scanner for this configuration. * * @return the Java multiline comment scanner * @since 2.0 */ protected RuleBasedScanner getMultilineCommentScanner() { return fJavaTextTools.getMultilineCommentScanner(); } /** * Returns the Java singleline comment scanner for this configuration. * * @return the Java singleline comment scanner * @since 2.0 */ protected RuleBasedScanner getSinglelineCommentScanner() { return fJavaTextTools.getSinglelineCommentScanner(); } /** * Returns the Java string scanner for this configuration. * * @return the Java string scanner * @since 2.0 */ protected RuleBasedScanner getStringScanner() { return fJavaTextTools.getStringScanner(); } /** * Returns the JavaDoc scanner for this configuration. * * @return the JavaDoc scanner */ protected RuleBasedScanner getJavaDocScanner() { return fJavaTextTools.getJavaDocScanner(); } /** * Returns the color manager for this configuration. * * @return the color manager */ protected IColorManager getColorManager() { return fJavaTextTools.getColorManager(); } /** * Returns the editor in which the configured viewer(s) will reside. * * @return the enclosing editor */ protected 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 */ public IPreferenceStore getPreferenceStore() { return fJavaTextTools.getPreferenceStore(); } /* * @see SourceViewerConfiguration#getPresentationReconciler(ISourceViewer) */ public IPresentationReconciler getPresentationReconciler(ISourceViewer sourceViewer) { PresentationReconciler reconciler= new PresentationReconciler(); reconciler.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); DefaultDamagerRepairer dr= new DefaultDamagerRepairer(getCodeScanner()); reconciler.setDamager(dr, IDocument.DEFAULT_CONTENT_TYPE); reconciler.setRepairer(dr, IDocument.DEFAULT_CONTENT_TYPE); dr= new DefaultDamagerRepairer(getJavaDocScanner()); reconciler.setDamager(dr, IJavaPartitions.JAVA_DOC); reconciler.setRepairer(dr, IJavaPartitions.JAVA_DOC); dr= new DefaultDamagerRepairer(getMultilineCommentScanner()); reconciler.setDamager(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); reconciler.setRepairer(dr, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); dr= new DefaultDamagerRepairer(getSinglelineCommentScanner()); reconciler.setDamager(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); reconciler.setRepairer(dr, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); dr= new DefaultDamagerRepairer(getStringScanner()); reconciler.setDamager(dr, IJavaPartitions.JAVA_STRING); reconciler.setRepairer(dr, IJavaPartitions.JAVA_STRING); dr= new DefaultDamagerRepairer(getStringScanner()); reconciler.setDamager(dr, IJavaPartitions.JAVA_CHARACTER); reconciler.setRepairer(dr, IJavaPartitions.JAVA_CHARACTER); return reconciler; } /* * @see SourceViewerConfiguration#getContentAssistant(ISourceViewer) */ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { if (getEditor() != null) { ContentAssistant assistant= new ContentAssistant(); assistant.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); IContentAssistProcessor processor= new JavaCompletionProcessor(getEditor()); assistant.setContentAssistProcessor(processor, 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(processor, IJavaPartitions.JAVA_STRING); assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); processor= new WordCompletionProcessor(); assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); assistant.setContentAssistProcessor(processor, IJavaPartitions.JAVA_STRING); assistant.setContentAssistProcessor(new JavaDocCompletionProcessor(getEditor()), IJavaPartitions.JAVA_DOC); ContentAssistPreference.configure(assistant, getPreferenceStore()); assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE); assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer)); return assistant; } return null; } /* * @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#getAutoIndentStrategy(ISourceViewer, String) */ public IAutoIndentStrategy getAutoIndentStrategy(ISourceViewer sourceViewer, String contentType) { if (IJavaPartitions.JAVA_DOC.equals(contentType) || IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType)) return new JavaDocAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer)); else if (IJavaPartitions.JAVA_STRING.equals(contentType)) return new JavaStringAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer)); return new JavaAutoIndentStrategy(getConfiguredDocumentPartitioning(sourceViewer)); } /* * @see SourceViewerConfiguration#getDoubleClickStrategy(ISourceViewer, String) */ public ITextDoubleClickStrategy getDoubleClickStrategy(ISourceViewer sourceViewer, String contentType) { if (IJavaPartitions.JAVA_DOC.equals(contentType) || IJavaPartitions.JAVA_MULTI_LINE_COMMENT.equals(contentType) || IJavaPartitions.JAVA_SINGLE_LINE_COMMENT.equals(contentType)) return new DefaultTextDoubleClickStrategy(); else if (IJavaPartitions.JAVA_STRING.equals(contentType) || IJavaPartitions.JAVA_CHARACTER.equals(contentType)) return new JavaStringDoubleClickSelector(getConfiguredDocumentPartitioning(sourceViewer)); return new JavaDoubleClickSelector(); } /* * @see SourceViewerConfiguration#getDefaultPrefixes(ISourceViewer, String) * @since 2.0 */ public String[] getDefaultPrefixes(ISourceViewer sourceViewer, String contentType) { return new String[] { "//", "" }; //$NON-NLS-1$ //$NON-NLS-2$ } /* * @see SourceViewerConfiguration#getIndentPrefixes(ISourceViewer, String) */ public String[] getIndentPrefixes(ISourceViewer sourceViewer, String contentType) { Vector vector= new Vector(); // prefix[0] is either '\t' or ' ' x tabWidth, depending on useSpaces int tabWidth= CodeFormatterUtil.getTabWidth(); 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()]); } /* * @see SourceViewerConfiguration#getTabWidth(ISourceViewer) */ public int getTabWidth(ISourceViewer sourceViewer) { return getPreferenceStore().getInt(PREFERENCE_TAB_WIDTH); } /* * @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); } /* * @see SourceViewerConfiguration#getConfiguredTextHoverStateMasks(ISourceViewer, String) * @since 2.1 */ public int[] getConfiguredTextHoverStateMasks(ISourceViewer sourceViewer, String contentType) { JavaEditorTextHoverDescriptor[] hoverDescs= JavaPlugin.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= JavaPlugin.getDefault().getJavaEditorTextHoverDescriptors(); int i= 0; while (i < hoverDescs.length) { if (hoverDescs[i].isEnabled() && hoverDescs[i].getStateMask() == stateMask) return new JavaEditorTextHoverProxy(hoverDescs[i], getEditor()); i++; } return null; } /* * @see SourceViewerConfiguration#getTextHover(ISourceViewer, String) */ public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) { return getTextHover(sourceViewer, contentType, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } /* * @see SourceViewerConfiguration#getConfiguredContentTypes(ISourceViewer) */ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { return new String[] { IDocument.DEFAULT_CONTENT_TYPE, IJavaPartitions.JAVA_DOC, IJavaPartitions.JAVA_MULTI_LINE_COMMENT, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT, IJavaPartitions.JAVA_STRING, IJavaPartitions.JAVA_CHARACTER }; } /* * @see org.eclipse.jface.text.source.SourceViewerConfiguration#getConfiguredDocumentPartitioning(org.eclipse.jface.text.source.ISourceViewer) */ public String getConfiguredDocumentPartitioning(ISourceViewer sourceViewer) { if (fDocumentPartitioning != null) return fDocumentPartitioning; return super.getConfiguredDocumentPartitioning(sourceViewer); } /* * @see SourceViewerConfiguration#getContentFormatter(ISourceViewer) */ public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) { final ContentFormatter2 formatter= new ContentFormatter2(); formatter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); IFormattingStrategy strategy= new JavaFormattingStrategy(sourceViewer); formatter.setFormattingStrategy(strategy); formatter.setFormattingStrategy(strategy, IDocument.DEFAULT_CONTENT_TYPE); formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_DOC); formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); formatter.setFormattingStrategy(new CommentFormattingStrategy(formatter, sourceViewer), IJavaPartitions.JAVA_MULTI_LINE_COMMENT); formatter.setFormattingStrategy(new JavaSnippetFormattingStrategy(sourceViewer), JavaDocRegion.JAVA_SNIPPET_PARTITION); return formatter; } /* * @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)); } }; } /** * Returns the information presenter control creator. The creator is a factory creating the * presenter controls for the given source viewer. This implementation always returns a creator * for <code>DefaultInformationControl</code> instances. * * @param sourceViewer the source viewer to be configured by this configuration * @return an information control creator * @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 <code>JavaOutlineInformationControl</code> 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, final String commandId) { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { int shellStyle= SWT.RESIZE; int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL; return new JavaOutlineInformationControl(parent, shellStyle, treeStyle, commandId); } }; } private IInformationControlCreator getHierarchyPresenterControlCreator(ISourceViewer sourceViewer) { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { int shellStyle= SWT.RESIZE; int treeStyle= SWT.V_SCROLL | SWT.H_SCROLL; return new HierarchyInformationControl(parent, shellStyle, treeStyle); } }; } /* * @see SourceViewerConfiguration#getInformationPresenter(ISourceViewer) * @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, IJavaPartitions.JAVA_DOC); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER); presenter.setSizeConstraints(60, 10, true, true); return presenter; } /** * Returns the outline presenter which will determine and shown * information requested for the current cursor position. * * @param sourceViewer the source viewer to be configured by this configuration * @param doCodeResolve a boolean which specifies whether code resolve should be used to compute the Java element * @return an information presenter * @since 2.1 */ public IInformationPresenter getOutlinePresenter(ISourceViewer sourceViewer, boolean doCodeResolve) { InformationPresenter presenter; if (doCodeResolve) presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.OPEN_STRUCTURE)); else presenter= new InformationPresenter(getOutlinePresenterControlCreator(sourceViewer, IJavaEditorActionDefinitionIds.SHOW_OUTLINE)); presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL); IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve); presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER); presenter.setSizeConstraints(40, 20, true, true); return presenter; } public IInformationPresenter getHierarchyPresenter(ISourceViewer sourceViewer, boolean doCodeResolve) { InformationPresenter presenter= new InformationPresenter(getHierarchyPresenterControlCreator(sourceViewer)); presenter.setDocumentPartitioning(getConfiguredDocumentPartitioning(sourceViewer)); presenter.setAnchor(InformationPresenter.ANCHOR_GLOBAL); IInformationProvider provider= new JavaElementProvider(getEditor(), doCodeResolve); presenter.setInformationProvider(provider, IDocument.DEFAULT_CONTENT_TYPE); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_DOC); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_MULTI_LINE_COMMENT); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_STRING); presenter.setInformationProvider(provider, IJavaPartitions.JAVA_CHARACTER); presenter.setSizeConstraints(50, 20, true, true); return presenter; } }
51,609
Bug 51609 Not all interfaces shown in Type Hierarchy
I200402102000 Open Type Hierarchy on package junit.framework. Observe: only one interface instead of three is shown. Nothing in .log
verified fixed
8f438b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-18T16:44:36Z
2004-02-11T11:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; /** * A TypeHierarchyViewer that looks like the type hierarchy view of VA/Java: * Starting form Object down to the element in focus, then all subclasses from * this element. * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle * on construction (shared type hierarchy) */ public class TraditionalHierarchyViewer extends TypeHierarchyViewer { public TraditionalHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { super(parent, new TraditionalHierarchyContentProvider(lifeCycle), lifeCycle, part); } /* * @see TypeHierarchyViewer#getTitle */ public String getTitle() { if (isMethodFiltering()) { return TypeHierarchyMessages.getString("TraditionalHierarchyViewer.filtered.title"); //$NON-NLS-1$ } else { return TypeHierarchyMessages.getString("TraditionalHierarchyViewer.title"); //$NON-NLS-1$ } } /* * @see TypeHierarchyViewer#updateContent */ public void updateContent(boolean expand) { getTree().setRedraw(false); refresh(); if (expand) { TraditionalHierarchyContentProvider contentProvider= (TraditionalHierarchyContentProvider) getContentProvider(); int expandLevel= contentProvider.getExpandLevel(); if (isMethodFiltering()) { expandLevel++; } expandToLevel(expandLevel); } getTree().setRedraw(true); } /** * Content provider for the 'traditional' type hierarchy. */ public static class TraditionalHierarchyContentProvider extends TypeHierarchyContentProvider { public TraditionalHierarchyContentProvider(TypeHierarchyLifeCycle provider) { super(provider); } public int getExpandLevel() { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { IType input= hierarchy.getType(); if (input != null) { return getDepth(hierarchy, input) + 2; } else { return 5; } } return 2; } private int getDepth(ITypeHierarchy hierarchy, IType input) { int count= 0; IType superType= hierarchy.getSuperclass(input); while (superType != null) { count++; superType= hierarchy.getSuperclass(superType); } return count; } /* * @see TypeHierarchyContentProvider.getElements */ public Object[] getElements(Object parent) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { IType input= hierarchy.getType(); if (input == null) { ArrayList res= new ArrayList(); IType[] classes= hierarchy.getRootClasses(); for (int i= 0; i < classes.length; i++) { res.add(classes[i]); } IType[] interfaces= hierarchy.getRootInterfaces(); for (int i= 0; i < interfaces.length; i++) { if (isRootOfInterfaceOrAnonym(hierarchy, interfaces[i])) { res.add(interfaces[i]); } } return res.toArray(); } else { if (Flags.isInterface(hierarchy.getCachedFlags(input))) { return new Object[] { input }; } else { IType[] roots= hierarchy.getRootClasses(); for (int i= 0; i < roots.length; i++) { if (isObject(roots[i])) { return new Object[] { roots[i] }; } } return roots; // a problem with the hierarchy } } } return NO_ELEMENTS; } private boolean isRootOfInterfaceOrAnonym(ITypeHierarchy hierarchy, IType type) { IType[] subTypes= hierarchy.getSubtypes(type); for (int i= 0; i < subTypes.length; i++) { IType curr= subTypes[i]; if (isAnonymous(curr)) { return true; } if (Flags.isInterface(hierarchy.getCachedFlags(curr))) { if (isInScope(curr) || isRootOfInterfaceOrAnonym(hierarchy, curr)) { return true; } } } return false; } private boolean isInScope(IType type) { IJavaElement input= fTypeHierarchy.getInputElement(); IJavaElement parent= type.getAncestor(input.getElementType()); if (input.getElementType() == IJavaElement.PACKAGE_FRAGMENT) { if (parent == null || parent.getElementName().equals(input.getElementName())) { return true; } } else if (input.equals(parent)) { return true; } return false; } /* * @see TypeHierarchyContentProvider.getTypesInHierarchy */ protected final void getTypesInHierarchy(IType type, List res) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { IType[] types= hierarchy.getSubtypes(type); if (isObject(type)) { for (int i= 0; i < types.length; i++) { IType curr= types[i]; if (!isAnonymous(curr)) { res.add(curr); } } } else { for (int i= 0; i < types.length; i++) { res.add(types[i]); } } } } protected IType getParentType(IType type) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { return hierarchy.getSuperclass(type); // dont handle interfaces } return null; } } }
52,460
Bug 52460 [spell checking] Spell check index out of range
I was running in console mode for other reasons, when I spotted this stack trace, that did not appear in the log. This is in M7; JDK 1.4.2_03. I just turned on spell checking in the In Progress pref pane but didn't otherwise do anything to configure. I don't know what specific action triggered this (nor did I observe any effect). java.lang.StringIndexOutOfBoundsException: String index out of range: 7 [Dynamic-linking native method java.lang.Throwable.getStackTraceDepth ... JNI] [Dynamic-linking native method java.lang.Throwable.getStackTraceElement ... JNI] at java.lang.String.charAt(String.java:444) at org.eclipse.jdt.internal.ui.text.spelling.SpellCheckIterator.nextToken (SpellCheckIterator.java:297) at org.eclipse.jdt.internal.ui.text.spelling.SpellCheckIterator.next (SpellCheckIterator.java:241) at org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker.execute (DefaultSpellChecker.java:208) at org.eclipse.jdt.internal.ui.text.spelling.SpellReconcileStrategy.reconcile (SpellReconcileStrategy.java:347) at org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy.reconcile (CompositeReconcilingStrategy.java:83) at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.reconcile (JavaCompositeReconcilingStrategy.java:97) at org.eclipse.jface.text.reconciler.MonoReconciler.process (MonoReconciler.java:76) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread.run (AbstractReconciler.java:189)
verified fixed
8f50f86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T09:18:01Z
2004-02-19T08:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/SpellCheckIterator.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.spelling; import java.text.BreakIterator; import java.util.LinkedList; import java.util.Locale; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker; import org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellCheckIterator; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement; import org.eclipse.jdt.internal.ui.text.javadoc.IHtmlTagConstants; import org.eclipse.jdt.internal.ui.text.javadoc.IJavaDocTagConstants; /** * Iterator to spell-check javadoc comment regions. * * @since 3.0 */ public class SpellCheckIterator implements ISpellCheckIterator, IJavaDocTagConstants, IHtmlTagConstants { /** The content of the region */ private final String fContent; /** The line delimiter */ private final String fDelimiter; /** The last token */ private String fLastToken= null; /** The next break */ private int fNext= 1; /** The offset of the region */ private final int fOffset; /** The predecessor break */ private int fPredecessor; /** The previous break */ private int fPrevious= 0; /** The sentence breaks */ private final LinkedList fSentenceBreaks= new LinkedList(); /** Does the current word start a sentence? */ private boolean fStartsSentence= false; /** The successor break */ private int fSuccessor; /** The word iterator */ private final BreakIterator fWordIterator; /** * Creates a new spell check iterator. * * @param document * The document containing the specified partition * @param region * The region to spell-check * @param locale * The locale to use for spell-checking */ public SpellCheckIterator(final IDocument document, final IRegion region, final Locale locale) { fOffset= region.getOffset(); fWordIterator= BreakIterator.getWordInstance(locale); fDelimiter= TextUtilities.getDefaultLineDelimiter(document); String content; try { content= document.get(region.getOffset(), region.getLength()); if (content.startsWith(NLSElement.TAG_PREFIX)) content= ""; //$NON-NLS-1$ } catch (Exception exception) { content= ""; //$NON-NLS-1$ } fContent= content; fWordIterator.setText(content); fPredecessor= fWordIterator.first(); fSuccessor= fWordIterator.next(); final BreakIterator iterator= BreakIterator.getSentenceInstance(locale); iterator.setText(content); int offset= iterator.current(); while (offset != BreakIterator.DONE) { fSentenceBreaks.add(new Integer(offset)); offset= iterator.next(); } } /* * @see org.eclipse.spelling.done.ISpellCheckIterator#getBegin() */ public final int getBegin() { return fPrevious + fOffset; } /* * @see org.eclipse.spelling.done.ISpellCheckIterator#getEnd() */ public final int getEnd() { return fNext + fOffset - 1; } /* * @see java.util.Iterator#hasNext() */ public final boolean hasNext() { return fSuccessor != BreakIterator.DONE; } /** * Does the specified token consist of at least one letter and digits only? * * @param begin * The begin index * @param end * The end index * @return <code>true</code> iff the token consists of digits and at * least one letter only, <code>false</code> otherwise */ protected final boolean isAlphaNumeric(final int begin, final int end) { char character= 0; boolean letter= false; for (int index= begin; index < end; index++) { character= fContent.charAt(index); if (Character.isLetter(character)) letter= true; if (!Character.isLetterOrDigit(character)) return false; } return letter; } /** * Was the last token a Javadoc tag tag? * * @param tags * The javadoc tags to check * @return <code>true</code> iff the last token was a Javadoc tag, <code>false</code> * otherwise */ protected final boolean isJavadocToken(final String[] tags) { if (fLastToken != null) { for (int index= 0; index < tags.length; index++) { if (fLastToken.equals(tags[index])) return true; } } return false; } /** * Is the current token a single letter token surrounded by non-whitespace * characters? * * @param begin * The begin index * @return <code>true</code> iff the token is a single letter token, * <code>false</code> 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 false; } /** * Does the specified token look like an URL? * * @param begin * The begin index * @return <code>true</code> iff this token look like an URL, <code>false</code> * otherwise */ protected final boolean isUrlToken(final int begin) { for (int index= 0; index < DefaultSpellChecker.URL_PREFIXES.length; index++) { if (fContent.startsWith(DefaultSpellChecker.URL_PREFIXES[index], begin)) return true; } return false; } /** * Does the specified token consist of whitespace only? * * @param begin * The begin index * @param end * The end index * @return <code>true</code> iff the token consists of whitespace only, * <code>false</code> otherwise */ protected final boolean isWhitespace(final int begin, final int end) { for (int index= begin; index < end; index++) { if (!Character.isWhitespace(fContent.charAt(index))) return false; } return true; } /* * @see java.util.Iterator#next() */ public final Object next() { String token= nextToken(); while (token == null && fSuccessor != BreakIterator.DONE) token= nextToken(); fLastToken= token; return token; } /** * Advances the end index to the next word break. */ protected final void nextBreak() { fNext= fSuccessor; fPredecessor= fSuccessor; fSuccessor= fWordIterator.next(); } /** * Returns the next sentence break. * * @return The next sentence break */ protected final int nextSentence() { return ((Integer) fSentenceBreaks.getFirst()).intValue(); } /** * Determines the next token to be spell-checked. * * @return The next token to be spell-checked, or <code>null</code> iff * the next token is not a candidate for spell-checking. */ protected String nextToken() { String token= null; fPrevious= fPredecessor; fStartsSentence= false; nextBreak(); boolean update= false; if (fNext - fPrevious > 0) { if (fContent.charAt(fPrevious) == JAVADOC_TAG_PREFIX && fSuccessor != BreakIterator.DONE) { nextBreak(); if (Character.isLetter(fContent.charAt(fPrevious + 1))) { update= true; token= fContent.substring(fPrevious, fNext); } else fPredecessor= fNext; } else if (fContent.charAt(fPrevious) == HTML_TAG_PREFIX && (Character.isLetter(fContent.charAt(fNext)) || fContent.charAt(fNext) == '/') && fSuccessor != BreakIterator.DONE) { if (fContent.startsWith(HTML_CLOSE_PREFIX, fPrevious)) nextBreak(); nextBreak(); if (fContent.charAt(fNext) == HTML_TAG_POSTFIX && fSuccessor != BreakIterator.DONE) { nextBreak(); if (fSuccessor != BreakIterator.DONE) { update= true; token= fContent.substring(fPrevious, fNext); } } } else if (!isWhitespace(fPrevious, fNext) && isAlphaNumeric(fPrevious, fNext)) { if (isUrlToken(fPrevious)) skipTokens(fPrevious, ' '); else if (isJavadocToken(JAVADOC_PARAM_TAGS)) fLastToken= null; else if (isJavadocToken(JAVADOC_REFERENCE_TAGS)) { fLastToken= null; skipTokens(fPrevious, fDelimiter.charAt(0)); } else if (fNext - fPrevious > 1 || isSingleLetter(fPrevious)) token= fContent.substring(fPrevious, fNext); update= true; } } if (update && fSentenceBreaks.size() > 0) { if (fPrevious >= nextSentence()) { while (fSentenceBreaks.size() > 0 && fPrevious >= nextSentence()) fSentenceBreaks.removeFirst(); fStartsSentence= (fLastToken == null) || (token != null); } } return token; } /* * @see java.util.Iterator#remove() */ public final void remove() { throw new UnsupportedOperationException(); } /** * Skip the tokens until the stop character is reached. * * @param begin * The begin index * @param stop * The stop character */ protected final void skipTokens(final int begin, final char stop) { int end= begin; while (end < fContent.length() && fContent.charAt(end) != stop) end++; if (end < fContent.length()) { fNext= end; fPredecessor= fNext; fSuccessor= fWordIterator.following(fNext); } else fSuccessor= BreakIterator.DONE; } /* * @see org.eclipse.spelling.done.ISpellCheckIterator#startsSentence() */ public final boolean startsSentence() { return fStartsSentence; } }
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots1/in/srcPrg/p/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots1/in/srcTest/p/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots1/in/srcTest/tests/AllTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots1/out/srcPrg/q/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots1/out/srcTest/p/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots1/out/srcTest/tests/AllTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/in/srcPrg/p/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/in/srcTest/p/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/in/srcTest/p/p/TestHelper.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/in/srcTest/tests/AllTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/in/srcTest/tests/QualifiedTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/out/srcPrg/q/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/out/srcTest/p/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/out/srcTest/p/p/TestHelper.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/out/srcTest/tests/AllTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots2/out/srcTest/tests/QualifiedTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots3/in/srcPrg/p/p/ToQ.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots3/in/srcTest/p/p/Ref.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots3/out/srcPrg/q/ToQ.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots3/out/srcTest/p/p/Ref.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots4/in/srcPrg/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots4/in/srcPrg/p/B.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots4/in/srcTest/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots4/out/srcPrg/a/b/c/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots4/out/srcPrg/a/b/c/B.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots4/out/srcTest/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots5/in/srcPrg/p/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots5/in/srcTest/p/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots5/out/srcPrg/p/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots5/out/srcTest/q/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots6/in/srcPrg/p/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots6/in/srcTest/p/p/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots6/out/srcPrg/p/p/A.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots6/out/srcTest/cheese/ATest.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/in/srcPrj.other/pack/Namesake.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/in/srcPrj.ref/pack/Referer.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/in/srcPrj.ref/pack/man/StarImporter.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/in/srcPrj/pack/DingsDa.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/out/srcPrj.other/pack/Namesake.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/out/srcPrj.ref/pack/Referer.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/out/srcPrj.ref/pack/man/StarImporter.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenamePackage/testImportFromMultiRoots7/out/srcPrj/com/packt/DingsDa.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui.tests.refactoring/test
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenamePackageTests.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui/core
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringScopeFactory.java
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
org.eclipse.jdt.ui/core
47,509
Bug 47509 Refactor name of package fragment does not handle on demand import
Build Eclipse 2.1.2 On the following setup, select package fragment 'p' located in project B and rename it into 'q'. It will rename the 'import p.*;' statement, but did not realize there was still a use for it due to other fragment. It should have inserted an extra import during the rename action. Project A +- package p +- A.java Project B prereqs A +- package p | +- B.java +- package c +- C.java package c; import p.*; public class C { }
verified fixed
9186dd4
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-19T14:22:48Z
2003-11-26T12:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenamePackageProcessor.java
52,310
Bug 52310 [Refactor] Moving a class from default package has missing "." from imports
Moved a class from the default package and ended up with imports missing the last ".". For example: I got something like org.eclipseMovedClass instead of org.eclipse.MovedClass
resolved fixed
9dd8937
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T14:15:53Z
2004-02-17T23:20:00Z
org.eclipse.jdt.ui.tests.refactoring/test
52,310
Bug 52310 [Refactor] Moving a class from default package has missing "." from imports
Moved a class from the default package and ended up with imports missing the last ".". For example: I got something like org.eclipseMovedClass instead of org.eclipse.MovedClass
resolved fixed
9dd8937
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T14:15:53Z
2004-02-17T23:20:00Z
cases/org/eclipse/jdt/ui/tests/reorg/MoveTest.java
52,310
Bug 52310 [Refactor] Moving a class from default package has missing "." from imports
Moved a class from the default package and ended up with imports missing the last ".". For example: I got something like org.eclipseMovedClass instead of org.eclipse.MovedClass
resolved fixed
9dd8937
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T14:15:53Z
2004-02-17T23:20:00Z
org.eclipse.jdt.ui/core
52,310
Bug 52310 [Refactor] Moving a class from default package has missing "." from imports
Moved a class from the default package and ended up with imports missing the last ".". For example: I got something like org.eclipseMovedClass instead of org.eclipse.MovedClass
resolved fixed
9dd8937
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T14:15:53Z
2004-02-17T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveCuUpdateCreator.java
51,954
Bug 51954 IOException while generating Javadoc
M7 build Try to generate Javadoc for the package org.eclipse.jdt.internal.corext.refactoring.participants.xml. java.io.IOException: CreateProcess: C:\apps\java\jdk1.4.2\bin\javadoc.exe -d c:\tmp\testdoc - sourcepath "C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \ui;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui\ui refactoring;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \core refactoring;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \core extension" -classpath C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui\bin;C:\home \dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.ui\ui.jar;C:\home\dbaeume r\devel\workspaces\eclipse\3.0new\org.eclipse.core.runtime.compatibility\compat ibility.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.core.r untime\runtime.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse .osgi\osgi.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.osg i\core.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.osgi\re solver.jar;C:\home\dbaeumer\devel\workspaces\eclipse\&#148; at java.lang.Win32Process.create(Native Method) at java.lang.Win32Process.<init>(Win32Process.java:66) at java.lang.Runtime.execInternal(Native Method) at java.lang.Runtime.exec(Runtime.java:566) at java.lang.Runtime.exec(Runtime.java:491) at java.lang.Runtime.exec(Runtime.java:457) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.executeJavadocGeneratio n(JavadocWizard.java:228) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.performFinish (JavadocWizard.java:191) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:608) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:321) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:402) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.jface.window.Window.runEventLoop(Window.java:647) at org.eclipse.jface.window.Window.open(Window.java:627) at org.eclipse.ui.actions.ExportResourcesAction.run (ExportResourcesAction.java:165) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:536) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:488) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent (ActionContributionItem.java:420) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1550) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1526) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:265) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:257) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
resolved fixed
47eda9e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T19:00:50Z
2004-02-13T13:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocOptionsManager.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.eclipse.jdt.launching.ExecutionArguments; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIStatus; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.preferences.JavadocPreferencePage; public class JavadocOptionsManager { private IFile fXmlfile; private StatusInfo fWizardStatus; private IJavaElement[] fSelectedElements; private IJavaElement[] fInitialElements; private String fAccess; private String fDocletpath; private String fDocletname; private boolean fFromStandard; private String fStylesheet; private String fAdditionalParams; private String fOverview; private String fTitle; private String[] fHRefs; private IPath[] fSourcepath; private IPath[] fClasspath; private boolean fNotree; private boolean fNoindex; private boolean fSplitindex; private boolean fNonavbar; private boolean fNodeprecated; private boolean fNoDeprecatedlist; private boolean fAuthor; private boolean fVersion; private boolean fUse; private boolean fJDK14Mode; private boolean fOpenInBrowser; private RecentSettingsStore fRecentSettings; //add-on for multi-project version private String fDestination; private String fAntpath; public final String PRIVATE= "private"; //$NON-NLS-1$ public final String PROTECTED= "protected"; //$NON-NLS-1$ public final String PACKAGE= "package"; //$NON-NLS-1$ public final String PUBLIC= "public"; //$NON-NLS-1$ public final String USE= "use"; //$NON-NLS-1$ public final String NOTREE= "notree"; //$NON-NLS-1$ public final String NOINDEX= "noindex"; //$NON-NLS-1$ public final String NONAVBAR= "nonavbar"; //$NON-NLS-1$ public final String NODEPRECATED= "nodeprecated"; //$NON-NLS-1$ public final String NODEPRECATEDLIST= "nodeprecatedlist"; //$NON-NLS-1$ public final String VERSION= "version"; //$NON-NLS-1$ public final String AUTHOR= "author"; //$NON-NLS-1$ public final String SPLITINDEX= "splitindex"; //$NON-NLS-1$ public final String STYLESHEETFILE= "stylesheetfile"; //$NON-NLS-1$ public final String OVERVIEW= "overview"; //$NON-NLS-1$ public final String DOCLETNAME= "docletname"; //$NON-NLS-1$ public final String DOCLETPATH= "docletpath"; //$NON-NLS-1$ public final String SOURCEPATH= "sourcepath"; //$NON-NLS-1$ public final String CLASSPATH= "classpath"; //$NON-NLS-1$ public final String DESTINATION= "destdir"; //$NON-NLS-1$ public final String OPENINBROWSER= "openinbrowser"; //$NON-NLS-1$ public final String VISIBILITY= "access"; //$NON-NLS-1$ public final String PACKAGENAMES= "packagenames"; //$NON-NLS-1$ public final String SOURCEFILES= "sourcefiles"; //$NON-NLS-1$ public final String EXTRAOPTIONS= "additionalparam"; //$NON-NLS-1$ //public final String JAVADOCCOMMAND= "javadoccommand"; //$NON-NLS-1$ public final String TITLE= "doctitle"; //$NON-NLS-1$ public final String HREF= "href"; //$NON-NLS-1$ public final String NAME= "name"; //$NON-NLS-1$ public final String PATH= "path"; //$NON-NLS-1$ public final String FROMSTANDARD= "fromStandard"; //$NON-NLS-1$ public final String ANTPATH= "antpath"; //$NON-NLS-1$ public final String SOURCE= "source"; //$NON-NLS-1$ private final String SECTION_JAVADOC= "javadoc"; //$NON-NLS-1$ public JavadocOptionsManager(IFile xmlJavadocFile, IDialogSettings dialogSettings, List currSelection) { fXmlfile= xmlJavadocFile; fWizardStatus= new StatusInfo(); IDialogSettings javadocSection= dialogSettings.getSection(SECTION_JAVADOC); //$NON-NLS-1$ fRecentSettings= new RecentSettingsStore(javadocSection); if (xmlJavadocFile != null) { try { JavadocReader reader= new JavadocReader(xmlJavadocFile.getContents()); Element element= reader.readXML(); if (element != null) { loadFromXML(element); return; } fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$ } catch (CoreException e) { JavaPlugin.log(e); fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectCE.warning")); //$NON-NLS-1$ } catch (IOException e) { JavaPlugin.log(e); fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectIOE.warning")); //$NON-NLS-1$ } catch (SAXException e) { fWizardStatus.setWarning(JavadocExportMessages.getString("JavadocOptionsManager.antfileincorrectSAXE.warning")); //$NON-NLS-1$ } } if (javadocSection != null) { loadFromDialogStore(javadocSection, currSelection); } else { loadDefaults(currSelection); } } /* * Returns the the Java project that is parent top all selected elements or null if * the elements are from several projects. */ private IJavaProject getSingleProjectFromInitialSelection() { IJavaProject res= null; for (int i= 0; i < fInitialElements.length; i++) { IJavaProject curr= fInitialElements[i].getJavaProject(); if (res == null) { res= curr; } else if (!res.equals(curr)) { return null; } } return res; } private void loadFromDialogStore(IDialogSettings settings, List sel) { fInitialElements= getInitialElementsFromSelection(sel); IJavaProject project= getSingleProjectFromInitialSelection(); fAccess= settings.get(VISIBILITY); if (fAccess == null) fAccess= PROTECTED; //this is defaulted to false. fFromStandard= settings.getBoolean(FROMSTANDARD); //doclet is loaded even if the standard doclet is being used fDocletpath= settings.get(DOCLETPATH); fDocletname= settings.get(DOCLETNAME); if (fDocletpath == null || fDocletname == null) { fFromStandard= true; fDocletpath= ""; //$NON-NLS-1$ fDocletname= ""; //$NON-NLS-1$ } if (project != null) { fAntpath= getRecentSettings().getAntpath(project); } else { fAntpath= settings.get(ANTPATH); if (fAntpath == null) { fAntpath= ""; //$NON-NLS-1$ } } if (project != null) { fDestination= getRecentSettings().getDestination(project); } else { fDestination= settings.get(DESTINATION); if (fDestination == null) { fDestination= ""; //$NON-NLS-1$ } } fTitle= settings.get(TITLE); if (fTitle == null) fTitle= ""; //$NON-NLS-1$ fStylesheet= settings.get(STYLESHEETFILE); if (fStylesheet == null) fStylesheet= ""; //$NON-NLS-1$ fAdditionalParams= settings.get(EXTRAOPTIONS); if (fAdditionalParams == null) fAdditionalParams= ""; //$NON-NLS-1$ fOverview= settings.get(OVERVIEW); if (fOverview == null) fOverview= ""; //$NON-NLS-1$ fUse= loadBoolean(settings.get(USE)); fAuthor= loadBoolean(settings.get(AUTHOR)); fVersion= loadBoolean(settings.get(VERSION)); fNodeprecated= loadBoolean(settings.get(NODEPRECATED)); fNoDeprecatedlist= loadBoolean(settings.get(NODEPRECATEDLIST)); fNonavbar= loadBoolean(settings.get(NONAVBAR)); fNoindex= loadBoolean(settings.get(NOINDEX)); fNotree= loadBoolean(settings.get(NOTREE)); fSplitindex= loadBoolean(settings.get(SPLITINDEX)); fOpenInBrowser= loadBoolean(settings.get(OPENINBROWSER)); fJDK14Mode= loadBoolean(settings.get(SOURCE)); if (project != null) { fHRefs= getRecentSettings().getHRefs(project); } else { fHRefs= new String[0]; } } //loads defaults for wizard (nothing is stored) private void loadDefaults(List sel) { fInitialElements= getInitialElementsFromSelection(sel); IJavaProject project= getSingleProjectFromInitialSelection(); if (project != null) { fAntpath= getRecentSettings().getAntpath(project); fDestination= getRecentSettings().getDestination(project); fHRefs= getRecentSettings().getHRefs(project); } else { fAntpath= ""; //$NON-NLS-1$ fDestination= ""; //$NON-NLS-1$ fHRefs= new String[0]; } fAccess= PUBLIC; fDocletname= ""; //$NON-NLS-1$ fDocletpath= ""; //$NON-NLS-1$ fTitle= ""; //$NON-NLS-1$ fStylesheet= ""; //$NON-NLS-1$ fAdditionalParams= ""; //$NON-NLS-1$ fOverview= ""; //$NON-NLS-1$ fUse= true; fAuthor= true; fVersion= true; fNodeprecated= false; fNoDeprecatedlist= false; fNonavbar= false; fNoindex= false; fNotree= false; fSplitindex= true; fOpenInBrowser= false; fJDK14Mode= false; //by default it is empty all project map to the empty string fFromStandard= true; } private void loadFromXML(Element element) { fAccess= element.getAttribute(VISIBILITY); if (fAccess.length() == 0) fAccess= PROTECTED; //Since the selected packages are stored we must locate the project String destination= element.getAttribute(DESTINATION); fDestination= makeAbsolutePathFromRelative(destination).toOSString(); fFromStandard= true; fDocletname= ""; //$NON-NLS-1$ fDocletpath= ""; //$NON-NLS-1$ if (destination.length() == 0) { //$NON-NLS-1$ NodeList list= element.getChildNodes(); for (int i= 0; i < list.getLength(); i++) { Node child= list.item(i); if (child.getNodeName().equals("doclet")) { //$NON-NLS-1$ fDocletpath= ((Element) child).getAttribute(PATH); fDocletname= ((Element) child).getAttribute(NAME); if (fDocletpath.length() != 0 || fDocletname.length() != 0) { fFromStandard= false; } else { fDocletname= ""; //$NON-NLS-1$ fDocletpath= ""; //$NON-NLS-1$ } break; } } } fInitialElements= getSelectedElementsFromAnt(element); //find all the links stored in the ant script NodeList children= element.getChildNodes(); fHRefs= new String[children.getLength()]; for (int i= 0; i < fHRefs.length; i++) { Node child= children.item(i); if (child.getNodeName().equals("link")) { //$NON-NLS-1$ fHRefs[i]= ((Element) child).getAttribute(HREF); } } //get tree elements IPath p= fXmlfile.getLocation(); if (p != null) fAntpath= p.toOSString(); else fAntpath= ""; //$NON-NLS-1$ fStylesheet= element.getAttribute(STYLESHEETFILE); fTitle= element.getAttribute(TITLE); fAdditionalParams= element.getAttribute(EXTRAOPTIONS); fOverview= element.getAttribute(OVERVIEW); fUse= loadBoolean(element.getAttribute(USE)); fAuthor= loadBoolean(element.getAttribute(AUTHOR)); fVersion= loadBoolean(element.getAttribute(VERSION)); fNodeprecated= loadBoolean(element.getAttribute(NODEPRECATED)); fNoDeprecatedlist= loadBoolean(element.getAttribute(NODEPRECATEDLIST)); fNonavbar= loadBoolean(element.getAttribute(NONAVBAR)); fNoindex= loadBoolean(element.getAttribute(NOINDEX)); fNotree= loadBoolean(element.getAttribute(NOTREE)); fSplitindex= loadBoolean(element.getAttribute(SPLITINDEX)); } /* * Method creates an absolute path to the project. If the path is already * absolute it returns the path. If it encounters any difficulties in * creating the absolute path, the method returns null. * * @param pathStr * @return IPath */ private IPath makeAbsolutePathFromRelative(String pathStr) { IPath path= new Path(pathStr); if (!path.isAbsolute()) { if (fXmlfile == null) { return null; } IPath basePath= fXmlfile.getParent().getLocation(); // relative to the ant file location if (basePath == null) { return null; } return basePath.append(pathStr); } return path; } private IContainer[] getSourceContainers(Element element) { String sourcePaths= element.getAttribute(SOURCEPATH); StringTokenizer tokenizer= new StringTokenizer(sourcePaths, ","); //$NON-NLS-1$ ArrayList res= new ArrayList(); IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); while (tokenizer.hasMoreTokens()) { IPath path= makeAbsolutePathFromRelative(tokenizer.nextToken().trim()); if (path != null) { IContainer[] containers= root.findContainersForLocation(path); for (int i= 0; i < containers.length; i++) { res.add(containers[i]); } } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private IJavaElement[] getSelectedElementsFromAnt(Element element) { List res= new ArrayList(); // get all the packages listed in the ANT file String packagenames= element.getAttribute(PACKAGENAMES); if (packagenames != null) { IContainer[] containers= getSourceContainers(element); StringTokenizer tokenizer= new StringTokenizer(packagenames, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { IPath relPackagePath= new Path(tokenizer.nextToken().trim().replace('.', '/')); for (int i= 0; i < containers.length; i++) { IContainer curr= containers[i]; IResource resource= curr.findMember(relPackagePath); if (resource != null) { IJavaElement javaElem= JavaCore.create(resource); if (javaElem instanceof IPackageFragment) { res.add(javaElem); } } } } } //get all CompilationUnites listed in the ANT file String sourcefiles= element.getAttribute(SOURCEFILES); if (sourcefiles != null) { IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); StringTokenizer tokenizer= new StringTokenizer(sourcefiles, ","); //$NON-NLS-1$ while (tokenizer.hasMoreTokens()) { String name= tokenizer.nextToken().trim(); if (name.endsWith(".java")) { //$NON-NLS-1$ IPath path= makeAbsolutePathFromRelative(name); //if unable to create an absolute path the the resource skip it if (path != null) { IFile[] files= root.findFilesForLocation(path); for (int i= 0; i < files.length; i++) { IJavaElement el= JavaCore.createCompilationUnitFrom(files[i]); if (el != null) { res.add(el); } } } } } } return (IJavaElement[]) res.toArray(new IJavaElement[res.size()]); } //it is possible that the package list is empty public StatusInfo getWizardStatus() { return fWizardStatus; } public IJavaElement[] getInitialElements() { return fInitialElements; } public IJavaElement[] getSourceElements() { return fSelectedElements; } public String getAccess() { return fAccess; } public String getAntpath() { return fAntpath; } public boolean isFromStandard() { return fFromStandard; } public String getDestination() { return fDestination; } public String getDocletPath() { return fDocletpath; } public String getDocletName() { return fDocletname; } public String getStyleSheet() { return fStylesheet; } public String getOverview() { return fOverview; } public String getAdditionalParams() { return fAdditionalParams; } public IPath[] getClasspath() { return fClasspath; } public IPath[] getSourcepath() { return fSourcepath; } public String getTitle() { return fTitle; } public boolean doOpenInBrowser() { return fOpenInBrowser; } public String[] getHRefs() { return fHRefs; } public boolean getBoolean(String flag) { if (flag.equals(AUTHOR)) return fAuthor; else if (flag.equals(VERSION)) return fVersion; else if (flag.equals(USE)) return fUse; else if (flag.equals(NODEPRECATED)) return fNodeprecated; else if (flag.equals(NODEPRECATEDLIST)) return fNoDeprecatedlist; else if (flag.equals(NOINDEX)) return fNoindex; else if (flag.equals(NOTREE)) return fNotree; else if (flag.equals(SPLITINDEX)) return fSplitindex; else if (flag.equals(NONAVBAR)) return fNonavbar; else return false; } private boolean loadBoolean(String value) { if (value == null || value.length() == 0) //$NON-NLS-1$ return false; else { if (value.equals("true")) //$NON-NLS-1$ return true; else return false; } } private String flatPathList(IPath[] paths) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < paths.length; i++) { if (i > 0) { buf.append(File.pathSeparatorChar); } buf.append(paths[i].toOSString()); } return buf.toString(); } public String[] createArgumentArray() { List args= new ArrayList(); //bug 38692 args.add(JavadocPreferencePage.getJavaDocCommand()); if (fFromStandard) { args.add("-d"); //$NON-NLS-1$ args.add(fDestination); } else { if (fAdditionalParams.length() != 0) { //$NON-NLS-1$ ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$ String[] argsArray= tokens.getProgramArgumentsArray(); for (int i= 0; i < argsArray.length; i++) { args.add(argsArray[i]); } } args.add("-doclet"); //$NON-NLS-1$ args.add(fDocletname); args.add("-docletpath"); //$NON-NLS-1$ args.add(fDocletpath); } args.add("-sourcepath"); //$NON-NLS-1$ args.add(flatPathList(fSourcepath)); args.add("-classpath"); //$NON-NLS-1$ args.add(flatPathList(fClasspath)); args.add("-" + fAccess); //$NON-NLS-1$ if (fFromStandard) { if (fJDK14Mode) { args.add("-source"); //$NON-NLS-1$ args.add("1.4"); //$NON-NLS-1$ } if (fUse) args.add("-use"); //$NON-NLS-1$ if (fVersion) args.add("-version"); //$NON-NLS-1$ if (fAuthor) args.add("-author"); //$NON-NLS-1$ if (fNonavbar) args.add("-nonavbar"); //$NON-NLS-1$ if (fNoindex) args.add("-noindex"); //$NON-NLS-1$ if (fNotree) args.add("-notree"); //$NON-NLS-1$ if (fNodeprecated) args.add("-nodeprecated"); //$NON-NLS-1$ if (fNoDeprecatedlist) args.add("-nodeprecatedlist"); //$NON-NLS-1$ if (fSplitindex) args.add("-splitindex"); //$NON-NLS-1$ if (fTitle.length() != 0) { //$NON-NLS-1$ args.add("-doctitle"); //$NON-NLS-1$ args.add(fTitle); } if (fStylesheet.length() != 0) { //$NON-NLS-1$ args.add("-stylesheetfile"); //$NON-NLS-1$ args.add(fStylesheet); } if (fAdditionalParams.length() != 0) { //$NON-NLS-1$ ExecutionArguments tokens= new ExecutionArguments("", fAdditionalParams); //$NON-NLS-1$ String[] argsArray= tokens.getProgramArgumentsArray(); for (int i= 0; i < argsArray.length; i++) { args.add(argsArray[i]); } } for (int i= 0; i < fHRefs.length; i++) { args.add("-link"); //$NON-NLS-1$ args.add(fHRefs[i]); } } //end standard options if (fOverview.length() != 0) { //$NON-NLS-1$ args.add("-overview"); //$NON-NLS-1$ args.add(fOverview); } for (int i= 0; i < fSelectedElements.length; i++) { IJavaElement curr= fSelectedElements[i]; if (curr instanceof IPackageFragment) { args.add(curr.getElementName()); } else if (curr instanceof ICompilationUnit) { IPath p= curr.getResource().getLocation(); if (p != null) args.add(p.toOSString()); } } String[] res= (String[]) args.toArray(new String[args.size()]); return res; } public void createXML(IJavaProject[] projects) throws CoreException { FileOutputStream objectStreamOutput= null; //@change //for now only writting ant files for single project selection String antpath= fAntpath; try { if (antpath.length() > 0) { File file= new File(antpath); IPath antPath= new Path(antpath); IPath antDir= antPath.removeLastSegments(1); IPath basePath= null; IWorkspaceRoot root= ResourcesPlugin.getWorkspace().getRoot(); if (root.findFilesForLocation(antPath).length > 0) { basePath= antDir; // only do relative path if ant file is stored in the workspace } antDir.toFile().mkdirs(); objectStreamOutput= new FileOutputStream(file); JavadocWriter writer= new JavadocWriter(objectStreamOutput, basePath, projects); writer.writeXML(this); } } catch (IOException e) { String message= JavadocExportMessages.getString("JavadocOptionsManager.createXM.error"); //$NON-NLS-1$ throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e)); } catch (ParserConfigurationException e) { String message= JavadocExportMessages.getString("JavadocOptionsManager.createXM.error"); //$NON-NLS-1$ throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e)); } catch (TransformerException e) { String message= JavadocExportMessages.getString("JavadocOptionsManager.createXM.error"); //$NON-NLS-1$ throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, message, e)); } finally { if (objectStreamOutput != null) { try { objectStreamOutput.close(); } catch (IOException e) { } } } } public void updateDialogSettings(IDialogSettings dialogSettings, IJavaProject[] checkedProjects) { IDialogSettings settings= dialogSettings.addNewSection(SECTION_JAVADOC); settings.put(FROMSTANDARD, fFromStandard); settings.put(DOCLETNAME, fDocletname); settings.put(DOCLETPATH, fDocletpath); settings.put(VISIBILITY, fAccess); settings.put(USE, fUse); settings.put(AUTHOR, fAuthor); settings.put(VERSION, fVersion); settings.put(NODEPRECATED, fNodeprecated); settings.put(NODEPRECATEDLIST, fNoDeprecatedlist); settings.put(SPLITINDEX, fSplitindex); settings.put(NOINDEX, fNoindex); settings.put(NOTREE, fNotree); settings.put(NONAVBAR, fNonavbar); settings.put(OPENINBROWSER, fOpenInBrowser); settings.put(SOURCE, fJDK14Mode); if (fAntpath.length() != 0) //$NON-NLS-1$ settings.put(ANTPATH, fAntpath); if (fDestination.length() != 0) //$NON-NLS-1$ settings.put(DESTINATION, fDestination); if (fAdditionalParams.length() != 0) //$NON-NLS-1$ settings.put(EXTRAOPTIONS, fAdditionalParams); if (fOverview.length() != 0) //$NON-NLS-1$ settings.put(OVERVIEW, fOverview); if (fStylesheet.length() != 0) //$NON-NLS-1$ settings.put(STYLESHEETFILE, fStylesheet); if (fTitle.length() != 0) //$NON-NLS-1$ settings.put(TITLE, fTitle); if (checkedProjects.length == 1) { updateRecentSettings(checkedProjects[0]); } getRecentSettings().store(settings); } public void setAccess(String access) { fAccess= access; } public void setDestination(String destination) { fDestination= destination; } public void setDocletPath(String docletpath) { fDocletpath= docletpath; } public void setDocletName(String docletname) { fDocletname= docletname; } public void setStyleSheet(String stylesheet) { fStylesheet= stylesheet; } public void setOverview(String overview) { fOverview= overview; } public void setAdditionalParams(String params) { fAdditionalParams= params; } public void setGeneralAntpath(String antpath) { fAntpath= antpath; } public void setClasspath(IPath[] classpath) { fClasspath= classpath; } public void setSourcepath(IPath[] sourcepath) { fSourcepath= sourcepath; } public void setSelectedElements(IJavaElement[] elements) { fSelectedElements= elements; } public void setFromStandard(boolean fromStandard) { fFromStandard= fromStandard; } public void setTitle(String title) { fTitle= title; } public void setOpenInBrowser(boolean openInBrowser) { fOpenInBrowser= openInBrowser; } public void setHRefs(String[] hrefs) { fHRefs= hrefs; } public void setBoolean(String flag, boolean value) { if (flag.equals(AUTHOR)) fAuthor= value; else if (flag.equals(USE)) fUse= value; else if (flag.equals(VERSION)) fVersion= value; else if (flag.equals(NODEPRECATED)) fNodeprecated= value; else if (flag.equals(NODEPRECATEDLIST)) fNoDeprecatedlist= value; else if (flag.equals(NOINDEX)) fNoindex= value; else if (flag.equals(NOTREE)) fNotree= value; else if (flag.equals(SPLITINDEX)) fSplitindex= value; else if (flag.equals(NONAVBAR)) fNonavbar= value; } public boolean isJDK14Mode() { return fJDK14Mode; } public void setJDK14Mode(boolean jdk14Mode) { fJDK14Mode= jdk14Mode; } private IJavaElement[] getInitialElementsFromSelection(List candidates) { ArrayList res= new ArrayList(); for (int i= 0; i < candidates.size(); i++) { try { IJavaElement elem= getSelectableJavaElement(candidates.get(i)); if (elem != null) { res.add(elem); } } catch (JavaModelException ignore) { // ignore this } } return (IJavaElement[]) res.toArray(new IJavaElement[res.size()]); } private IJavaElement getSelectableJavaElement(Object obj) throws JavaModelException { IJavaElement je= null; if (obj instanceof IAdaptable) { je= (IJavaElement) ((IAdaptable) obj).getAdapter(IJavaElement.class); } if (je != null) { switch (je.getElementType()) { case IJavaElement.JAVA_MODEL : case IJavaElement.JAVA_PROJECT : case IJavaElement.CLASS_FILE : break; case IJavaElement.PACKAGE_FRAGMENT_ROOT : if (containsCompilationUnits((IPackageFragmentRoot) je)) { return je; } break; case IJavaElement.PACKAGE_FRAGMENT : if (containsCompilationUnits((IPackageFragment) je)) { return je; } break; default : ICompilationUnit cu= (ICompilationUnit) je.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { return cu; } } IJavaProject project= je.getJavaProject(); if (isValidProject(project)) return project; } return null; } private boolean isValidProject(IJavaProject project) throws JavaModelException { if (project != null && project.exists()) { IPackageFragmentRoot[] roots= project.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (containsCompilationUnits(roots[i])) { return true; } } } return false; } private boolean containsCompilationUnits(IPackageFragmentRoot root) throws JavaModelException { if (root.getKind() != IPackageFragmentRoot.K_SOURCE) { return false; } IJavaElement[] elements= root.getChildren(); for (int i= 0; i < elements.length; i++) { if (elements[i] instanceof IPackageFragment) { IPackageFragment fragment= (IPackageFragment) elements[i]; if (containsCompilationUnits(fragment)) { return true; } } } return false; } private boolean containsCompilationUnits(IPackageFragment pack) throws JavaModelException { return pack.getCompilationUnits().length > 0; } public RecentSettingsStore getRecentSettings() { return fRecentSettings; } /** * @param project */ public void updateRecentSettings(IJavaProject project) { fRecentSettings.setProjectSettings(project, fDestination, fAntpath, fHRefs); } }
51,954
Bug 51954 IOException while generating Javadoc
M7 build Try to generate Javadoc for the package org.eclipse.jdt.internal.corext.refactoring.participants.xml. java.io.IOException: CreateProcess: C:\apps\java\jdk1.4.2\bin\javadoc.exe -d c:\tmp\testdoc - sourcepath "C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \ui;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui\ui refactoring;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \core refactoring;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \core extension" -classpath C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui\bin;C:\home \dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.ui\ui.jar;C:\home\dbaeume r\devel\workspaces\eclipse\3.0new\org.eclipse.core.runtime.compatibility\compat ibility.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.core.r untime\runtime.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse .osgi\osgi.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.osg i\core.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.osgi\re solver.jar;C:\home\dbaeumer\devel\workspaces\eclipse\&#148; at java.lang.Win32Process.create(Native Method) at java.lang.Win32Process.<init>(Win32Process.java:66) at java.lang.Runtime.execInternal(Native Method) at java.lang.Runtime.exec(Runtime.java:566) at java.lang.Runtime.exec(Runtime.java:491) at java.lang.Runtime.exec(Runtime.java:457) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.executeJavadocGeneratio n(JavadocWizard.java:228) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.performFinish (JavadocWizard.java:191) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:608) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:321) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:402) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.jface.window.Window.runEventLoop(Window.java:647) at org.eclipse.jface.window.Window.open(Window.java:627) at org.eclipse.ui.actions.ExportResourcesAction.run (ExportResourcesAction.java:165) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:536) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:488) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent (ActionContributionItem.java:420) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1550) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1526) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:265) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:257) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
resolved fixed
47eda9e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T19:00:50Z
2004-02-13T13:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocSpecificsWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.File; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.SWTUtil; public class JavadocSpecificsWizardPage extends JavadocWizardPage { private Button fAntBrowseButton; private Button fCheckbrowser; private Text fAntText; private Button fOverViewButton; private Button fOverViewBrowseButton; private Button fAntButton; private Button fJDK14Button; private Composite fLowerComposite; private Text fOverViewText; private Text fExtraOptionsText; private StatusInfo fOverviewStatus; private StatusInfo fAntStatus; private JavadocOptionsManager fStore; private final int OVERVIEWSTATUS= 1; private final int ANTSTATUS= 2; protected JavadocSpecificsWizardPage(String pageName, JavadocOptionsManager store) { super(pageName); setDescription(JavadocExportMessages.getString("JavadocSpecificsWizardPage.description")); //$NON-NLS-1$ fStore= store; fOverviewStatus= new StatusInfo(); fAntStatus= new StatusInfo(); } /* * @see IDialogPage#createControl(Composite) */ public void createControl(Composite parent) { fLowerComposite= new Composite(parent, SWT.NONE); fLowerComposite.setLayoutData(createGridData(GridData.FILL_BOTH, 1, 0)); GridLayout layout= createGridLayout(3); layout.marginHeight= 0; fLowerComposite.setLayout(layout); createExtraOptionsGroup(fLowerComposite); createAntGroup(fLowerComposite); setControl(fLowerComposite); Dialog.applyDialogFont(fLowerComposite); WorkbenchHelp.setHelp(fLowerComposite, IJavaHelpContextIds.JAVADOC_SPECIFICS_PAGE); } //end method createControl private void createExtraOptionsGroup(Composite composite) { Composite c= new Composite(composite, SWT.NONE); c.setLayout(createGridLayout(3)); c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 3, 0)); ((GridLayout) c.getLayout()).marginWidth= 0; fOverViewButton= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewbutton.label"), createGridData(1)); //$NON-NLS-1$ fOverViewText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //there really aught to be a way to specify this ((GridData) fOverViewText.getLayoutData()).widthHint= 200; fOverViewBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0)); //$NON-NLS-1$ SWTUtil.setButtonDimensionHint(fOverViewBrowseButton); String str= fStore.getOverview(); if (str.equals("")) { //$NON-NLS-1$ //default fOverViewText.setEnabled(false); fOverViewBrowseButton.setEnabled(false); } else { fOverViewButton.setSelection(true); fOverViewText.setText(str); } createLabel(composite, SWT.NONE, JavadocExportMessages.getString("JavadocSpecificsWizardPage.extraoptionsfield.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 3, 0)); //$NON-NLS-1$ fExtraOptionsText= createText(composite, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.H_SCROLL | SWT.V_SCROLL, null, createGridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL, 3, 0)); //fExtraOptionsText.setSize(convertWidthInCharsToPixels(60), convertHeightInCharsToPixels(10)); str= fStore.getAdditionalParams(); fExtraOptionsText.setText(str); fJDK14Button= createButton(composite, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.jdk14mode.label"), createGridData(3)); //$NON-NLS-1$ fJDK14Button.setSelection(fStore.isJDK14Mode()); //Listeners fOverViewButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fOverViewBrowseButton, fOverViewText }) { public void validate() { doValidation(OVERVIEWSTATUS); } }); fOverViewText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(OVERVIEWSTATUS); } }); fOverViewBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { handleFileBrowseButtonPressed(fOverViewText, new String[] { "*.html" }, JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewbrowsedialog.title")); //$NON-NLS-1$ //$NON-NLS-2$ } }); } private void createAntGroup(Composite composite) { Composite c= new Composite(composite, SWT.NONE); c.setLayout(createGridLayout(3)); c.setLayoutData(createGridData(GridData.FILL_HORIZONTAL, 3, 0)); ((GridLayout) c.getLayout()).marginWidth= 0; fAntButton= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbutton.label"), createGridData(3)); //$NON-NLS-1$ createLabel(c, SWT.NONE, JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscripttext.label"), createGridData(GridData.HORIZONTAL_ALIGN_BEGINNING, 1, 0)); //$NON-NLS-1$ fAntText= createText(c, SWT.SINGLE | SWT.BORDER, null, createGridData(GridData.FILL_HORIZONTAL, 1, 0)); //there really aught to be a way to specify this ((GridData) fAntText.getLayoutData()).widthHint= 200; fAntText.setText(fStore.getAntpath()); fAntBrowseButton= createButton(c, SWT.PUSH, JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbrowse.label"), createGridData(GridData.HORIZONTAL_ALIGN_END, 1, 0)); //$NON-NLS-1$ SWTUtil.setButtonDimensionHint(fAntBrowseButton); fAntText.setEnabled(false); fAntBrowseButton.setEnabled(false); fCheckbrowser= createButton(c, SWT.CHECK, JavadocExportMessages.getString("JavadocSpecificsWizardPage.openbrowserbutton.label"), createGridData(3)); //$NON-NLS-1$ fCheckbrowser.setSelection(fStore.doOpenInBrowser()); fAntButton.addSelectionListener(new ToggleSelectionAdapter(new Control[] { fAntText, fAntBrowseButton }) { public void validate() { doValidation(ANTSTATUS); } }); fAntText.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { doValidation(ANTSTATUS); } }); fAntBrowseButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { String temp= fAntText.getText(); IPath path= new Path(temp); String file= path.lastSegment(); if (file == null) file= "javadoc.xml";//$NON-NLS-1$ path= path.removeLastSegments(1); temp= handleFolderBrowseButtonPressed(path.toOSString(), fAntText.getShell(), JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbrowsedialog.title"), JavadocExportMessages.getString("JavadocSpecificsWizardPage.antscriptbrowsedialog.label")); //$NON-NLS-1$ //$NON-NLS-2$ path= new Path(temp); path= path.addTrailingSeparator().append(file); fAntText.setText(path.toOSString()); } }); } //end method createExtraOptionsGroup private void doValidation(int val) { File file= null; String ext= null; Path path= null; switch (val) { case OVERVIEWSTATUS : fOverviewStatus= new StatusInfo(); if (fOverViewButton.getSelection()) { path= new Path(fOverViewText.getText()); file= path.toFile(); ext= path.getFileExtension(); if ((file == null) || !file.exists()) { fOverviewStatus.setError(JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewnotfound.error")); //$NON-NLS-1$ } else if ((ext == null) || !ext.equalsIgnoreCase("html")) { //$NON-NLS-1$ fOverviewStatus.setError(JavadocExportMessages.getString("JavadocSpecificsWizardPage.overviewincorrect.error")); //$NON-NLS-1$ } } break; case ANTSTATUS : fAntStatus= new StatusInfo(); if (fAntButton.getSelection()) { path= new Path(fAntText.getText()); ext= path.getFileExtension(); IPath antSeg= path.removeLastSegments(1); if ((!antSeg.isValidPath(antSeg.toOSString())) || (ext == null) || !(ext.equalsIgnoreCase("xml"))) //$NON-NLS-1$ fAntStatus.setError(JavadocExportMessages.getString("JavadocSpecificsWizardPage.antfileincorrect.error")); //$NON-NLS-1$ else if (path.toFile().exists()) fAntStatus.setWarning(JavadocExportMessages.getString("JavadocSpecificsWizardPage.antfileoverwrite.warning")); //$NON-NLS-1$ } break; } updateStatus(findMostSevereStatus()); } /* * @see JavadocWizardPage#onFinish() */ protected void updateStore() { String str= fExtraOptionsText.getText(); if (str.length() > 0) fStore.setAdditionalParams(str); else fStore.setAdditionalParams(""); //$NON-NLS-1$ if (fOverViewText.getEnabled()) fStore.setOverview(fOverViewText.getText()); else fStore.setOverview(""); //$NON-NLS-1$ //for now if there are multiple then the ant file is not stored for specific projects if (fAntText.getEnabled()) { fStore.setGeneralAntpath(fAntText.getText()); } fStore.setOpenInBrowser(fCheckbrowser.getSelection()); fStore.setJDK14Mode(fJDK14Button.getSelection()); } public void setVisible(boolean visible) { super.setVisible(visible); if (visible) { doValidation(OVERVIEWSTATUS); doValidation(ANTSTATUS); } } public void init() { updateStatus(new StatusInfo()); } private IStatus findMostSevereStatus() { return StatusUtil.getMostSevere(new IStatus[] { fAntStatus, fOverviewStatus }); } public boolean generateAnt() { return fAntButton.getSelection(); } }
51,954
Bug 51954 IOException while generating Javadoc
M7 build Try to generate Javadoc for the package org.eclipse.jdt.internal.corext.refactoring.participants.xml. java.io.IOException: CreateProcess: C:\apps\java\jdk1.4.2\bin\javadoc.exe -d c:\tmp\testdoc - sourcepath "C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \ui;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui\ui refactoring;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \core refactoring;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui \core extension" -classpath C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.jdt.ui\bin;C:\home \dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.ui\ui.jar;C:\home\dbaeume r\devel\workspaces\eclipse\3.0new\org.eclipse.core.runtime.compatibility\compat ibility.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.core.r untime\runtime.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse .osgi\osgi.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.osg i\core.jar;C:\home\dbaeumer\devel\workspaces\eclipse\3.0new\org.eclipse.osgi\re solver.jar;C:\home\dbaeumer\devel\workspaces\eclipse\&#148; at java.lang.Win32Process.create(Native Method) at java.lang.Win32Process.<init>(Win32Process.java:66) at java.lang.Runtime.execInternal(Native Method) at java.lang.Runtime.exec(Runtime.java:566) at java.lang.Runtime.exec(Runtime.java:491) at java.lang.Runtime.exec(Runtime.java:457) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.executeJavadocGeneratio n(JavadocWizard.java:228) at org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard.performFinish (JavadocWizard.java:191) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:608) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:321) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:402) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.jface.window.Window.runEventLoop(Window.java:647) at org.eclipse.jface.window.Window.open(Window.java:627) at org.eclipse.ui.actions.ExportResourcesAction.run (ExportResourcesAction.java:165) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:536) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:488) at org.eclipse.jface.action.ActionContributionItem$5.handleEvent (ActionContributionItem.java:420) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1550) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1526) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:265) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:257) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581)
resolved fixed
47eda9e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-20T19:00:50Z
2004-02-13T13:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizard.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation * Sebastian Davids <[email protected]> bug 38692 *******************************************************************************/ package org.eclipse.jdt.internal.ui.javadocexport; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IDebugEventSetListener; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.ILaunchConfigurationType; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.debug.core.ILaunchManager; import org.eclipse.debug.core.Launch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.ui.IDebugUIConstants; import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IWorkspaceDescription; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IExportWizard; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IWorkbench; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil; import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog; import org.eclipse.jdt.internal.ui.jarpackager.ConfirmSaveModifiedResourcesDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; public class JavadocWizard extends Wizard implements IExportWizard { private JavadocTreeWizardPage fJTWPage; private JavadocSpecificsWizardPage fJSWPage; private JavadocStandardWizardPage fJSpWPage; private IPath fDestination; private boolean fWriteCustom; private boolean fOpenInBrowser; private final String TreePageDesc= "JavadocTreePage"; //$NON-NLS-1$ private final String SpecificsPageDesc= "JavadocSpecificsPage"; //$NON-NLS-1$ private final String StandardPageDesc= "JavadocStandardPage"; //$NON-NLS-1$ private final int YES= 0; private final int YES_TO_ALL= 1; private final int NO= 2; private final int NO_TO_ALL= 3; private final String JAVADOC_ANT_INFORMATION_DIALOG= "javadocAntInformationDialog";//$NON-NLS-1$ private JavadocOptionsManager fStore; private IWorkspaceRoot fRoot; private IFile fXmlJavadocFile; //private ILaunchConfiguration fConfig; public JavadocWizard() { this(null); } public JavadocWizard(IFile xmlJavadocFile) { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_EXPORT_JAVADOC); setWindowTitle(JavadocExportMessages.getString("JavadocWizard.javadocwizard.title")); //$NON-NLS-1$ setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); fRoot= ResourcesPlugin.getWorkspace().getRoot(); fXmlJavadocFile= xmlJavadocFile; fWriteCustom= false; } /* * @see IWizard#performFinish() */ public boolean performFinish() { IJavaProject[] checkedProjects= fJTWPage.getCheckedProjects(); updateStore(checkedProjects); //If the wizard was not launched from an ant file store the setttings if (fXmlJavadocFile == null) { fStore.updateDialogSettings(getDialogSettings(), checkedProjects); } // Wizard will not run with unsaved files. if (!checkPreconditions(fStore.getSourceElements())) { return false; } fDestination= new Path(fStore.getDestination()); fDestination.toFile().mkdirs(); fOpenInBrowser= fStore.doOpenInBrowser(); //Ask if you wish to set the javadoc location for the projects (all) to //the location of the newly generated javadoc if (fStore.isFromStandard()) { try { URL newURL= fDestination.toFile().toURL(); List projs= new ArrayList(); //get javadoc locations for all projects for (int i= 0; i < checkedProjects.length; i++) { IJavaProject curr= checkedProjects[i]; URL currURL= JavaUI.getProjectJavadocLocation(curr); if (!newURL.equals(currURL)) { // currURL can be null //if not all projects have the same javadoc location ask if you want to change //them to have the same javadoc location projs.add(curr); } } if (!projs.isEmpty()) { setAllJavadocLocations((IJavaProject[]) projs.toArray(new IJavaProject[projs.size()]), newURL); } } catch (MalformedURLException e) { JavaPlugin.log(e); } } if (fJSWPage.generateAnt()) { //@Improve: make a better message OptionalMessageDialog.open(JAVADOC_ANT_INFORMATION_DIALOG, getShell(), JavadocExportMessages.getString("JavadocWizard.antInformationDialog.title"), null, JavadocExportMessages.getString("JavadocWizard.antInformationDialog.message"), MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); //$NON-NLS-1$ //$NON-NLS-2$ try { fStore.createXML(checkedProjects); } catch (CoreException e) { ExceptionHandler.handle(e, getShell(),JavadocExportMessages.getString("JavadocWizard.error.writeANT.title"), JavadocExportMessages.getString("JavadocWizard.error.writeANT.message")); //$NON-NLS-1$ //$NON-NLS-2$ } } if (!executeJavadocGeneration(fStore.createArgumentArray())) return false; return true; } private void updateStore(IJavaProject[] checkedProjects) { //writes the new settings to store fJTWPage.updateStore(checkedProjects); if (!fJTWPage.getCustom()) fJSpWPage.updateStore(); fJSWPage.updateStore(); } /* (non-Javadoc) * @see org.eclipse.jface.wizard.IWizard#performCancel() */ public boolean performCancel() { IJavaProject[] checkedProjects= fJTWPage.getCheckedProjects(); updateStore(checkedProjects); //If the wizard was not launched from an ant file store the setttings if (fXmlJavadocFile == null) { fStore.updateDialogSettings(getDialogSettings(), checkedProjects); } return super.performCancel(); } private void setAllJavadocLocations(IJavaProject[] projects, URL newURL) { for (int j= 0; j < projects.length; j++) { IJavaProject iJavaProject= projects[j]; String message= JavadocExportMessages.getFormattedString("JavadocWizard.updatejavadoclocation.message", new String[] { iJavaProject.getElementName(), fDestination.toOSString()}); //$NON-NLS-1$ String[] buttonlabels= new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL }; MessageDialog dialog= new MessageDialog(getShell(), JavadocExportMessages.getString("JavadocWizard.updatejavadocdialog.label"), Dialog.getImage(Dialog.DLG_IMG_QUESTION), message, 4, buttonlabels, 1);//$NON-NLS-1$ switch (dialog.open()) { case YES : JavaUI.setProjectJavadocLocation(iJavaProject, newURL); break; case YES_TO_ALL : for (int i= j; i < projects.length; i++) { iJavaProject= projects[i]; JavaUI.setProjectJavadocLocation(iJavaProject, newURL); j++; } break; case NO_TO_ALL : j= projects.length; break; case NO : default : break; } } } private boolean executeJavadocGeneration(String[] args) { Process process= null; try { process= Runtime.getRuntime().exec(args); if (process != null) { // contruct a formatted command line for the process properties StringBuffer buf= new StringBuffer(); for (int i= 0; i < args.length; i++) { buf.append(args[i]); buf.append(' '); } IDebugEventSetListener listener= new JavadocDebugEventListener(getShell().getDisplay()); DebugPlugin.getDefault().addDebugEventListener(listener); ILaunchConfigurationWorkingCopy wc= null; try { ILaunchConfigurationType lcType= DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION); String name= JavadocExportMessages.getString("JavadocWizard.launchconfig.name"); //$NON-NLS-1$ wc= lcType.newInstance(null, name); wc.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true); ILaunch newLaunch= new Launch(wc, ILaunchManager.RUN_MODE, null); IProcess iprocess= DebugPlugin.newProcess(newLaunch, process, JavadocExportMessages.getString("JavadocWizard.javadocprocess.label")); //$NON-NLS-1$ iprocess.setAttribute(IProcess.ATTR_CMDLINE, buf.toString()); DebugPlugin.getDefault().getLaunchManager().addLaunch(newLaunch); } catch (CoreException e) { String title= JavadocExportMessages.getString("JavadocWizard.error.title"); //$NON-NLS-1$ String message= JavadocExportMessages.getString("JavadocWizard.launch.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } return true; } } catch (IOException e) { String title= JavadocExportMessages.getString("JavadocWizard.error.title"); //$NON-NLS-1$ String message= JavadocExportMessages.getString("JavadocWizard.exec.error.message"); //$NON-NLS-1$ IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, e.getMessage(), e); ExceptionHandler.handle(new CoreException(status), getShell(), title, message); return false; } return false; } /** * Creates a list of all CompilationUnits and extracts from that list a list of dirty * files. The user is then asked to confirm if those resources should be saved or * not. * * @param elements * @return <code>true</code> if all preconditions are satisfied otherwise false */ private boolean checkPreconditions(IJavaElement[] elements) { ArrayList resources= new ArrayList(); for (int i= 0; i < elements.length; i++) { if (elements[i] instanceof ICompilationUnit) { resources.add(elements[i].getResource()); } } //message could be null IFile[] unSavedFiles= getUnsavedFiles(resources); return saveModifiedResourcesIfUserConfirms(unSavedFiles); } /** * Returns the files which are not saved and which are * part of the files being exported. * * @param resources * @return an array of unsaved files */ private IFile[] getUnsavedFiles(List resources) { IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors(); Set unsavedFiles= new HashSet(dirtyEditors.length); if (dirtyEditors.length > 0) { for (int i= 0; i < dirtyEditors.length; i++) { if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) { IFile dirtyFile= ((IFileEditorInput) dirtyEditors[i].getEditorInput()).getFile(); if (resources.contains(dirtyFile)) { unsavedFiles.add(dirtyFile); } } } } return (IFile[]) unsavedFiles.toArray(new IFile[unsavedFiles.size()]); } /** * Asks to confirm to save the modified resources * and save them if OK is pressed. Must be run in the display thread. * * @param dirtyFiles * @return true if user pressed OK and save was successful. */ private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) { if (confirmSaveModifiedResources(dirtyFiles)) { try { if (saveModifiedResources(dirtyFiles)) return true; } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.message")); //$NON-NLS-1$ //$NON-NLS-2$ } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.message")); //$NON-NLS-1$ //$NON-NLS-2$ } } return false; } /** * Asks the user to confirm to save the modified resources. * * @param dirtyFiles * @return true if user pressed OK. */ private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) { if (dirtyFiles == null || dirtyFiles.length == 0) return true; // Get display for further UI operations Display display= getShell().getDisplay(); if (display == null || display.isDisposed()) return false; // Ask user to confirm saving of all files final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(getShell(), dirtyFiles); final int[] intResult= new int[1]; Runnable runnable= new Runnable() { public void run() { intResult[0]= dlg.open(); } }; display.syncExec(runnable); return intResult[0] == IDialogConstants.OK_ID; } /** * Save all of the editors in the workbench. Must be run in the display thread. * * @param dirtyFiles * @return true if successful. * @throws CoreException * @throws InvocationTargetException */ private boolean saveModifiedResources(final IFile[] dirtyFiles) throws CoreException, InvocationTargetException { IWorkspace workspace= ResourcesPlugin.getWorkspace(); IWorkspaceDescription description= workspace.getDescription(); boolean autoBuild= description.isAutoBuilding(); description.setAutoBuilding(false); try { workspace.setDescription(description); // This save operation can not be canceled. try { new ProgressMonitorDialog(getShell()).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles)); } finally { description.setAutoBuilding(autoBuild); workspace.setDescription(description); } } catch (InterruptedException ex) { return false; } return true; } private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) { return new IRunnableWithProgress() { public void run(final IProgressMonitor pm) { IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors(); String name= JavadocExportMessages.getString("JavadocWizard.savetask.name"); //$NON-NLS-1$ pm.beginTask(name, editorsToSave.length); try { List dirtyFilesList= Arrays.asList(dirtyFiles); for (int i= 0; i < editorsToSave.length; i++) { if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) { IFile dirtyFile= ((IFileEditorInput) editorsToSave[i].getEditorInput()).getFile(); if (dirtyFilesList.contains((dirtyFile))) editorsToSave[i].doSave(new SubProgressMonitor(pm, 1)); } pm.worked(1); } } finally { pm.done(); } } }; } /* * @see IWizard#addPages() */ public void addPages() { fJTWPage= new JavadocTreeWizardPage(TreePageDesc, fStore); fJSWPage= new JavadocSpecificsWizardPage(SpecificsPageDesc, fStore); fJSpWPage= new JavadocStandardWizardPage(StandardPageDesc, fJTWPage, fStore); super.addPage(fJTWPage); super.addPage(fJSpWPage); super.addPage(fJSWPage); fJTWPage.init(); fJSpWPage.init(); fJSWPage.init(); } public void init(IWorkbench workbench, IStructuredSelection structuredSelection) { List selected= structuredSelection.toList(); if (selected.isEmpty()) { IJavaElement element= EditorUtility.getActiveEditorJavaInput(); selected= new ArrayList(); selected.add(element); } fStore= new JavadocOptionsManager(fXmlJavadocFile, getDialogSettings(), selected); } private void refresh(IPath path) { if (fRoot.findContainersForLocation(path).length > 0) { try { fRoot.refreshLocal(IResource.DEPTH_INFINITE, null); } catch (CoreException e) { JavaPlugin.log(e); } } } private void spawnInBrowser(Display display) { if (fOpenInBrowser) { try { IPath indexFile= fDestination.append("index.html"); //$NON-NLS-1$ URL url= indexFile.toFile().toURL(); OpenBrowserUtil.open(url, display, getWindowTitle()); } catch (MalformedURLException e) { JavaPlugin.log(e); } } } private class JavadocDebugEventListener implements IDebugEventSetListener { private Display fDisplay; public JavadocDebugEventListener(Display display) { fDisplay= display; } public void handleDebugEvents(DebugEvent[] events) { for (int i= 0; i < events.length; i++) { if (events[i].getKind() == DebugEvent.TERMINATE) { try { if (!fWriteCustom) { refresh(fDestination); //If destination of javadoc is in workspace then refresh workspace spawnInBrowser(fDisplay); } } finally { DebugPlugin.getDefault().removeDebugEventListener(this); } return; } } } } public IWizardPage getNextPage(IWizardPage page) { if (page instanceof JavadocTreeWizardPage) { if (!fJTWPage.getCustom()) { return fJSpWPage; } return fJSWPage; } else if (page instanceof JavadocSpecificsWizardPage) { return null; } else if (page instanceof JavadocStandardWizardPage) return fJSWPage; else return null; } public IWizardPage getPreviousPage(IWizardPage page) { if (page instanceof JavadocSpecificsWizardPage) { if (!fJTWPage.getCustom()) { return fJSpWPage; } return fJSWPage; } else if (page instanceof JavadocTreeWizardPage) { return null; } else if (page instanceof JavadocStandardWizardPage) return fJTWPage; else return null; } }
52,750
Bug 52750 correct indentation messes with comment boxes
3m7 /* ******** */ /* */ /* ******** */ comes out /* ******** */ /* */ /* ******** */
resolved fixed
32c050f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T10:50:49Z
2004-02-21T21:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/IndentAction.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.actions; import java.util.ResourceBundle; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.widgets.Display; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner; import org.eclipse.jdt.internal.ui.text.JavaIndenter; import org.eclipse.jdt.internal.ui.text.javadoc.JavaDocAutoIndentStrategy; /** * 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 org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner * @see org.eclipse.jdt.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 <code>true</code>, 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 <code>bundle</code> * @param editor the text editor * @param isTabAction whether the action should insert tabs if over the indentation */ public IndentAction(ResourceBundle bundle, String prefix, ITextEditor editor, boolean isTabAction) { super(bundle, prefix, editor); fIsTabAction= isTabAction; } /* * @see org.eclipse.jface.action.Action#run() */ public void run() { // update has been called by the framework if (!isEnabled() || !validateEditorInputState()) return; ITextSelection selection= getSelection(); final IDocument document= getDocument(); if (document != null) { final int offset= selection.getOffset(); final int length= selection.getLength(); final Position end= new Position(offset + length); final int firstLine, nLines; fCaretOffset= -1; try { document.addPosition(end); firstLine= document.getLineOfOffset(offset); // check for marginal (zero-length) lines int minusOne= length == 0 ? 0 : 1; nLines= document.getLineOfOffset(offset + length - minusOne) - firstLine + 1; } catch (BadLocationException e) { // will only happen on concurrent modification JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "", e)); //$NON-NLS-1$ return; } Runnable runnable= new Runnable() { public void run() { IRewriteTarget target= (IRewriteTarget)getTextEditor().getAdapter(IRewriteTarget.class); if (target != null) { target.beginCompoundChange(); 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); } // 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; } else if (nLines > 1) { newOffset= offset; newLength= end.getOffset() - offset; } else { newOffset= fCaretOffset; newLength= 0; } // always reset the selection if anything was replaced // but not when we had a singleline nontab invocation if (newOffset != -1 && (hasChanged || newOffset != offset || newLength != length)) selectAndReveal(newOffset, newLength); document.removePosition(end); } catch (BadLocationException e) { // will only happen on concurrent modification JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK, "ConcurrentModification in IndentAction", e)); //$NON-NLS-1$ } finally { if (target != null) { target.endCompoundChange(); target.setRedraw(true); } } } }; if (nLines > 50) { Display display= getTextEditor().getEditorSite().getWorkbenchWindow().getShell().getDisplay(); BusyIndicator.showWhile(display, runnable); } else runnable.run(); } } /** * Selects the given range on the editor. * * @param newOffset the selection offset * @param newLength the selection range */ private void selectAndReveal(int newOffset, int newLength) { Assert.isTrue(newOffset >= 0); Assert.isTrue(newLength >= 0); ITextEditor editor= getTextEditor(); if (editor instanceof JavaEditor) { ISourceViewer viewer= ((JavaEditor)editor).getViewer(); if (viewer != null) viewer.setSelectedRange(newOffset, newLength); } else // this is too intrusive, but will never get called anyway getTextEditor().selectAndReveal(newOffset, newLength); } /** * Indents a single line using the java heuristic scanner. Javadoc and multiline comments are * indented as specified by the <code>JavaDocAutoIndentStrategy</code>. * * @param document the document * @param line the line to be indented * @param caret the caret position * @param indenter the java indenter * @param scanner the heuristic scanner * @return <code>true</code> if <code>document</code> was modified, <code>false</code> otherwise * @throws BadLocationException if the document got changed concurrently */ private boolean indentLine(IDocument document, int line, int caret, JavaIndenter indenter, JavaHeuristicScanner scanner) 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, IJavaPartitions.JAVA_PARTITIONING, offset); String type= partition.getType(); if (partition.getOffset() < offset && type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { // TODO this is a hack // what I want to do // new JavaDocAutoIndentStrategy().indentLineAtOffset(document, offset); // return; int start= 0; if (line > 0) { 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(IJavaPartitions.JAVA_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(IJavaPartitions.JAVA_SINGLE_LINE_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= JavaPlugin.getDefault().getPreferenceStore().getInt(ExtendedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH); while (slashes > 0 && computed.length() > 0) { char c= computed.charAt(0); if (c == '\t') if (slashes > tabSize) slashes-= tabSize; else break; else if (c == ' ') slashes--; else break; computed.deleteCharAt(0); } indent= document.get(offset, wsStart - offset) + computed; } } // standard java indentation if (indent == null) { StringBuffer computed= indenter.computeIndentation(offset); if (computed != null) indent= computed.toString(); else indent= new String(); } // change document: // get current white space int lineLength= currentLine.getLength(); int end= scanner.findNonWhitespaceForwardInAnyPartition(wsStart, offset + lineLength); if (end == JavaHeuristicScanner.NOT_FOUND) end= offset + lineLength; int length= end - offset; String currentIndent= document.get(offset, length); // if we are right before the text start / line end, and already after the insertion point // then just insert a tab. if (fIsTabAction && caret == end && whiteSpaceLength(currentIndent) >= whiteSpaceLength(indent)) { String tab= getTabEquivalent(); document.replace(caret, 0, tab); fCaretOffset= caret + tab.length(); return true; } // set the caret offset so it can be used when setting the selection if (caret >= offset && caret <= end) fCaretOffset= offset + indent.length(); else fCaretOffset= -1; // only change the document if it is a real change if (!indent.equals(currentIndent)) { document.replace(offset, length, indent); return true; } else return false; } /** * Returns the size in characters of a string. All characters count one, tabs count the editor's * preference for the tab display * * @param indent the string to be measured. * @return */ private int whiteSpaceLength(String indent) { if (indent == null) return 0; else { int size= 0; int l= indent.length(); int tabSize= JavaPlugin.getDefault().getPreferenceStore().getInt(ExtendedTextEditorPreferenceConstants.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. * * @return a string representing one tab in the editor, never <code>null</code> */ private String getTabEquivalent() { String tab; if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SPACES_FOR_TABS)) { int size= JavaCore.getPlugin().getPluginPreferences().getInt(JavaCore.FORMATTER_TAB_SIZE); StringBuffer buf= new StringBuffer(); for (int i= 0; i< size; i++) buf.append(' '); tab= buf.toString(); } else tab= "\t"; //$NON-NLS-1$ return tab; } /** * Returns the editor's selection provider. * * @return the editor's selection provider or <code>null</code> */ private ISelectionProvider getSelectionProvider() { ITextEditor editor= getTextEditor(); if (editor != null) { return editor.getSelectionProvider(); } return null; } /* * @see org.eclipse.ui.texteditor.IUpdate#update() */ public void update() { super.update(); if (isEnabled()) if (fIsTabAction) setEnabled(canModifyEditor() && isSmartMode() && isValidSelection()); else setEnabled(canModifyEditor() && !getSelection().isEmpty()); } /** * Returns if the current selection is valid, i.e. whether it is empty and the caret in the * whitespace at the start of a line, or covers multiple lines. * * @return <code>true</code> if the selection is valid for an indent operation */ private boolean isValidSelection() { ITextSelection selection= getSelection(); if (selection.isEmpty()) return false; int offset= selection.getOffset(); int length= selection.getLength(); IDocument document= getDocument(); if (document == null) return false; try { IRegion firstLine= document.getLineInformationOfOffset(offset); int lineOffset= firstLine.getOffset(); // either the selection has to be empty and the caret in the WS at the line start // or the selection has to extend over multiple lines if (length == 0) return document.get(lineOffset, offset - lineOffset).trim().length() == 0; else // return lineOffset + firstLine.getLength() < offset + length; return false; // only enable for empty selections for now } catch (BadLocationException e) { } return false; } /** * Returns the smart preference state. * * @return <code>true</code> if smart mode is on, <code>false</code> otherwise */ private boolean isSmartMode() { ITextEditor editor= getTextEditor(); if (editor instanceof ITextEditorExtension3) return ((ITextEditorExtension3) editor).getInsertMode() == ITextEditorExtension3.SMART_INSERT; return false; } /** * Returns the document currently displayed in the editor, or <code>null</code> if none can be * obtained. * * @return the current document or <code>null</code> */ private IDocument getDocument() { ITextEditor editor= getTextEditor(); if (editor != null) { IDocumentProvider provider= editor.getDocumentProvider(); IEditorInput input= editor.getEditorInput(); if (provider != null && input != null) return provider.getDocument(input); } return null; } /** * Returns the selection on the editor or an invalid selection if none can be obtained. Returns * never <code>null</code>. * * @return the current selection, never <code>null</code> */ private ITextSelection getSelection() { ISelectionProvider provider= getSelectionProvider(); if (provider != null) { ISelection selection= provider.getSelection(); if (selection instanceof ITextSelection) return (ITextSelection) selection; } // null object return TextSelection.emptySelection(); } }
47,316
Bug 47316 [Junit] Add support to run/re-run an individual test which requires some setup
(based on a discussion with Dirk) The JUnit plug-in supports to run or re-run a single test. However, this only works for simple tests which don't depend on being decorated by some setup. In the case of decorated test suites you always have to run the entire suite and you cannot run an individual test. Proposal: A decorated test suite is created in a static suite() method: class SomeTest: public static Test suite() { return new SomeSetup(new TestSuite(SomeTest.class)); } To decorate a single test method clients can provide a similar method called setUpTest: class SomeTest: public static Test setUpTest(Test someTest) { return new SomeSetup(someTest); } This method will be invoked by the JUnit run-time when someTest is about to be executed indivudually (e.g. run a single test, re-rerun a failed test). Instead of executing "someTest" the Test returned from setUpTest will be executed. I've released a first version into head, pls let me know whether this addresses your needs.
resolved fixed
d16ecfa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:55:30Z
2003-11-23T20:40:00Z
org.eclipse.jdt.ui.tests.refactoring/test
47,316
Bug 47316 [Junit] Add support to run/re-run an individual test which requires some setup
(based on a discussion with Dirk) The JUnit plug-in supports to run or re-run a single test. However, this only works for simple tests which don't depend on being decorated by some setup. In the case of decorated test suites you always have to run the entire suite and you cannot run an individual test. Proposal: A decorated test suite is created in a static suite() method: class SomeTest: public static Test suite() { return new SomeSetup(new TestSuite(SomeTest.class)); } To decorate a single test method clients can provide a similar method called setUpTest: class SomeTest: public static Test setUpTest(Test someTest) { return new SomeSetup(someTest); } This method will be invoked by the JUnit run-time when someTest is about to be executed indivudually (e.g. run a single test, re-rerun a failed test). Instead of executing "someTest" the Test returned from setUpTest will be executed. I've released a first version into head, pls let me know whether this addresses your needs.
resolved fixed
d16ecfa
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:55:30Z
2003-11-23T20:40:00Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
org.eclipse.jdt.ui/core
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractConstantRefactoring.java
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
org.eclipse.jdt.ui/core
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
org.eclipse.jdt.ui/core
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
org.eclipse.jdt.ui/core
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractTempRefactoring.java
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
org.eclipse.jdt.ui/ui
52,352
Bug 52352 refactor: extract local variable: default: no selection of ... for literal expressions
When I am extracting a local variable from a trivial/literal expression, e.g. true, 100, ... I do NOT want to replace occurrences of that expression, because the next expression e.g. true may have a totally independent/orthogonal semantic and value. In all other cases (complex expressions) the current default is o.k. best regards Thorsten van Ellen
resolved fixed
5c5c2ca
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T11:58:56Z
2004-02-18T10:26:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java
52,476
Bug 52476 [painting] redraw behavior
build M7 Annotated method AnnotationPainter.handleDrawRequest with a repaint counter. 1) Open TestCase.java 2) add line >String s= < to tearDown method, set caret at end of line 3) spell checking enabled, otherwise default settings 3) type a single space -> 1 immediate repaint, 3 after timeout 4) type " -> auto inserted closing " + linked mode -> 10 immediate repaints, 3 after timeout
resolved fixed
4f2336a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T13:51:48Z
2004-02-19T14:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedUIControl.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.link; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.ShellListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelExtension; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.link.contentassist.ContentAssistant2; /** * The UI for linked mode. Detects events that influence behaviour of the * linked position UI and acts upon them. * * @since 3.0 */ public class LinkedUIControl { /* cycle constants */ /** * Constant indicating that this UI should never cycle from the last * position to the first and vice versa. */ public static final int CYCLE_NEVER= 0; /** * Constant indicating that this UI should always cycle from the last * position to the first and vice versa. */ public static final int CYCLE_ALWAYS= 1; /** * Constant indicating that this UI should cycle from the last position to * the first and vice versa if its environment is not nested. */ public static final int CYCLE_WHEN_NO_PARENT= 2; /** * Listens on a styled text for events before (Verify) and after (Modify) * modifications. Used to update the caret after linked changes. */ private final class CaretListener implements ModifyListener, VerifyListener { /* * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) */ public void modifyText(ModifyEvent e) { updateSelection(e); } /* * @see org.eclipse.swt.events.VerifyListener#verifyText(org.eclipse.swt.events.VerifyEvent) */ public void verifyText(VerifyEvent e) { rememberSelection(e); } } /** * A link target consists of a viewer and gets notified if the linked UI on * it is being shown. * * @since 3.0 */ public static abstract class LinkedUITarget { /** * Returns the viewer represented by this target, never <code>null</code>. * * @return the viewer associated with this target. */ abstract ITextViewer getViewer(); /** * Called by the linked UI when this target is being shown. An * implementation could for example ensure that the corresponding * editor is showing. */ abstract void enter(); /** * The viewer's text widget is initialized when the UI first connects * to the viewer and never changed thereafter. This is to keep the * reference of the widget that we have registered our listeners with, * as the viewer, when it gets disposed, does not remember it, resulting * in a situation where we cannot uninstall the listeners and a memory leak. */ StyledText fWidget; /** The cached shell - same reason as fWidget. */ Shell fShell; /** The registered listener, or <code>null</code>. */ LinkedUIKeyListener fKeyListener; /** The cached custom annotation model. */ LinkedPositionAnnotations fAnnotationModel; } private static final class EmptyTarget extends LinkedUITarget { private ITextViewer fTextViewer; /** * @param viewer the viewer */ public EmptyTarget(ITextViewer viewer) { Assert.isNotNull(viewer); fTextViewer= viewer; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#getViewer() */ public ITextViewer getViewer() { return fTextViewer; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#enter() */ public void enter() { } } /** * An <code>ILinkedUITarget</code> with an associated editor, which is * brought to the top when a linked position in its viewer is jumped to. * * @since 3.0 */ public static class EditorTarget extends LinkedUITarget { /** The text viewer. */ protected final ITextViewer fTextViewer; /** The editor displaying the viewer. */ protected final ITextEditor fTextEditor; /** * Creates a new instance. * * @param viewer the viewer * @param editor the editor displaying <code>viewer</code>, or <code>null</code> */ public EditorTarget(ITextViewer viewer, ITextEditor editor) { Assert.isNotNull(viewer); fTextViewer= viewer; fTextEditor= editor; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#getViewer() */ public ITextViewer getViewer() { return fTextViewer; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#enter() */ public void enter() { if (fTextEditor != null) return; IWorkbenchPage page= fTextEditor.getEditorSite().getPage(); if (page != null) { page.bringToTop(fTextEditor); } fTextEditor.setFocus(); } } /** * Listens for state changes in the model. */ private final class ExitListener implements ILinkedListener { /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void left(LinkedEnvironment environment, int flags) { leave(ILinkedListener.EXIT_ALL | flags); } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void suspend(LinkedEnvironment environment) { disconnect(); redraw(); } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void resume(LinkedEnvironment environment, int flags) { if ((flags & ILinkedListener.EXIT_ALL) != 0) { leave(flags); } else { connect(); if ((flags & ILinkedListener.SELECT) != 0) select(); redraw(); } } } /** * Exit flags returned if a custom exit policy wants to exit linked mode. */ public static class ExitFlags { /** The flags to return in the <code>leave</code> method. */ public int flags; /** The doit flag of the checked <code>VerifyKeyEvent</code>. */ public boolean doit; /** * Creates a new instance. * * @param flags the exit flags * @param doit the doit flag for the verify event */ public ExitFlags(int flags, boolean doit) { this.flags= flags; this.doit= doit; } } /** * An exit policy can be registered by a caller to get custom exit * behaviour. */ public interface IExitPolicy { /** * Checks whether the linked mode should be left after receiving the * given <code>VerifyEvent</code> and selection. Note that the event * carries widget coordinates as opposed to <code>offset</code> and * <code>length</code> which are document coordinates. * * @param environment the linked environment * @param event the verify event * @param offset the offset of the current selection * @param length the length of the current selection * @return valid exit flags or <code>null</code> if no special action * should be taken */ ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length); } /** * A NullObject implementation of <code>IExitPolicy</code>. */ private static class NullExitPolicy implements IExitPolicy { /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.IExitPolicy#doExit(org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length) { return null; } } /** * Listens for shell events and acts upon them. */ private class LinkedUICloser implements ShellListener { public void shellActivated(ShellEvent e) { } public void shellClosed(ShellEvent e) { leave(ILinkedListener.EXIT_ALL); } public void shellDeactivated(ShellEvent e) { // T ODO reenable after debugging // if (true) return; // from LinkedPositionUI: // 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 // Seems to be no problem // Better: // 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 || fCurrentTarget == null || (text= fCurrentTarget.fWidget) == null || text.isDisposed() || (display= text.getDisplay()) == null || display.isDisposed()) { leave(ILinkedListener.EXIT_ALL); } else { // Post in UI thread since the assistant popup will only get the focus after we lose it. display.asyncExec(new Runnable() { public void run() { if (fIsActive && (fAssistant == null || !fAssistant.hasFocus())) { leave(ILinkedListener.EXIT_ALL); } } }); } } public void shellDeiconified(ShellEvent e) { } public void shellIconified(ShellEvent e) { leave(ILinkedListener.EXIT_ALL); } } /** * Listens for key events, checks the exit policy for custom exit * strategies but defaults to handling Tab, Enter, and Escape. */ private class LinkedUIKeyListener implements VerifyKeyListener { private boolean fIsEnabled= true; public void verifyKey(VerifyEvent event) { if (!event.doit || !fIsEnabled) return; Point selection= fCurrentTarget.getViewer().getSelectedRange(); int offset= selection.x; int length= selection.y; // if the custom exit policy returns anything, use that ExitFlags exitFlags= fExitPolicy.doExit(fEnvironment, event, offset, length); if (exitFlags != null) { leave(exitFlags.flags); event.doit= exitFlags.doit; return; } // standard behaviour: // (Shift+)Tab: jumps from position to position, depending on cycle mode // Enter: accepts all entries and leaves all (possibly stacked) environments, the last sets the caret // Esc: accepts all entries and leaves all (possibly stacked) environments, the caret stays // ? what do we do to leave one level of a cycling environment that is stacked? // -> This is only the case if the level was set up with forced cycling (CYCLE_ALWAYS), in which case // the caller is sure that one does not need by-level exiting. switch (event.character) { // [SHIFT-]TAB = hop between edit boxes case 0x09: if (!(fExitPosition != null && fExitPosition.includes(offset)) && !fEnvironment.anyPositionContains(offset)) { // outside any edit box -> leave (all? TODO should only leave the affected, level and forward to the next upper) leave(ILinkedListener.EXIT_ALL); break; } else { if (event.stateMask == SWT.SHIFT) previous(); else next(); } event.doit= false; break; // ENTER case 0x0A: // Ctrl+Enter on WinXP case 0x0D: if (fAssistant != null && fAssistant.wasProposalChosen()) { // don't exit as it was really just the proposal that was chosen next(); event.doit= false; break; } else if ((fExitPosition != null && fExitPosition.includes(offset)) || !fEnvironment.anyPositionContains(offset)) { // outside any edit box or on exit position -> leave (all? TODO should only leave the affected, level and forward to the next upper) leave(ILinkedListener.EXIT_ALL); break; } else { // normal case: exit entire stack and put caret to final position leave(ILinkedListener.EXIT_ALL | ILinkedListener.UPDATE_CARET); event.doit= false; break; } // ESC case 0x1B: // exit entire stack and leave caret leave(ILinkedListener.EXIT_ALL); event.doit= false; break; default: if (event.character != 0) { if (!controlUndoBehavior(offset, length)) { leave(ILinkedListener.EXIT_ALL); break; } } } } private boolean controlUndoBehavior(int offset, int length) { LinkedPosition position= fEnvironment.findPosition(new LinkedPosition(fCurrentTarget.getViewer().getDocument(), offset, length, LinkedPositionGroup.NO_STOP)); if (position != null) { ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer(); IRewriteTarget target= extension.getRewriteTarget(); // if the last position is not the same and there is an open change: close it. if (!position.equals(fPreviousPosition) && fHasOpenCompoundChange) { target.endCompoundChange(); fHasOpenCompoundChange= false; } // we are editing - if there is no open change: open one if (!fHasOpenCompoundChange) { target.beginCompoundChange(); fHasOpenCompoundChange= true; } } fPreviousPosition= position; return fPreviousPosition != null; } /** * @param enabled the new enabled state */ public void setEnabled(boolean enabled) { fIsEnabled= enabled; } } /** * Installed as post selection listener on the watched viewer. Updates the * linked position after cursor movement, even to positions not in the * iteration list. */ private class MySelectionListener implements ISelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { ISelection selection= event.getSelection(); if (selection instanceof ITextSelection) { ITextSelection textsel= (ITextSelection) selection; if (event.getSelectionProvider() instanceof ITextViewer) { IDocument doc= ((ITextViewer) event.getSelectionProvider()).getDocument(); if (doc != null) { int offset= textsel.getOffset(); int length= textsel.getLength(); if (offset >= 0 && length >= 0) { LinkedPosition find= new LinkedPosition(doc, offset, length, LinkedPositionGroup.NO_STOP); LinkedPosition pos= fEnvironment.findPosition(find); if (pos == null && fExitPosition != null && fExitPosition.includes(find)) pos= fExitPosition; if (pos != null) switchPosition(pos, false, false); } } } } } } /** The current viewer. */ private LinkedUITarget fCurrentTarget; /** The manager of the linked positions we provide a UI for. */ private LinkedEnvironment fEnvironment; /** The set of viewers we manage. */ private LinkedUITarget[] fTargets; /** The iterator over the tab stop positions. */ private TabStopIterator fIterator; /* Our team of event listeners */ /** The shell listener. */ private LinkedUICloser fCloser= new LinkedUICloser(); /** The linked listener. */ private ILinkedListener fLinkedListener= new ExitListener(); /** The selection listener. */ private MySelectionListener fSelectionListener= new MySelectionListener(); /** The styled text listener. */ private CaretListener fCaretListener= new CaretListener(); /** The last caret position, used by fCaretListener. */ private final Position fCaretPosition= new Position(0, 0); /** The exit policy to control custom exit behaviour */ private IExitPolicy fExitPolicy= new NullExitPolicy(); /** The current frame position shown in the UI, or <code>null</code>. */ private LinkedPosition fFramePosition; /** The last visisted position, used for undo / redo. */ private LinkedPosition fPreviousPosition; /** The content assistant used to show proposals. */ private ContentAssistant2 fAssistant; /** The exit position. */ private LinkedPosition fExitPosition; /** State indicator to prevent multiple invocation of leave. */ private boolean fIsActive= false; private IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(getCategory()); private boolean fDoContextInfo= false; private boolean fHasOpenCompoundChange= false; /** * Creates a new UI on the given model (environment) and the set of * viewers. The environment must provide a tab stop sequence with a * non-empty list of tab stops. * * @param environment the linked position model * @param targets the non-empty list of targets upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, LinkedUITarget[] targets) { constructor(environment, targets); } /** * Conveniance ctor for just one viewer. * * @param environment the linked position model * @param viewer the viewer upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, ITextViewer viewer) { constructor(environment, new LinkedUITarget[]{new EmptyTarget(viewer)}); } /** * Conveniance ctor for multiple viewers. * * @param environment the linked position model * @param viewers the non-empty list of viewers upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, ITextViewer[] viewers) { LinkedUITarget[] array= new LinkedUITarget[viewers.length]; for (int i= 0; i < array.length; i++) { array[i]= new EmptyTarget(viewers[i]); } constructor(environment, array); } /** * Conveniance ctor for one target. * * @param environment the linked position model * @param target the target upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, LinkedUITarget target) { constructor(environment, new LinkedUITarget[]{target}); } /** * This does the actual constructor work. * * @param environment the linked position model * @param targets the non-empty array of targets upon which the linked ui * should act */ private void constructor(LinkedEnvironment environment, LinkedUITarget[] targets) { Assert.isNotNull(environment); Assert.isNotNull(targets); Assert.isTrue(targets.length > 0); Assert.isTrue(environment.getTabStopSequence().size() > 0); fEnvironment= environment; fTargets= targets; fCurrentTarget= targets[0]; fIterator= new TabStopIterator(fEnvironment.getTabStopSequence()); fIterator.setCycling(!fEnvironment.isNested()); fEnvironment.addLinkedListener(fLinkedListener); fAssistant= new ContentAssistant2(); fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); fCaretPosition.delete(); } /** * Starts this UI on the first position. */ public void enter() { fIsActive= true; connect(); next(); } /** * Sets an <code>IExitPolicy</code> to customize the exit behaviour of * this linked UI. * * @param policy the exit policy to use. */ public void setExitPolicy(IExitPolicy policy) { fExitPolicy= policy; } /** * Sets the exit position to move the caret to when linked mode is exited. * * @param target the target where the exit position is located * @param offset the offset of the exit position * @param length the length of the exit position (in case there should be a * selection) * @param sequence set to the tab stop position of the exit position, or * <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop. * @throws BadLocationException if the position is not valid in the * viewer's document */ public void setExitPosition(LinkedUITarget target, int offset, int length, int sequence) throws BadLocationException { // remove any existing exit position if (fExitPosition != null) { fExitPosition.getDocument().removePosition(fExitPosition); fIterator.removePosition(fExitPosition); fExitPosition= null; } IDocument doc= target.getViewer().getDocument(); if (doc == null) return; fExitPosition= new LinkedPosition(doc, offset, length, sequence); doc.addPosition(fExitPosition); // gets removed in leave() if (sequence != LinkedPositionGroup.NO_STOP) fIterator.addPosition(fExitPosition); } /** * Sets the exit position to move the caret to when linked mode is exited. * * @param viewer the viewer where the exit position is located * @param offset the offset of the exit position * @param length the length of the exit position (in case there should be a * selection) * @param sequence set to the tab stop position of the exit position, or * <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop. * @throws BadLocationException if the position is not valid in the * viewer's document */ public void setExitPosition(ITextViewer viewer, int offset, int length, int sequence) throws BadLocationException { setExitPosition(new EditorTarget(viewer, null), offset, length, sequence); } /** * Sets the cycling mode to either of <code>CYCLING_ALWAYS</code>, * <code>CYCLING_NEVER</code>, or <code>CYCLING_WHEN_NO_PARENT</code>, * which is the default. * * @param mode the new cycling mode. */ public void setCyclingMode(int mode) { if (mode == CYCLE_ALWAYS || mode == CYCLE_WHEN_NO_PARENT && !fEnvironment.isNested()) fIterator.setCycling(true); else fIterator.setCycling(false); } void next() { if (fIterator.hasNext(fFramePosition)) { switchPosition(fIterator.next(fFramePosition), true, true); return; } else leave(ILinkedListener.UPDATE_CARET); } void previous() { if (fIterator.hasPrevious(fFramePosition)) { switchPosition(fIterator.previous(fFramePosition), true, true); } else // dont't update caret, but rather select the current frame leave(ILinkedListener.SELECT); } private void triggerContextInfo() { ITextOperationTarget target= fCurrentTarget.getViewer().getTextOperationTarget(); if (target != null) { if (target.canDoOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION)) target.doOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); } } /** Trigger content assist on choice positions */ private void triggerContentAssist() { if (fFramePosition instanceof ProposalPosition) { ProposalPosition pp= (ProposalPosition) fFramePosition; fAssistant.setCompletions(pp.getChoices()); fAssistant.showPossibleCompletions(); } else { fAssistant.setCompletions(new ICompletionProposal[0]); fAssistant.hidePossibleCompletions(); } } private void switchPosition(LinkedPosition pos, boolean select, boolean showProposals) { Assert.isNotNull(pos); if (pos.equals(fFramePosition)) return; // mark navigation history JavaPlugin.getActivePage().getNavigationHistory().markLocation(JavaPlugin.getActivePage().getActiveEditor()); // undo if (fHasOpenCompoundChange) { ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer(); IRewriteTarget target= extension.getRewriteTarget(); target.endCompoundChange(); fHasOpenCompoundChange= false; } redraw(); IDocument oldDoc= fFramePosition == null ? null : fFramePosition.getDocument(); IDocument newDoc= pos.getDocument(); if (fCurrentTarget.fAnnotationModel != null) fCurrentTarget.fAnnotationModel.switchToPosition(fEnvironment, pos); switchViewer(oldDoc, newDoc); fFramePosition= pos; if (select) select(); if (fFramePosition == fExitPosition && !fIterator.isCycling()) leave(ILinkedListener.NONE); else { redraw(); } if (showProposals) triggerContentAssist(); if (fFramePosition != fExitPosition && fDoContextInfo) triggerContextInfo(); } private void switchViewer(IDocument oldDoc, IDocument newDoc) { if (oldDoc != newDoc) { LinkedUITarget target= null; for (int i= 0; i < fTargets.length; i++) { if (fTargets[i].getViewer().getDocument() == newDoc) { target= fTargets[i]; break; } } if (target != fCurrentTarget) { disconnect(); fCurrentTarget= target; target.enter(); connect(); } } } private void select() { ITextViewer viewer= fCurrentTarget.getViewer(); if (!viewer.overlapsWithVisibleRegion(fFramePosition.offset, fFramePosition.length)) viewer.resetVisibleRegion(); viewer.revealRange(fFramePosition.offset, fFramePosition.length); viewer.setSelectedRange(fFramePosition.offset, fFramePosition.length); } private void redraw() { if (fCurrentTarget.fAnnotationModel != null) fCurrentTarget.fAnnotationModel.switchToPosition(fEnvironment, fFramePosition); } private void connect() { Assert.isNotNull(fCurrentTarget); ITextViewer viewer= fCurrentTarget.getViewer(); Assert.isNotNull(viewer); fCurrentTarget.fWidget= viewer.getTextWidget(); if (fCurrentTarget.fWidget == null) leave(ILinkedListener.EXIT_ALL); if (fCurrentTarget.fKeyListener == null) { fCurrentTarget.fKeyListener= new LinkedUIKeyListener(); ((ITextViewerExtension) viewer).prependVerifyKeyListener(fCurrentTarget.fKeyListener); } else fCurrentTarget.fKeyListener.setEnabled(true); ((IPostSelectionProvider) viewer).addPostSelectionChangedListener(fSelectionListener); if (viewer instanceof ISourceViewer) { ISourceViewer sv= (ISourceViewer) viewer; IAnnotationModel model= sv.getAnnotationModel(); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ext= (IAnnotationModelExtension) model; IAnnotationModel ourModel= ext.getAnnotationModel(getUniqueKey()); if (ourModel == null) { LinkedPositionAnnotations lpa= new LinkedPositionAnnotations(); lpa.setTargets(fIterator.getPositions()); lpa.setExitTarget(fExitPosition); ext.addAnnotationModel(getUniqueKey(), lpa); fCurrentTarget.fAnnotationModel= lpa; } } } fCurrentTarget.fWidget.showSelection(); fCurrentTarget.fWidget.addVerifyListener(fCaretListener); fCurrentTarget.fWidget.addModifyListener(fCaretListener); fCurrentTarget.fShell= fCurrentTarget.fWidget.getShell(); if (fCurrentTarget.fShell == null) leave(ILinkedListener.EXIT_ALL); fCurrentTarget.fShell.addShellListener(fCloser); fAssistant.install(viewer); } private String getUniqueKey() { return "linked.annotationmodelkey."+toString(); //$NON-NLS-1$ } private void disconnect() { Assert.isNotNull(fCurrentTarget); ITextViewer viewer= fCurrentTarget.getViewer(); Assert.isNotNull(viewer); fAssistant.uninstall(); StyledText text= fCurrentTarget.fWidget; fCurrentTarget.fWidget= null; Shell shell= fCurrentTarget.fShell; fCurrentTarget.fShell= null; if (shell != null && !shell.isDisposed()) shell.removeShellListener(fCloser); if (text != null && !text.isDisposed()) { text.removeModifyListener(fCaretListener); text.removeVerifyListener(fCaretListener); } // don't remove the verify key listener to let it keep its position // in the listener queue fCurrentTarget.fKeyListener.setEnabled(false); fCurrentTarget.fAnnotationModel.removeAllAnnotations(); if (viewer instanceof ISourceViewer) { ISourceViewer sv= (ISourceViewer) viewer; IAnnotationModel model= sv.getAnnotationModel(); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ext= (IAnnotationModelExtension) model; ext.removeAnnotationModel(getUniqueKey()); } } ((IPostSelectionProvider) viewer).removePostSelectionChangedListener(fSelectionListener); redraw(); } void leave(int flags) { if (!fIsActive) return; fIsActive= false; ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer(); IRewriteTarget target= extension.getRewriteTarget(); if (fHasOpenCompoundChange) { target.endCompoundChange(); fHasOpenCompoundChange= false; } // // debug trace // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "leaving linked mode", null)); disconnect(); redraw(); for (int i= 0; i < fTargets.length; i++) { if (fCurrentTarget.fKeyListener != null) { ((ITextViewerExtension) fTargets[i].getViewer()).removeVerifyKeyListener(fCurrentTarget.fKeyListener); fCurrentTarget.fKeyListener= null; } } for (int i= 0; i < fTargets.length; i++) { if (fTargets[i].fAnnotationModel != null) { fTargets[i].fAnnotationModel.removeAllAnnotations(); fTargets[i].fAnnotationModel= null; } ITextViewer vi= fTargets[i].getViewer(); if (vi instanceof ISourceViewer) { ISourceViewer sv= (ISourceViewer) vi; IAnnotationModel model= sv.getAnnotationModel(); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ext= (IAnnotationModelExtension) model; ext.removeAnnotationModel(getUniqueKey()); } } } if (fExitPosition != null) fExitPosition.getDocument().removePosition(fExitPosition); if ((flags & ILinkedListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition && !fExitPosition.isDeleted()) switchPosition(fExitPosition, true, false); for (int i= 0; i < fTargets.length; i++) { IDocument doc= fTargets[i].getViewer().getDocument(); if (doc != null) { doc.removePositionUpdater(fPositionUpdater); boolean uninstallCat= false; String[] cats= doc.getPositionCategories(); for (int j= 0; j < cats.length; j++) { if (getCategory().equals(cats[j])) { uninstallCat= true; break; } } if (uninstallCat) try { doc.removePositionCategory(getCategory()); } catch (BadPositionCategoryException e) { // ignore } } } fEnvironment.exit(flags); } /** * Returns the currently selected region or <code>null</code>. * * @return the currently selected region or <code>null</code> */ public IRegion getSelectedRegion() { if (fFramePosition == null) if (fExitPosition != null) return new Region(fExitPosition.getOffset(), fExitPosition.getLength()); else return null; else return new Region(fFramePosition.getOffset(), fFramePosition.getLength()); } private void rememberSelection(VerifyEvent event) { // don't update other editor's carets if (event.getSource() != fCurrentTarget.fWidget) return; Point selection= fCurrentTarget.getViewer().getSelectedRange(); fCaretPosition.offset= selection.x + selection.y; fCaretPosition.length= 0; fCaretPosition.isDeleted= false; try { IDocument document= fCurrentTarget.getViewer().getDocument(); boolean installCat= true; String[] cats= document.getPositionCategories(); for (int i= 0; i < cats.length; i++) { if (getCategory().equals(cats[i])) installCat= false; } if (installCat) { document.addPositionCategory(getCategory()); document.addPositionUpdater(fPositionUpdater); } if (document.getPositions(getCategory()).length != 0) document.removePosition(getCategory(), fCaretPosition); document.addPosition(getCategory(), fCaretPosition); } catch (BadLocationException e) { // will not happen Assert.isTrue(false); } catch (BadPositionCategoryException e) { // will not happen Assert.isTrue(false); } } private void updateSelection(ModifyEvent event) { // don't set the caret if we've left already (we're still called as the listener // has just been removed) or the event does not happen on our current viewer if (!fIsActive || event.getSource() != fCurrentTarget.fWidget) return; if (!fCaretPosition.isDeleted()) fCurrentTarget.getViewer().setSelectedRange(fCaretPosition.getOffset(), 0); fCaretPosition.isDeleted= true; } private String getCategory() { return toString(); } /** * Sets the context info property. If set to <code>true</code>, context * info will be invoked on the current target's viewer whenever a position * is switched. * * @param doContextInfo The doContextInfo to set. */ public void setDoContextInfo(boolean doContextInfo) { fDoContextInfo= doContextInfo; } }
52,361
Bug 52361 [templates] linked mode not exited / annotations not redrawn when inserting anonymous completion
M7 0. Auto-closed parenthesis on 1. Insert this code: import java.lang.Runnable; void m() { method(<caret> } -> closing parenthesis gets inserted -> linked mode entered 2. type "new Runnable(" -> nested linked mode is entered for second parenthesis, also autoclosed 3. use code completion to complete the anonymous type -> you end up with this code: void m() { method(new Runnable() { public void run() { } }) } -> Linked mode is still drawn 4. Press <Tab> or <Enter> -> linked mode is not exited -> annotations keep being drawn The only way to get away with the annotations is to open a new parenthesis somewhere outside the initial code.
verified fixed
7413ec3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T14:37:32Z
2004-02-18T16:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionAnnotations.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.link; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationModel; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * @since 3.0 */ final class LinkedPositionAnnotations extends AnnotationModel { /* annotation types */ private static final String TARGET_ANNOTATION_TYPE= "org.eclipse.jdt.ui.link.target"; //$NON-NLS-1$ private static final String SLAVE_ANNOTATION_TYPE= "org.eclipse.jdt.ui.link.slave"; //$NON-NLS-1$ private static final String FOCUS_ANNOTATION_TYPE= "org.eclipse.jdt.ui.link.master"; //$NON-NLS-1$ private static final String EXIT_ANNOTATION_TYPE= "org.eclipse.jdt.ui.link.exit"; //$NON-NLS-1$ /* configuration */ private final static boolean markTargets= true; private final static boolean markSlaves= true; private final static boolean markFocus= true; private final static boolean markExitTarget= true; private Annotation fFocusAnnotation= null; private Annotation fExitAnnotation= null; private final Map fGroupAnnotations= new HashMap(); private final Map fTargetAnnotations= new HashMap(); private Position[] fTargets= new Position[0]; private LinkedPosition fExitPosition= null; /** * Sets the position that should be highlighted as the focus position, i.e. * as the position whose changes are propagated to all its linked positions * by the linked environment. * * @param position the new focus position, or <code>null</code> if no focus is set. */ private void setFocusPosition(Position position) throws BadLocationException { if (markFocus && getPosition(fFocusAnnotation) != position) { removeAnnotation(fFocusAnnotation, false); if (position != null) { fFocusAnnotation= new Annotation(FOCUS_ANNOTATION_TYPE, false, ""); //$NON-NLS-1$ addAnnotation(fFocusAnnotation, position, false); } else fFocusAnnotation= null; } } /** * Sets the position that should be highlighted as the exit position, i.e. * as the position whose changes are propagated to all its linked positions * by the linked environment. * * @param position the new exit position, or <code>null</code> if no focus is set. */ private void setExitPosition(Position position) throws BadLocationException { if (markExitTarget && getPosition(fExitAnnotation) != position) { removeAnnotation(fExitAnnotation, false); if (position != null) { fExitAnnotation= new Annotation(EXIT_ANNOTATION_TYPE, false, ""); //$NON-NLS-1$ addAnnotation(fExitAnnotation, position, false); } else fExitAnnotation= null; } } /** * Sets the positions that should be highlighted as the slave positions, i.e. * as the positions that are linked to the focus position. * * @param positions the new slave positions, or <code>null</code> if no slave positions are to be set */ private void setGroupPositions(List positions) throws BadLocationException { if (!markSlaves) return; // remove all positions which are already there // algo: toRemove contains all mappings at first, but all that are in // positions get removed -> toRemove contains the difference set of previsous - new // toAdd are the new positions, which don't exist in previous = new - previous List toRemove= new ArrayList(fGroupAnnotations.values()); Map toAdd= new HashMap(); if (positions != null) { for (Iterator iter= positions.iterator(); iter.hasNext();) { Position p= (Position) iter.next(); if (fGroupAnnotations.containsKey(p)) { toRemove.remove(fGroupAnnotations.get(p)); } else { Annotation a= new Annotation(SLAVE_ANNOTATION_TYPE, false, ""); //$NON-NLS-1$ toAdd.put(a, p); fGroupAnnotations.put(p, a); } } } fGroupAnnotations.values().removeAll(toRemove); replaceAnnotations((Annotation[]) toRemove.toArray(new Annotation[0]), toAdd, false); } /** * Sets the positions that should be highlighted as the target positions, i.e. * as the positions that can be jumped to in a linked set up. * * @param positions the new target positions, or <code>null</code> if no target positions are to be set */ private void setTargetPositions(List positions) throws BadLocationException { if (!markTargets) return; // remove all positions which are already there // algo: toRemove contains all mappings at first, but all that are in // positions get removed -> toRemove contains the difference set of previsous - new // toAdd are the new positions, which don't exist in previous = new - previous List toRemove= new ArrayList(fTargetAnnotations.values()); Map toAdd= new HashMap(); if (positions != null) { for (Iterator iter= positions.iterator(); iter.hasNext();) { Position p= (Position) iter.next(); if (fTargetAnnotations.containsKey(p)) { toRemove.remove(fTargetAnnotations.get(p)); } else { Annotation a= new Annotation(TARGET_ANNOTATION_TYPE, false, ""); //$NON-NLS-1$ toAdd.put(a, p); fTargetAnnotations.put(p, a); } } } fTargetAnnotations.values().removeAll(toRemove); replaceAnnotations((Annotation[]) toRemove.toArray(new Annotation[0]), toAdd, false); } /** * Switches the focus position to <code>position</code> given the * <code>LinkedEnvironment env</code>. The slave positions for <code>position</code> * is extracted from the environment and set accordingly, the target positions * are updated as well. * * @param env * @param position */ public void switchToPosition(LinkedEnvironment env, LinkedPosition position) { if (fDocument == null || (position != null && getPosition(fFocusAnnotation) == position) || (position == null && fFocusAnnotation == null)) return; LinkedPositionGroup linkedGroup= null; if (position != null) linkedGroup= env.getGroupForPosition(position); List targets= new ArrayList(); targets.addAll(Arrays.asList(fTargets)); List group; if (linkedGroup != null) group= new ArrayList(Arrays.asList(linkedGroup.getPositions())); else group= new ArrayList(); if (position == null || !fDocument.equals(position.getDocument())) // position is not valid if not in this document position= null; LinkedPosition exit= fExitPosition; if (exit == null || !fDocument.equals(exit.getDocument())) // position is not valid if not in this document exit= null; if (exit != null) { group.remove(exit); targets.remove(exit); } group.removeAll(targets); targets.remove(position); group.remove(position); // if (position == null) // System.out.println("n"); // if (group.removeAll(targets)) // System.out.println("g"); // if (targets.remove(position)) // System.out.println("t"); // if (group.remove(position)) // System.out.println("p"); prune(targets); prune(group); try { setFocusPosition(position); setExitPosition(exit); setGroupPositions(group); setTargetPositions(targets); } catch (BadLocationException e) { // log and ignore JavaPlugin.log(e); } fireModelChanged(); } /** * Prune <code>list</code> of all <code>LinkedPosition</code>s that * do not belong to this model's <code>IDocument</code>. * * @param list the list of positions to prune */ private void prune(List list) { for (Iterator iter= list.iterator(); iter.hasNext();) { LinkedPosition pos= (LinkedPosition) iter.next(); if (!pos.getDocument().equals(fDocument)) iter.remove(); } } /** * Sets the target positions * @param positions */ public void setTargets(Position[] positions) { fTargets= positions; } /** * Sets the exit position. * * @param position the new exit position, or <code>null</code> if no exit position should be set */ public void setExitTarget(LinkedPosition position) { fExitPosition = position; } /* * @see org.eclipse.jface.text.source.AnnotationModel#connect(org.eclipse.jface.text.IDocument) */ public void connect(IDocument document) { fDocument= document; } /* * @see org.eclipse.jface.text.source.AnnotationModel#disconnect(org.eclipse.jface.text.IDocument) */ public void disconnect(IDocument document) { fDocument= null; } /* * @see org.eclipse.jface.text.source.AnnotationModel#addPosition(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.Position) */ protected void addPosition(IDocument document, Position position) { // don't to anything as our positions are managed by custom // position updaters } /* * @see org.eclipse.jface.text.source.AnnotationModel#removePosition(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.Position) */ protected void removePosition(IDocument document, Position pos) { // don't to anything as our positions are managed by custom // position updaters } /* * @see org.eclipse.jface.text.source.AnnotationModel#fireModelChanged() */ public void fireModelChanged() { super.fireModelChanged(); } }
52,361
Bug 52361 [templates] linked mode not exited / annotations not redrawn when inserting anonymous completion
M7 0. Auto-closed parenthesis on 1. Insert this code: import java.lang.Runnable; void m() { method(<caret> } -> closing parenthesis gets inserted -> linked mode entered 2. type "new Runnable(" -> nested linked mode is entered for second parenthesis, also autoclosed 3. use code completion to complete the anonymous type -> you end up with this code: void m() { method(new Runnable() { public void run() { } }) } -> Linked mode is still drawn 4. Press <Tab> or <Enter> -> linked mode is not exited -> annotations keep being drawn The only way to get away with the annotations is to open a new parenthesis somewhere outside the initial code.
verified fixed
7413ec3
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T14:37:32Z
2004-02-18T16:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedUIControl.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.link; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.ShellListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.IRewriteTarget; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelExtension; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.link.contentassist.ContentAssistant2; /** * The UI for linked mode. Detects events that influence behaviour of the * linked position UI and acts upon them. * * @since 3.0 */ public class LinkedUIControl { /* cycle constants */ /** * Constant indicating that this UI should never cycle from the last * position to the first and vice versa. */ public static final int CYCLE_NEVER= 0; /** * Constant indicating that this UI should always cycle from the last * position to the first and vice versa. */ public static final int CYCLE_ALWAYS= 1; /** * Constant indicating that this UI should cycle from the last position to * the first and vice versa if its environment is not nested. */ public static final int CYCLE_WHEN_NO_PARENT= 2; /** * Listens on a styled text for events before (Verify) and after (Modify) * modifications. Used to update the caret after linked changes. */ private final class CaretListener implements ModifyListener, VerifyListener { /* * @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent) */ public void modifyText(ModifyEvent e) { updateSelection(e); } /* * @see org.eclipse.swt.events.VerifyListener#verifyText(org.eclipse.swt.events.VerifyEvent) */ public void verifyText(VerifyEvent e) { rememberSelection(e); } } /** * A link target consists of a viewer and gets notified if the linked UI on * it is being shown. * * @since 3.0 */ public static abstract class LinkedUITarget { /** * Returns the viewer represented by this target, never <code>null</code>. * * @return the viewer associated with this target. */ abstract ITextViewer getViewer(); /** * Called by the linked UI when this target is being shown. An * implementation could for example ensure that the corresponding * editor is showing. */ abstract void enter(); /** * The viewer's text widget is initialized when the UI first connects * to the viewer and never changed thereafter. This is to keep the * reference of the widget that we have registered our listeners with, * as the viewer, when it gets disposed, does not remember it, resulting * in a situation where we cannot uninstall the listeners and a memory leak. */ StyledText fWidget; /** The cached shell - same reason as fWidget. */ Shell fShell; /** The registered listener, or <code>null</code>. */ LinkedUIKeyListener fKeyListener; /** The cached custom annotation model. */ LinkedPositionAnnotations fAnnotationModel; } private static final class EmptyTarget extends LinkedUITarget { private ITextViewer fTextViewer; /** * @param viewer the viewer */ public EmptyTarget(ITextViewer viewer) { Assert.isNotNull(viewer); fTextViewer= viewer; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#getViewer() */ public ITextViewer getViewer() { return fTextViewer; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#enter() */ public void enter() { } } /** * An <code>ILinkedUITarget</code> with an associated editor, which is * brought to the top when a linked position in its viewer is jumped to. * * @since 3.0 */ public static class EditorTarget extends LinkedUITarget { /** The text viewer. */ protected final ITextViewer fTextViewer; /** The editor displaying the viewer. */ protected final ITextEditor fTextEditor; /** * Creates a new instance. * * @param viewer the viewer * @param editor the editor displaying <code>viewer</code>, or <code>null</code> */ public EditorTarget(ITextViewer viewer, ITextEditor editor) { Assert.isNotNull(viewer); fTextViewer= viewer; fTextEditor= editor; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#getViewer() */ public ITextViewer getViewer() { return fTextViewer; } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.ILinkedUITarget#enter() */ public void enter() { if (fTextEditor != null) return; IWorkbenchPage page= fTextEditor.getEditorSite().getPage(); if (page != null) { page.bringToTop(fTextEditor); } fTextEditor.setFocus(); } } /** * Listens for state changes in the model. */ private final class ExitListener implements ILinkedListener { /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void left(LinkedEnvironment environment, int flags) { leave(ILinkedListener.EXIT_ALL | flags); } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void suspend(LinkedEnvironment environment) { disconnect(); redraw(); } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void resume(LinkedEnvironment environment, int flags) { if ((flags & ILinkedListener.EXIT_ALL) != 0) { leave(flags); } else { connect(); if ((flags & ILinkedListener.SELECT) != 0) select(); redraw(); } } } /** * Exit flags returned if a custom exit policy wants to exit linked mode. */ public static class ExitFlags { /** The flags to return in the <code>leave</code> method. */ public int flags; /** The doit flag of the checked <code>VerifyKeyEvent</code>. */ public boolean doit; /** * Creates a new instance. * * @param flags the exit flags * @param doit the doit flag for the verify event */ public ExitFlags(int flags, boolean doit) { this.flags= flags; this.doit= doit; } } /** * An exit policy can be registered by a caller to get custom exit * behaviour. */ public interface IExitPolicy { /** * Checks whether the linked mode should be left after receiving the * given <code>VerifyEvent</code> and selection. Note that the event * carries widget coordinates as opposed to <code>offset</code> and * <code>length</code> which are document coordinates. * * @param environment the linked environment * @param event the verify event * @param offset the offset of the current selection * @param length the length of the current selection * @return valid exit flags or <code>null</code> if no special action * should be taken */ ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length); } /** * A NullObject implementation of <code>IExitPolicy</code>. */ private static class NullExitPolicy implements IExitPolicy { /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedUIControl.IExitPolicy#doExit(org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length) { return null; } } /** * Listens for shell events and acts upon them. */ private class LinkedUICloser implements ShellListener { public void shellActivated(ShellEvent e) { } public void shellClosed(ShellEvent e) { leave(ILinkedListener.EXIT_ALL); } public void shellDeactivated(ShellEvent e) { // T ODO reenable after debugging // if (true) return; // from LinkedPositionUI: // 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 // Seems to be no problem // Better: // 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 || fCurrentTarget == null || (text= fCurrentTarget.fWidget) == null || text.isDisposed() || (display= text.getDisplay()) == null || display.isDisposed()) { leave(ILinkedListener.EXIT_ALL); } else { // Post in UI thread since the assistant popup will only get the focus after we lose it. display.asyncExec(new Runnable() { public void run() { if (fIsActive && (fAssistant == null || !fAssistant.hasFocus())) { leave(ILinkedListener.EXIT_ALL); } } }); } } public void shellDeiconified(ShellEvent e) { } public void shellIconified(ShellEvent e) { leave(ILinkedListener.EXIT_ALL); } } /** * Listens for key events, checks the exit policy for custom exit * strategies but defaults to handling Tab, Enter, and Escape. */ private class LinkedUIKeyListener implements VerifyKeyListener { private boolean fIsEnabled= true; public void verifyKey(VerifyEvent event) { if (!event.doit || !fIsEnabled) return; Point selection= fCurrentTarget.getViewer().getSelectedRange(); int offset= selection.x; int length= selection.y; // if the custom exit policy returns anything, use that ExitFlags exitFlags= fExitPolicy.doExit(fEnvironment, event, offset, length); if (exitFlags != null) { leave(exitFlags.flags); event.doit= exitFlags.doit; return; } // standard behaviour: // (Shift+)Tab: jumps from position to position, depending on cycle mode // Enter: accepts all entries and leaves all (possibly stacked) environments, the last sets the caret // Esc: accepts all entries and leaves all (possibly stacked) environments, the caret stays // ? what do we do to leave one level of a cycling environment that is stacked? // -> This is only the case if the level was set up with forced cycling (CYCLE_ALWAYS), in which case // the caller is sure that one does not need by-level exiting. switch (event.character) { // [SHIFT-]TAB = hop between edit boxes case 0x09: if (!(fExitPosition != null && fExitPosition.includes(offset)) && !fEnvironment.anyPositionContains(offset)) { // outside any edit box -> leave (all? TODO should only leave the affected, level and forward to the next upper) leave(ILinkedListener.EXIT_ALL); break; } else { if (event.stateMask == SWT.SHIFT) previous(); else next(); } event.doit= false; break; // ENTER case 0x0A: // Ctrl+Enter on WinXP case 0x0D: if (fAssistant != null && fAssistant.wasProposalChosen()) { // don't exit as it was really just the proposal that was chosen next(); event.doit= false; break; } else if ((fExitPosition != null && fExitPosition.includes(offset)) || !fEnvironment.anyPositionContains(offset)) { // outside any edit box or on exit position -> leave (all? TODO should only leave the affected, level and forward to the next upper) leave(ILinkedListener.EXIT_ALL); break; } else { // normal case: exit entire stack and put caret to final position leave(ILinkedListener.EXIT_ALL | ILinkedListener.UPDATE_CARET); event.doit= false; break; } // ESC case 0x1B: // exit entire stack and leave caret leave(ILinkedListener.EXIT_ALL); event.doit= false; break; default: if (event.character != 0) { if (!controlUndoBehavior(offset, length)) { leave(ILinkedListener.EXIT_ALL); break; } } } } private boolean controlUndoBehavior(int offset, int length) { LinkedPosition position= fEnvironment.findPosition(new LinkedPosition(fCurrentTarget.getViewer().getDocument(), offset, length, LinkedPositionGroup.NO_STOP)); if (position != null) { // if the last position is not the same and there is an open change: close it. if (!position.equals(fPreviousPosition)) endCompoundChange(); beginCompoundChange(); } fPreviousPosition= position; return fPreviousPosition != null; } /** * @param enabled the new enabled state */ public void setEnabled(boolean enabled) { fIsEnabled= enabled; } } /** * Installed as post selection listener on the watched viewer. Updates the * linked position after cursor movement, even to positions not in the * iteration list. */ private class MySelectionListener implements ISelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { ISelection selection= event.getSelection(); if (selection instanceof ITextSelection) { ITextSelection textsel= (ITextSelection) selection; if (event.getSelectionProvider() instanceof ITextViewer) { IDocument doc= ((ITextViewer) event.getSelectionProvider()).getDocument(); if (doc != null) { int offset= textsel.getOffset(); int length= textsel.getLength(); if (offset >= 0 && length >= 0) { LinkedPosition find= new LinkedPosition(doc, offset, length, LinkedPositionGroup.NO_STOP); LinkedPosition pos= fEnvironment.findPosition(find); if (pos == null && fExitPosition != null && fExitPosition.includes(find)) pos= fExitPosition; if (pos != null) switchPosition(pos, false, false); } } } } } } /** The current viewer. */ private LinkedUITarget fCurrentTarget; /** The manager of the linked positions we provide a UI for. */ private LinkedEnvironment fEnvironment; /** The set of viewers we manage. */ private LinkedUITarget[] fTargets; /** The iterator over the tab stop positions. */ private TabStopIterator fIterator; /* Our team of event listeners */ /** The shell listener. */ private LinkedUICloser fCloser= new LinkedUICloser(); /** The linked listener. */ private ILinkedListener fLinkedListener= new ExitListener(); /** The selection listener. */ private MySelectionListener fSelectionListener= new MySelectionListener(); /** The styled text listener. */ private CaretListener fCaretListener= new CaretListener(); /** The last caret position, used by fCaretListener. */ private final Position fCaretPosition= new Position(0, 0); /** The exit policy to control custom exit behaviour */ private IExitPolicy fExitPolicy= new NullExitPolicy(); /** The current frame position shown in the UI, or <code>null</code>. */ private LinkedPosition fFramePosition; /** The last visisted position, used for undo / redo. */ private LinkedPosition fPreviousPosition; /** The content assistant used to show proposals. */ private ContentAssistant2 fAssistant; /** The exit position. */ private LinkedPosition fExitPosition; /** State indicator to prevent multiple invocation of leave. */ private boolean fIsActive= false; private IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(getCategory()); private boolean fDoContextInfo= false; private boolean fHasOpenCompoundChange= false; /** * Creates a new UI on the given model (environment) and the set of * viewers. The environment must provide a tab stop sequence with a * non-empty list of tab stops. * * @param environment the linked position model * @param targets the non-empty list of targets upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, LinkedUITarget[] targets) { constructor(environment, targets); } /** * Conveniance ctor for just one viewer. * * @param environment the linked position model * @param viewer the viewer upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, ITextViewer viewer) { constructor(environment, new LinkedUITarget[]{new EmptyTarget(viewer)}); } /** * Conveniance ctor for multiple viewers. * * @param environment the linked position model * @param viewers the non-empty list of viewers upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, ITextViewer[] viewers) { LinkedUITarget[] array= new LinkedUITarget[viewers.length]; for (int i= 0; i < array.length; i++) { array[i]= new EmptyTarget(viewers[i]); } constructor(environment, array); } /** * Conveniance ctor for one target. * * @param environment the linked position model * @param target the target upon which the linked ui * should act */ public LinkedUIControl(LinkedEnvironment environment, LinkedUITarget target) { constructor(environment, new LinkedUITarget[]{target}); } /** * This does the actual constructor work. * * @param environment the linked position model * @param targets the non-empty array of targets upon which the linked ui * should act */ private void constructor(LinkedEnvironment environment, LinkedUITarget[] targets) { Assert.isNotNull(environment); Assert.isNotNull(targets); Assert.isTrue(targets.length > 0); Assert.isTrue(environment.getTabStopSequence().size() > 0); fEnvironment= environment; fTargets= targets; fCurrentTarget= targets[0]; fIterator= new TabStopIterator(fEnvironment.getTabStopSequence()); fIterator.setCycling(!fEnvironment.isNested()); fEnvironment.addLinkedListener(fLinkedListener); fAssistant= new ContentAssistant2(); fAssistant.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING); fCaretPosition.delete(); } /** * Starts this UI on the first position. */ public void enter() { fIsActive= true; connect(); next(); } /** * Sets an <code>IExitPolicy</code> to customize the exit behaviour of * this linked UI. * * @param policy the exit policy to use. */ public void setExitPolicy(IExitPolicy policy) { fExitPolicy= policy; } /** * Sets the exit position to move the caret to when linked mode is exited. * * @param target the target where the exit position is located * @param offset the offset of the exit position * @param length the length of the exit position (in case there should be a * selection) * @param sequence set to the tab stop position of the exit position, or * <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop. * @throws BadLocationException if the position is not valid in the * viewer's document */ public void setExitPosition(LinkedUITarget target, int offset, int length, int sequence) throws BadLocationException { // remove any existing exit position if (fExitPosition != null) { fExitPosition.getDocument().removePosition(fExitPosition); fIterator.removePosition(fExitPosition); fExitPosition= null; } IDocument doc= target.getViewer().getDocument(); if (doc == null) return; fExitPosition= new LinkedPosition(doc, offset, length, sequence); doc.addPosition(fExitPosition); // gets removed in leave() if (sequence != LinkedPositionGroup.NO_STOP) fIterator.addPosition(fExitPosition); } /** * Sets the exit position to move the caret to when linked mode is exited. * * @param viewer the viewer where the exit position is located * @param offset the offset of the exit position * @param length the length of the exit position (in case there should be a * selection) * @param sequence set to the tab stop position of the exit position, or * <code>LinkedPositionGroup.NO_STOP</code> if there should be no tab stop. * @throws BadLocationException if the position is not valid in the * viewer's document */ public void setExitPosition(ITextViewer viewer, int offset, int length, int sequence) throws BadLocationException { setExitPosition(new EditorTarget(viewer, null), offset, length, sequence); } /** * Sets the cycling mode to either of <code>CYCLING_ALWAYS</code>, * <code>CYCLING_NEVER</code>, or <code>CYCLING_WHEN_NO_PARENT</code>, * which is the default. * * @param mode the new cycling mode. */ public void setCyclingMode(int mode) { if (mode == CYCLE_ALWAYS || mode == CYCLE_WHEN_NO_PARENT && !fEnvironment.isNested()) fIterator.setCycling(true); else fIterator.setCycling(false); } void next() { if (fIterator.hasNext(fFramePosition)) { switchPosition(fIterator.next(fFramePosition), true, true); return; } else leave(ILinkedListener.UPDATE_CARET); } void previous() { if (fIterator.hasPrevious(fFramePosition)) { switchPosition(fIterator.previous(fFramePosition), true, true); } else // dont't update caret, but rather select the current frame leave(ILinkedListener.SELECT); } private void triggerContextInfo() { ITextOperationTarget target= fCurrentTarget.getViewer().getTextOperationTarget(); if (target != null) { if (target.canDoOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION)) target.doOperation(ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); } } /** Trigger content assist on choice positions */ private void triggerContentAssist() { if (fFramePosition instanceof ProposalPosition) { ProposalPosition pp= (ProposalPosition) fFramePosition; fAssistant.setCompletions(pp.getChoices()); fAssistant.showPossibleCompletions(); } else { fAssistant.setCompletions(new ICompletionProposal[0]); fAssistant.hidePossibleCompletions(); } } private void switchPosition(LinkedPosition pos, boolean select, boolean showProposals) { Assert.isNotNull(pos); if (pos.equals(fFramePosition)) return; markNavigationHistory(); // undo endCompoundChange(); redraw(); // redraw current position being left - usually not needed IDocument oldDoc= fFramePosition == null ? null : fFramePosition.getDocument(); IDocument newDoc= pos.getDocument(); switchViewer(oldDoc, newDoc, pos); fFramePosition= pos; if (select) select(); if (fFramePosition == fExitPosition && !fIterator.isCycling()) leave(ILinkedListener.NONE); else { redraw(); // redraw new position ensureAnnotationModelInstalled(); } if (showProposals) triggerContentAssist(); if (fFramePosition != fExitPosition && fDoContextInfo) triggerContextInfo(); } /** * */ private void markNavigationHistory() { // mark navigation history IWorkbenchWindow win= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (win != null) { IWorkbenchPage page= win.getActivePage(); if (page != null) { IEditorPart part= page.getActiveEditor(); page.getNavigationHistory().markLocation(part); } } } private void ensureAnnotationModelInstalled() { LinkedPositionAnnotations lpa= fCurrentTarget.fAnnotationModel; if (lpa != null) { ITextViewer viewer= fCurrentTarget.getViewer(); if (viewer instanceof ISourceViewer) { ISourceViewer sv= (ISourceViewer) viewer; IAnnotationModel model= sv.getAnnotationModel(); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ext= (IAnnotationModelExtension) model; IAnnotationModel ourModel= ext.getAnnotationModel(getUniqueKey()); if (ourModel == null) { ext.addAnnotationModel(getUniqueKey(), lpa); } } } } } private void switchViewer(IDocument oldDoc, IDocument newDoc, LinkedPosition pos) { if (oldDoc != newDoc) { // redraw current document with new position before switching viewer if (fCurrentTarget.fAnnotationModel != null) fCurrentTarget.fAnnotationModel.switchToPosition(fEnvironment, pos); LinkedUITarget target= null; for (int i= 0; i < fTargets.length; i++) { if (fTargets[i].getViewer().getDocument() == newDoc) { target= fTargets[i]; break; } } if (target != fCurrentTarget) { disconnect(); fCurrentTarget= target; target.enter(); connect(); } } } private void select() { ITextViewer viewer= fCurrentTarget.getViewer(); if (!viewer.overlapsWithVisibleRegion(fFramePosition.offset, fFramePosition.length)) viewer.resetVisibleRegion(); viewer.revealRange(fFramePosition.offset, fFramePosition.length); viewer.setSelectedRange(fFramePosition.offset, fFramePosition.length); } private void redraw() { if (fCurrentTarget.fAnnotationModel != null) fCurrentTarget.fAnnotationModel.switchToPosition(fEnvironment, fFramePosition); } private void connect() { Assert.isNotNull(fCurrentTarget); ITextViewer viewer= fCurrentTarget.getViewer(); Assert.isNotNull(viewer); fCurrentTarget.fWidget= viewer.getTextWidget(); if (fCurrentTarget.fWidget == null) leave(ILinkedListener.EXIT_ALL); if (fCurrentTarget.fKeyListener == null) { fCurrentTarget.fKeyListener= new LinkedUIKeyListener(); ((ITextViewerExtension) viewer).prependVerifyKeyListener(fCurrentTarget.fKeyListener); } else fCurrentTarget.fKeyListener.setEnabled(true); ((IPostSelectionProvider) viewer).addPostSelectionChangedListener(fSelectionListener); createAnnotationModel(); fCurrentTarget.fWidget.showSelection(); fCurrentTarget.fWidget.addVerifyListener(fCaretListener); fCurrentTarget.fWidget.addModifyListener(fCaretListener); fCurrentTarget.fShell= fCurrentTarget.fWidget.getShell(); if (fCurrentTarget.fShell == null) leave(ILinkedListener.EXIT_ALL); fCurrentTarget.fShell.addShellListener(fCloser); fAssistant.install(viewer); } private void createAnnotationModel() { if (fCurrentTarget.fAnnotationModel == null) { LinkedPositionAnnotations lpa= new LinkedPositionAnnotations(); lpa.setTargets(fIterator.getPositions()); lpa.setExitTarget(fExitPosition); lpa.connect(fCurrentTarget.getViewer().getDocument()); fCurrentTarget.fAnnotationModel= lpa; } } private String getUniqueKey() { return "linked.annotationmodelkey."+toString(); //$NON-NLS-1$ } private void disconnect() { Assert.isNotNull(fCurrentTarget); ITextViewer viewer= fCurrentTarget.getViewer(); Assert.isNotNull(viewer); fAssistant.uninstall(); StyledText text= fCurrentTarget.fWidget; fCurrentTarget.fWidget= null; Shell shell= fCurrentTarget.fShell; fCurrentTarget.fShell= null; if (shell != null && !shell.isDisposed()) shell.removeShellListener(fCloser); if (text != null && !text.isDisposed()) { text.removeModifyListener(fCaretListener); text.removeVerifyListener(fCaretListener); } // don't remove the verify key listener to let it keep its position // in the listener queue fCurrentTarget.fKeyListener.setEnabled(false); ((IPostSelectionProvider) viewer).removePostSelectionChangedListener(fSelectionListener); redraw(); } void leave(int flags) { if (!fIsActive) return; fIsActive= false; endCompoundChange(); // // debug trace // JavaPlugin.log(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IStatus.OK, "leaving linked mode", null)); disconnect(); redraw(); for (int i= 0; i < fTargets.length; i++) { if (fCurrentTarget.fKeyListener != null) { ((ITextViewerExtension) fTargets[i].getViewer()).removeVerifyKeyListener(fCurrentTarget.fKeyListener); fCurrentTarget.fKeyListener= null; } } for (int i= 0; i < fTargets.length; i++) { if (fTargets[i].fAnnotationModel != null) { fTargets[i].fAnnotationModel.removeAllAnnotations(); fTargets[i].fAnnotationModel= null; } ITextViewer vi= fTargets[i].getViewer(); if (vi instanceof ISourceViewer) { ISourceViewer sv= (ISourceViewer) vi; IAnnotationModel model= sv.getAnnotationModel(); if (model instanceof IAnnotationModelExtension) { IAnnotationModelExtension ext= (IAnnotationModelExtension) model; ext.removeAnnotationModel(getUniqueKey()); } } } if (fExitPosition != null) fExitPosition.getDocument().removePosition(fExitPosition); if ((flags & ILinkedListener.UPDATE_CARET) != 0 && fExitPosition != null && fFramePosition != fExitPosition && !fExitPosition.isDeleted()) switchPosition(fExitPosition, true, false); for (int i= 0; i < fTargets.length; i++) { IDocument doc= fTargets[i].getViewer().getDocument(); if (doc != null) { doc.removePositionUpdater(fPositionUpdater); boolean uninstallCat= false; String[] cats= doc.getPositionCategories(); for (int j= 0; j < cats.length; j++) { if (getCategory().equals(cats[j])) { uninstallCat= true; break; } } if (uninstallCat) try { doc.removePositionCategory(getCategory()); } catch (BadPositionCategoryException e) { // ignore } } } fEnvironment.exit(flags); } /** * */ private void endCompoundChange() { if (fHasOpenCompoundChange) { ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer(); IRewriteTarget target= extension.getRewriteTarget(); target.endCompoundChange(); fHasOpenCompoundChange= false; } } private void beginCompoundChange() { if (!fHasOpenCompoundChange) { ITextViewerExtension extension= (ITextViewerExtension) fCurrentTarget.getViewer(); IRewriteTarget target= extension.getRewriteTarget(); target.beginCompoundChange(); fHasOpenCompoundChange= true; } } /** * Returns the currently selected region or <code>null</code>. * * @return the currently selected region or <code>null</code> */ public IRegion getSelectedRegion() { if (fFramePosition == null) if (fExitPosition != null) return new Region(fExitPosition.getOffset(), fExitPosition.getLength()); else return null; else return new Region(fFramePosition.getOffset(), fFramePosition.getLength()); } private void rememberSelection(VerifyEvent event) { // don't update other editor's carets if (event.getSource() != fCurrentTarget.fWidget) return; Point selection= fCurrentTarget.getViewer().getSelectedRange(); fCaretPosition.offset= selection.x + selection.y; fCaretPosition.length= 0; fCaretPosition.isDeleted= false; try { IDocument document= fCurrentTarget.getViewer().getDocument(); boolean installCat= true; String[] cats= document.getPositionCategories(); for (int i= 0; i < cats.length; i++) { if (getCategory().equals(cats[i])) installCat= false; } if (installCat) { document.addPositionCategory(getCategory()); document.addPositionUpdater(fPositionUpdater); } if (document.getPositions(getCategory()).length != 0) document.removePosition(getCategory(), fCaretPosition); document.addPosition(getCategory(), fCaretPosition); } catch (BadLocationException e) { // will not happen Assert.isTrue(false); } catch (BadPositionCategoryException e) { // will not happen Assert.isTrue(false); } } private void updateSelection(ModifyEvent event) { // don't set the caret if we've left already (we're still called as the listener // has just been removed) or the event does not happen on our current viewer if (!fIsActive || event.getSource() != fCurrentTarget.fWidget) return; if (!fCaretPosition.isDeleted()) fCurrentTarget.getViewer().setSelectedRange(fCaretPosition.getOffset(), 0); fCaretPosition.isDeleted= true; } private String getCategory() { return toString(); } /** * Sets the context info property. If set to <code>true</code>, context * info will be invoked on the current target's viewer whenever a position * is switched. * * @param doContextInfo The doContextInfo to set. */ public void setDoContextInfo(boolean doContextInfo) { fDoContextInfo= doContextInfo; } }
52,470
Bug 52470 CallHierarchy: SourceLocation View doesn't deliver IJavaElement selection
M7 Steps: - Open Java Browsing Perspective - Open CallHierarchy - single-click on source location -> observe: JavaBrowsing Views lose their JavaElement I guess it's because there's no SelectionProviderMediator which delivers IJavaElements for selected source positions.
resolved fixed
7d6c359
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T14:53:03Z
2004-02-19T11:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/CallHierarchyUI.java
/******************************************************************************* * Copyright (c) 2000, 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: * Jesper Kamstrup Linnet ([email protected]) - initial API and implementation * (report 36180: Callers/Callees view) ******************************************************************************/ package org.eclipse.jdt.internal.ui.callhierarchy; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.OpenStrategy; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.IJavaStatusConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.OpenActionUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.corext.callhierarchy.CallHierarchy; import org.eclipse.jdt.internal.corext.callhierarchy.CallLocation; import org.eclipse.jdt.internal.corext.callhierarchy.MethodWrapper; public class CallHierarchyUI { private static final int DEFAULT_MAX_CALL_DEPTH= 10; private static final String PREF_MAX_CALL_DEPTH = "PREF_MAX_CALL_DEPTH"; //$NON-NLS-1$ private static CallHierarchyUI fgInstance; private CallHierarchyUI() { // Do nothing } public static CallHierarchyUI getDefault() { if (fgInstance == null) { fgInstance = new CallHierarchyUI(); } return fgInstance; } /** * Returns the maximum tree level allowed * @return int */ public int getMaxCallDepth() { int maxCallDepth; IPreferenceStore settings = JavaPlugin.getDefault().getPreferenceStore(); maxCallDepth = settings.getInt(PREF_MAX_CALL_DEPTH); if (maxCallDepth < 1 || maxCallDepth > 99) { maxCallDepth= DEFAULT_MAX_CALL_DEPTH; } return maxCallDepth; } public void setMaxCallDepth(int maxCallDepth) { IPreferenceStore settings = JavaPlugin.getDefault().getPreferenceStore(); settings.setValue(PREF_MAX_CALL_DEPTH, maxCallDepth); } public static void jumpToMember(IJavaElement element) { if (element != null) { try { IEditorPart methodEditor = EditorUtility.openInEditor(element, true); JavaUI.revealInEditor(methodEditor, element); } catch (JavaModelException e) { JavaPlugin.log(e); } catch (PartInitException e) { JavaPlugin.log(e); } } } public static void jumpToLocation(CallLocation callLocation) { try { IEditorPart methodEditor = EditorUtility.openInEditor(callLocation.getMember(), false); if (methodEditor instanceof ITextEditor) { ITextEditor editor = (ITextEditor) methodEditor; editor.selectAndReveal(callLocation.getStart(), (callLocation.getEnd() - callLocation.getStart())); } } catch (JavaModelException e) { JavaPlugin.log(e); } catch (PartInitException e) { JavaPlugin.log(e); } } public static void openInEditor(Object element, Shell shell, String title) { CallLocation callLocation= CallHierarchy.getCallLocation(element); if (callLocation == null) { return; } try { boolean activateOnOpen = OpenStrategy.activateOnOpen(); IEditorPart methodEditor = EditorUtility.openInEditor(callLocation.getMember(), activateOnOpen); if (methodEditor instanceof ITextEditor) { ITextEditor editor = (ITextEditor) methodEditor; editor.selectAndReveal(callLocation.getStart(), (callLocation.getEnd() - callLocation.getStart())); } } catch (JavaModelException e) { JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, CallHierarchyMessages.getString( "CallHierarchyUI.open_in_editor.error.message"), e)); //$NON-NLS-1$ ErrorDialog.openError(shell, title, CallHierarchyMessages.getString( "CallHierarchyUI.open_in_editor.error.messageProblems"), //$NON-NLS-1$ e.getStatus()); } catch (PartInitException x) { String name = callLocation.getCalledMember().getElementName(); MessageDialog.openError(shell, CallHierarchyMessages.getString( "CallHierarchyUI.open_in_editor.error.messageProblems"), //$NON-NLS-1$ CallHierarchyMessages.getFormattedString( "CallHierarchyUI.open_in_editor.error.messageArgs", //$NON-NLS-1$ new String[] { name, x.getMessage() })); } } /** * @param elem * @return */ public static IEditorPart isOpenInEditor(Object elem) { IJavaElement javaElement= null; if (elem instanceof MethodWrapper) { javaElement= ((MethodWrapper) elem).getMember(); } else if (elem instanceof CallLocation) { javaElement= ((CallLocation) elem).getCalledMember(); } if (javaElement != null) { return EditorUtility.isOpenInEditor(javaElement); } return null; } /** * Converts the input to a possible input candidates */ public static IJavaElement[] getCandidates(Object input) { if (!(input instanceof IJavaElement)) { return null; } IJavaElement elem= (IJavaElement) input; if (elem.getElementType() == IJavaElement.METHOD) { return new IJavaElement[] { elem }; } return null; } public static CallHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) { Assert.isTrue(candidates != null && candidates.length != 0); IJavaElement input= null; if (candidates.length > 1) { String title= CallHierarchyMessages.getString("CallHierarchyUI.selectionDialog.title"); //$NON-NLS-1$ String message= CallHierarchyMessages.getString("CallHierarchyUI.selectionDialog.message"); //$NON-NLS-1$ input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message); } else { input= candidates[0]; } if (input == null) return null; return openInViewPart(window, input); } private static void openEditor(Object input, boolean activate) throws PartInitException, JavaModelException { IEditorPart part= EditorUtility.openInEditor(input, activate); if (input instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) input); } private static CallHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) { IWorkbenchPage page= window.getActivePage(); try { CallHierarchyViewPart result= (CallHierarchyViewPart)page.showView(CallHierarchyViewPart.ID_CALL_HIERARCHY); result.setMethod((IMethod)input); openEditor(input, false); return result; } catch (CoreException e) { ExceptionHandler.handle(e, window.getShell(), CallHierarchyMessages.getString("CallHierarchyUI.error.open_view"), e.getMessage()); //$NON-NLS-1$ } return null; } /** * Converts an ISelection (containing MethodWrapper instances) to an ISelection * with the MethodWrapper's replaced by their corresponding IMembers. If the selection * contains elements which are not MethodWrapper instances or not already IMember instances * they are discarded. * @param selection The selection to convert. * @return An ISelection containing IMember's in place of MethodWrapper instances. */ static ISelection convertSelection(ISelection selection) { if (selection.isEmpty()) { return selection; } if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection= (IStructuredSelection) selection; List javaElements= new ArrayList(); for (Iterator iter= structuredSelection.iterator(); iter.hasNext();) { Object element= iter.next(); if (element instanceof MethodWrapper) { IMember member= ((MethodWrapper)element).getMember(); if (member != null) { javaElements.add(member); } } else if (element instanceof IMember) { javaElements.add(element); } } return new StructuredSelection(javaElements); } return StructuredSelection.EMPTY; } }
52,801
Bug 52801 "Press F2 for focus" does not work for spell-checking hovers
"Press F2 for focus" does not work for spell-checking hovers.
resolved fixed
4c0b449
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T15:22:14Z
2004-02-23T09:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.text.CollationElementIterator; import java.text.Collator; import java.text.RuleBasedCollator; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.StringTokenizer; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.Preferences; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BidiSegmentEvent; import org.eclipse.swt.custom.BidiSegmentListener; import org.eclipse.swt.custom.ST; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.MouseMoveListener; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.GroupMarker; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.IPostSelectionProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextHover; import org.eclipse.jface.text.ITextInputListener; import org.eclipse.jface.text.ITextPresentationListener; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.ITextViewerExtension4; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextPresentation; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.information.IInformationProvider; import org.eclipse.jface.text.information.IInformationProviderExtension2; import org.eclipse.jface.text.information.InformationPresenter; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.AnnotationRulerColumn; import org.eclipse.jface.text.source.CompositeRuler; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.text.source.IAnnotationModelExtension; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.LineChangeHover; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.editors.text.DefaultEncodingSupport; import org.eclipse.ui.editors.text.EditorsUI; import org.eclipse.ui.editors.text.IEncodingSupport; import org.eclipse.ui.IEditorActionBarContributor; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartService; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.EditorActionBarContributor; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.texteditor.AnnotationPreference; import org.eclipse.ui.texteditor.DefaultRangeIndicator; import org.eclipse.ui.texteditor.ExtendedTextEditor; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.IEditorStatusLine; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds; import org.eclipse.ui.texteditor.IUpdate; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.ui.texteditor.ResourceAction; import org.eclipse.ui.texteditor.SourceViewerDecorationSupport; import org.eclipse.ui.texteditor.TextEditorAction; import org.eclipse.ui.texteditor.TextNavigationAction; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.ui.views.contentoutline.IContentOutlinePage; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICodeAssist; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ILocalVariable; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.corext.dom.NodeFinder; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder; import org.eclipse.jdt.internal.ui.search.OccurrencesFinder; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaChangeHover; import org.eclipse.jdt.internal.ui.text.JavaPairMatcher; import org.eclipse.jdt.internal.ui.text.java.hover.JavaExpandHover; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager; /** * Java specific text editor. */ public abstract class JavaEditor extends ExtendedTextEditor implements IViewPartInputProvider { /** * Internal implementation class for a change listener. * @since 3.0 */ protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener { /** * Installs this selection changed listener with the given selection provider. If * the selection provider is a post selection provider, post selection changed * events are the preferred choice, otherwise normal selection changed events * are requested. * * @param selectionProvider */ public void install(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.addPostSelectionChangedListener(this); } else { selectionProvider.addSelectionChangedListener(this); } } /** * Removes this selection changed listener from the given selection provider. * * @param selectionProviderstyle */ public void uninstall(ISelectionProvider selectionProvider) { if (selectionProvider == null) return; if (selectionProvider instanceof IPostSelectionProvider) { IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider; provider.removePostSelectionChangedListener(this); } else { selectionProvider.removeSelectionChangedListener(this); } } } /** * Updates the Java outline page selection and this editor's range indicator. * * @since 3.0 */ private class EditorSelectionChangedListener extends AbstractSelectionChangedListener { /* * @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { selectionChanged(); } public void selectionChanged() { ISourceReference element= computeHighlightRangeSourceReference(); if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) synchronizeOutlinePage(element); setSelection(element, false); updateStatusLine(); } } /** * Updates the selection in the editor's widget with the selection of the outline page. */ class OutlineSelectionChangedListener extends AbstractSelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } } /* * Link mode. */ class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener, FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener { /** The session is active. */ private boolean fActive; /** The currently active style range. */ private IRegion fActiveRegion; /** The currently active style range as position. */ private Position fRememberedPosition; /** The hand cursor. */ private Cursor fCursor; /** The link color. */ private Color fColor; /** The key modifier mask. */ private int fKeyModifierMask; public void deactivate() { deactivate(false); } public void deactivate(boolean redrawAll) { if (!fActive) return; repairRepresentation(redrawAll); fActive= false; } public void install() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; updateColor(sourceViewer); sourceViewer.addTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.addDocumentListener(this); text.addKeyListener(this); text.addMouseListener(this); text.addMouseMoveListener(this); text.addFocusListener(this); text.addPaintListener(this); ((ITextViewerExtension4)sourceViewer).addTextPresentationListener(this); updateKeyModifierMask(); IPreferenceStore preferenceStore= getPreferenceStore(); preferenceStore.addPropertyChangeListener(this); } private void updateKeyModifierMask() { String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER); fKeyModifierMask= computeStateMask(modifiers); if (fKeyModifierMask == -1) { // Fallback to stored state mask fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK); } } 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; } public void uninstall() { if (fColor != null) { fColor.dispose(); fColor= null; } if (fCursor != null) { fCursor.dispose(); fCursor= null; } ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; sourceViewer.removeTextInputListener(this); IDocument document= sourceViewer.getDocument(); if (document != null) document.removeDocumentListener(this); IPreferenceStore preferenceStore= getPreferenceStore(); if (preferenceStore != null) preferenceStore.removePropertyChangeListener(this); StyledText text= sourceViewer.getTextWidget(); if (text == null || text.isDisposed()) return; text.removeKeyListener(this); text.removeMouseListener(this); text.removeMouseMoveListener(this); text.removeFocusListener(this); text.removePaintListener(this); ((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(this); } /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(JavaEditor.LINK_COLOR)) { ISourceViewer viewer= getSourceViewer(); if (viewer != null) updateColor(viewer); } else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) { updateKeyModifierMask(); } } private void updateColor(ISourceViewer viewer) { if (fColor != null) fColor.dispose(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display); } /** * Creates a color from the information stored in the given preference store. * Returns <code>null</code> 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; } private void repairRepresentation() { repairRepresentation(false); } private void repairRepresentation(boolean redrawAll) { if (fActiveRegion == null) return; int offset= fActiveRegion.getOffset(); int length= fActiveRegion.getLength(); fActiveRegion= null; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { resetCursor(viewer); // Invalidate ==> remove applied text presentation if (!redrawAll && viewer instanceof ITextViewerExtension2) ((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length); else viewer.invalidateTextPresentation(); // Remove underline if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; offset= extension.modelOffset2WidgetOffset(offset); } else { offset -= viewer.getVisibleRegion().getOffset(); } try { StyledText text= viewer.getTextWidget(); text.redrawRange(offset, length, false); } catch (IllegalArgumentException x) { JavaPlugin.log(x); } } } // will eventually be replaced by a method provided by jdt.core private IRegion selectWord(IDocument document, int anchor) { try { int offset= anchor; char c; while (offset >= 0) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; --offset; } int start= offset; offset= anchor; int length= document.getLength(); while (offset < length) { c= document.getChar(offset); if (!Character.isJavaIdentifierPart(c)) break; ++offset; } int end= offset; if (start == end) return new Region(start, 0); else return new Region(start + 1, end - start - 1); } catch (BadLocationException x) { return null; } } IRegion getCurrentTextRegion(ISourceViewer viewer) { int offset= getCurrentTextOffset(viewer); if (offset == -1) return null; IJavaElement input= SelectionConverter.getInput(JavaEditor.this); if (input == null) return null; try { IJavaElement[] elements= null; synchronized (input) { elements= ((ICodeAssist) input).codeSelect(offset, 0); } if (elements == null || elements.length == 0) return null; return selectWord(viewer.getDocument(), offset); } catch (JavaModelException e) { return null; } } private int getCurrentTextOffset(ISourceViewer viewer) { try { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return -1; Display display= text.getDisplay(); Point absolutePosition= display.getCursorLocation(); Point relativePosition= text.toControl(absolutePosition); int widgetOffset= text.getOffsetAtLocation(relativePosition); if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; return extension.widgetOffset2ModelOffset(widgetOffset); } else { return widgetOffset + viewer.getVisibleRegion().getOffset(); } } catch (IllegalArgumentException e) { return -1; } } public void applyTextPresentation(TextPresentation textPresentation) { 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)); } private void highlightRegion(ISourceViewer viewer, IRegion region) { if (region.equals(fActiveRegion)) return; repairRepresentation(); StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; // Underline int offset= 0; int length= 0; if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; IRegion widgetRange= extension.modelRange2WidgetRange(region); if (widgetRange == null) return; offset= widgetRange.getOffset(); length= widgetRange.getLength(); } else { offset= region.getOffset() - viewer.getVisibleRegion().getOffset(); length= region.getLength(); } text.redrawRange(offset, length, false); // Invalidate region ==> apply text presentation fActiveRegion= region; if (viewer instanceof ITextViewerExtension2) ((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength()); else viewer.invalidateTextPresentation(); } private void activateCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; Display display= text.getDisplay(); if (fCursor == null) fCursor= new Cursor(display, SWT.CURSOR_HAND); text.setCursor(fCursor); } private void resetCursor(ISourceViewer viewer) { StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) text.setCursor(null); if (fCursor != null) { fCursor.dispose(); fCursor= null; } } /* * @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent) */ public void keyPressed(KeyEvent event) { if (fActive) { deactivate(); return; } if (event.keyCode != fKeyModifierMask) { deactivate(); return; } fActive= true; // removed for #25871 // // ISourceViewer viewer= getSourceViewer(); // if (viewer == null) // return; // // IRegion region= getCurrentTextRegion(viewer); // if (region == null) // return; // // highlightRegion(viewer, region); // activateCursor(viewer); } /* * @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent) */ public void keyReleased(KeyEvent event) { if (!fActive) return; deactivate(); } /* * @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) */ public void mouseDoubleClick(MouseEvent e) {} /* * @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent) */ public void mouseDown(MouseEvent event) { if (!fActive) return; if (event.stateMask != fKeyModifierMask) { deactivate(); return; } if (event.button != 1) { deactivate(); return; } } /* * @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent) */ public void mouseUp(MouseEvent e) { if (!fActive) return; if (e.button != 1) { deactivate(); return; } boolean wasActive= fCursor != null; deactivate(); if (wasActive) { IAction action= getAction("OpenEditor"); //$NON-NLS-1$ if (action != null) action.run(); } } /* * @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent) */ public void mouseMove(MouseEvent event) { if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) { deactivate(); return; } if (!fActive) { if (event.stateMask != fKeyModifierMask) return; // modifier was already pressed fActive= true; } ISourceViewer viewer= getSourceViewer(); if (viewer == null) { deactivate(); return; } StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) { deactivate(); return; } if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) { deactivate(); return; } IRegion region= getCurrentTextRegion(viewer); if (region == null || region.getLength() == 0) { repairRepresentation(); return; } highlightRegion(viewer, region); activateCursor(viewer); } /* * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) */ public void focusGained(FocusEvent e) {} /* * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent event) { deactivate(); } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { if (fActive && fActiveRegion != null) { fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength()); try { event.getDocument().addPosition(fRememberedPosition); } catch (BadLocationException x) { fRememberedPosition= null; } } } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { if (fRememberedPosition != null) { if (!fRememberedPosition.isDeleted()) { event.getDocument().removePosition(fRememberedPosition); fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength()); fRememberedPosition= null; ISourceViewer viewer= getSourceViewer(); if (viewer != null) { StyledText widget= viewer.getTextWidget(); if (widget != null && !widget.isDisposed()) { widget.getDisplay().asyncExec(new Runnable() { public void run() { deactivate(); } }); } } } else { fActiveRegion= null; fRememberedPosition= null; deactivate(); } } } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) { if (oldInput == null) return; deactivate(); oldInput.removeDocumentListener(this); } /* * @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument) */ public void inputDocumentChanged(IDocument oldInput, IDocument newInput) { if (newInput == null) return; newInput.addDocumentListener(this); } /* * @see PaintListener#paintControl(PaintEvent) */ public void paintControl(PaintEvent event) { if (fActiveRegion == null) return; ISourceViewer viewer= getSourceViewer(); if (viewer == null) return; StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; int offset= 0; int length= 0; if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length)); if (widgetRange == null) return; offset= widgetRange.getOffset(); length= widgetRange.getLength(); } else { IRegion region= viewer.getVisibleRegion(); if (!includes(region, fActiveRegion)) return; offset= fActiveRegion.getOffset() - region.getOffset(); length= fActiveRegion.getLength(); } // support for bidi 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; GC gc= event.gc; if (fColor != null && !fColor.isDisposed()) gc.setForeground(fColor); gc.drawLine(x1, y, x2, y); } private boolean includes(IRegion region, IRegion position) { return position.getOffset() >= region.getOffset() && position.getOffset() + position.getLength() <= region.getOffset() + region.getLength(); } 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++) { Point location= text.getLocationAtOffset(offset + i); if (location.x < minLocation.x) minLocation.x= location.x; if (location.y < minLocation.y) minLocation.y= location.y; } return minLocation; } 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++) { Point location= text.getLocationAtOffset(offset + i); if (location.x > maxLocation.x) maxLocation.x= location.x; if (location.y > maxLocation.y) maxLocation.y= location.y; } return maxLocation; } } /** * 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. */ class InformationDispatchAction extends TextEditorAction { /** The wrapped text operation action. */ private final TextOperationAction fTextOperationAction; /** * Creates a dispatch action. */ public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) { super(resourceBundle, prefix, JavaEditor.this); if (textOperationAction == null) throw new IllegalArgumentException(); fTextOperationAction= textOperationAction; } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { /** * Information provider used to present the information. * * @since 3.0 */ class InformationProvider implements IInformationProvider, IInformationProviderExtension2 { private IRegion fHoverRegion; private String fHoverInfo; private IInformationControlCreator fControlCreator; InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) { fHoverRegion= hoverRegion; fHoverInfo= hoverInfo; fControlCreator= controlCreator; } /* * @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int) */ public IRegion getSubject(ITextViewer textViewer, int invocationOffset) { return fHoverRegion; } /* * @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) { return fHoverInfo; } /* * @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator() * @since 3.0 */ public IInformationControlCreator getInformationPresenterControlCreator() { return fControlCreator; } } ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) { fTextOperationAction.run(); return; } if (sourceViewer instanceof ITextViewerExtension4) { ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer; if (extension4.moveFocusToWidgetToken()) return; } if (! (sourceViewer instanceof ITextViewerExtension2)) { fTextOperationAction.run(); return; } ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer; // does a text hover exist? ITextHover textHover= textViewerExtension2.getCurrentTextHover(); if (textHover == null) { fTextOperationAction.run(); return; } Point hoverEventLocation= textViewerExtension2.getHoverEventLocation(); int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y); if (offset == -1) { fTextOperationAction.run(); return; } try { // get the text hover content String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset); IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset); if (hoverRegion == null) return; String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion); IInformationControlCreator controlCreator= null; if (textHover instanceof IInformationProviderExtension2) controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator(); IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator); fInformationPresenter.setOffset(offset); fInformationPresenter.setInformationProvider(informationProvider, contentType); fInformationPresenter.showInformation(); } catch (BadLocationException e) { } } // modified version from TextViewer private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) { StyledText styledText= textViewer.getTextWidget(); IDocument document= textViewer.getDocument(); if (document == null) return -1; try { int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y)); if (textViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer; return extension.widgetOffset2ModelOffset(widgetLocation); } else { IRegion visibleRegion= textViewer.getVisibleRegion(); return widgetLocation + visibleRegion.getOffset(); } } catch (IllegalArgumentException e) { return -1; } } } private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener { /* * @see IPropertyChangeListener#propertyChange(PropertyChangeEvent) */ public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { handlePreferencePropertyChanged(event); } } /** * 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. * * @since 3.0 */ protected class SmartLineStartAction extends LineStartAction { /** * Creates a new smart line start action * * @param textWidget the styled text widget * @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected */ public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) { super(textWidget, doSelect); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String) */ protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) { String type= IDocument.DEFAULT_CONTENT_TYPE; try { type= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset).getType(); } catch (BadLocationException exception) { // Should not happen } int index= super.getLineStartPosition(document, line, length, offset); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) { if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } else { if (index < length - 1 && line.charAt(index) == '/' && line.charAt(++index) == '/') { do { ++index; } while (index < length && Character.isWhitespace(line.charAt(index))); } } return index; } } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected abstract class NextSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new next sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected NextSubWordAction(int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Check whether right hand character of caret is valid identifier start if (Character.isJavaIdentifierStart(document.getChar(position))) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final String buffer= document.get(position, region.getOffset() + region.getLength() - position); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character do { // Check whether we reached end of word offset= iterator.getOffset(); if (!Character.isJavaIdentifierPart(document.getChar(position + offset))) throw new BadLocationException(); // Test next characters order= iterator.next(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check for leading underscores position += offset; if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) { setCaretPosition(position); getTextWidget().showSelection(); fireSelectionChanged(); return; } } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the next sub-word. * * @since 3.0 */ protected class NavigateNextSubWordAction extends NextSubWordAction { /** * Creates a new navigate next sub-word action. */ public NavigateNextSubWordAction() { super(ST.WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position)); } } /** * Text operation action to delete the next sub-word. * * @since 3.0 */ protected class DeleteNextSubWordAction extends NextSubWordAction { /** * Creates a new delete next sub-word action. */ public DeleteNextSubWordAction() { super(ST.DELETE_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the next sub-word. * * @since 3.0 */ protected class SelectNextSubWordAction extends NextSubWordAction { /** * Creates a new select next sub-word action. */ public SelectNextSubWordAction() { super(ST.SELECT_WORD_NEXT); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); final int caret= text.getCaretOffset(); final int offset= modelOffset2WidgetOffset(viewer, position); if (caret == selection.x) text.setSelectionRange(selection.y, offset - selection.y); else text.setSelectionRange(selection.x, offset - selection.x); } } } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected abstract class PreviousSubWordAction extends TextNavigationAction { /** Collator to determine the sub-word boundaries */ private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance(); /** * Creates a new previous sub-word action. * * @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST. */ protected PreviousSubWordAction(final int code) { super(getSourceViewer().getTextWidget(), code); // Only compare upper-/lower case fCollator.setStrength(Collator.TERTIARY); } /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { try { final ISourceViewer viewer= getSourceViewer(); final IDocument document= viewer.getDocument(); int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1; // Check whether we are in a java code partititon and the preference is enabled final IPreferenceStore store= getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) { super.run(); return; } // Ignore trailing white spaces char character= document.getChar(position); while (position > 0 && Character.isWhitespace(character)) { --position; character= document.getChar(position); } // Check whether left hand character of caret is valid identifier part if (Character.isJavaIdentifierPart(character)) { int offset= 0; int order= CollationElementIterator.NULLORDER; short previous= Short.MAX_VALUE; short next= Short.MAX_VALUE; // Acquire collator for partition around caret final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position); final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1); final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer); // Iterate to first upper-case character iterator.setOffset(buffer.length() - 1); do { // Check whether we reached begin of word or single upper-case start offset= iterator.getOffset(); character= document.getChar(region.getOffset() + offset); if (!Character.isJavaIdentifierPart(character)) throw new BadLocationException(); else if (Character.isUpperCase(character)) { ++offset; break; } // Test next characters order= iterator.previous(); next= CollationElementIterator.tertiaryOrder(order); if (next <= previous) previous= next; else break; } while (order != CollationElementIterator.NULLORDER); // Check left character for multiple upper-case characters position= position - buffer.length() + offset - 1; character= document.getChar(position); while (position >= 0 && Character.isUpperCase(character)) character= document.getChar(--position); setCaretPosition(position + 1); getTextWidget().showSelection(); fireSelectionChanged(); return; } } catch (BadLocationException exception) { // Use default behavior } super.run(); } /** * Sets the caret position to the sub-word boundary given with <code>position</code>. * * @param position Position where the action should move the caret */ protected abstract void setCaretPosition(int position); } /** * Text navigation action to navigate to the previous sub-word. * * @since 3.0 */ protected class NavigatePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new navigate previous sub-word action. */ public NavigatePreviousSubWordAction() { super(ST.WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position)); } } /** * Text operation action to delete the previous sub-word. * * @since 3.0 */ protected class DeletePreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new delete previous sub-word action. */ public DeletePreviousSubWordAction() { super(ST.DELETE_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()); try { viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$ } catch (BadLocationException exception) { // Should not happen } } } /** * Text operation action to select the previous sub-word. * * @since 3.0 */ protected class SelectPreviousSubWordAction extends PreviousSubWordAction { /** * Creates a new select previous sub-word action. */ public SelectPreviousSubWordAction() { super(ST.SELECT_WORD_PREVIOUS); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int) */ protected void setCaretPosition(final int position) { final ISourceViewer viewer= getSourceViewer(); final StyledText text= viewer.getTextWidget(); if (text != null && !text.isDisposed()) { final Point selection= text.getSelection(); final int caret= text.getCaretOffset(); final int offset= modelOffset2WidgetOffset(viewer, position); if (caret == selection.x) text.setSelectionRange(selection.y, offset - selection.y); else text.setSelectionRange(selection.x, offset - selection.x); } } } /** * Quick format action to format the enclosing java element. * <p> * The quick format action works as follows: * <ul> * <li>If there is no selection and the caret is positioned on a Java element, * only this element is formatted. If the element has some accompanying comment, * then the comment is formatted as well.</li> * <li>If the selection spans one or more partitions of the document, then all * partitions covered by the selection are entirely formatted.</li> * <p> * Partitions at the end of the selection are not completed, except for comments. * * @since 3.0 */ protected class QuickFormatAction extends Action { /* * @see org.eclipse.jface.action.IAction#run() */ public void run() { final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer(); if (viewer.isEditable()) { final Point selection= viewer.rememberSelection(); try { viewer.setRedraw(false); final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x); if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) { try { final IJavaElement element= getElementAt(selection.x, true); if (element != null && element.exists()) { final int kind= element.getElementType(); if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) { final ISourceReference reference= (ISourceReference)element; final ISourceRange range= reference.getSourceRange(); if (range != null) { viewer.setSelectedRange(range.getOffset(), range.getLength()); viewer.doOperation(ISourceViewer.FORMAT); } } } } catch (JavaModelException exception) { // Should not happen } } else { viewer.setSelectedRange(selection.x, 1); viewer.doOperation(ISourceViewer.FORMAT); } } catch (BadLocationException exception) { // Can not happen } finally { viewer.setRedraw(true); viewer.restoreSelection(); } } } } /** * Internal activation listener. * @since 3.0 */ private class ActivationListener extends ShellAdapter { /* * @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent) */ public void shellActivated(ShellEvent e) { if (fMarkOccurrenceAnnotations && isActivePart()) SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)getSelectionProvider().getSelection()); } /* * @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent) */ public void shellDeactivated(ShellEvent e) { removeOccurrenceAnnotations(); } } /** Preference key for the link color */ protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR; /** Preference key for matching brackets */ protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS; /** Preference key for matching brackets color */ protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR; /** Preference key for compiler task tags */ private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; /** Preference key for browser like links */ private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS; /** Preference key for key modifier of browser like links */ private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER; /** * Preference key for key modifier mask of browser like links. * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> * cannot be resolved to valid SWT modifier bits. * * @since 2.1.1 */ private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK; protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' }; /** The outline page */ protected JavaOutlinePage fOutlinePage; /** Outliner context menu Id */ protected String fOutlinerContextMenuId; /** * The editor selection changed listener. * * @since 3.0 */ private EditorSelectionChangedListener fEditorSelectionChangedListener; /** The selection changed listener */ protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener(); /** The editor's bracket matcher */ protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS); /** This editor's encoding support */ private DefaultEncodingSupport fEncodingSupport; /** The mouse listener */ private MouseClickListener fMouseListener; /** The information presenter. */ private InformationPresenter fInformationPresenter; /** History for structure select action */ private SelectionHistory fSelectionHistory; /** The preference property change listener for java core. */ private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener(); /** * 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; protected CompositeActionGroup fActionGroups; private CompositeActionGroup fContextMenuGroup; /** * 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. * @since 3.0 */ private boolean fMarkOccurrenceAnnotations; /** * Tells whether the occurrence annotations are sticky * i.e. whether they stay even if there's no valid Java * element at the current caret position. * @since 3.0 */ private boolean fStickyOccurrenceAnnotations; /** * The internal shell activation listener for updating occurrences. * @since 3.0 */ private ActivationListener fActivationListener= new ActivationListener(); private ISelectionListenerWithAST fPostSelectionListenerWithAST; private Job fOccurrencesFinderJob; /** * Returns the most narrow java element including the given offset. * * @param offset the offset inside of the requested element * @return the most narrow java element */ abstract protected IJavaElement getElementAt(int offset); /** * 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); /** * Default constructor. */ public JavaEditor() { super(); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this, IJavaPartitions.JAVA_PARTITIONING)); setRangeIndicator(new DefaultRangeIndicator()); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); setPreferenceStore(store); setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$ fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES); fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES); } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) { ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles); StyledText text= viewer.getTextWidget(); text.addBidiSegmentListener(new BidiSegmentListener() { public void lineGetSegments(BidiSegmentEvent event) { event.segments= getBidiLineSegments(event.lineOffset, event.lineText); } }); JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR); // ensure source viewer decoration support has been created and configured getSourceViewerDecorationSupport(viewer); return viewer; } public final ISourceViewer getViewer() { return getSourceViewer(); } /* * @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) { return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles); } /* * @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent) */ protected boolean affectsTextPresentation(PropertyChangeEvent event) { JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.affectsBehavior(event); } /** * Sets the outliner's context menu ID. */ protected void setOutlinerContextMenuId(String menuId) { fOutlinerContextMenuId= menuId; } /** * Returns the standard action group of this editor. */ protected ActionGroup getActionGroup() { return fActionGroups; } /* * @see AbstractTextEditor#editorContextMenuAboutToShow */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); 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()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /** * Creates the outline page used with this editor. */ protected JavaOutlinePage createOutlinePage() { JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this); fOutlineSelectionChangedListener.install(page); setOutlinePageInput(page, getEditorInput()); return page; } /** * Informs the editor that its outliner has been closed. */ public void outlinePageClosed() { if (fOutlinePage != null) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage= null; resetHighlightRange(); } } /** * Synchronizes the outliner selection with the given element * position in the editor. * * @param element the java element to select */ protected void synchronizeOutlinePage(ISourceReference element) { synchronizeOutlinePage(element, true); } /** * Synchronizes the outliner selection with the given element * position in the editor. * * @param element the java element to select * @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done */ protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) { if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select(element); fOutlineSelectionChangedListener.install(fOutlinePage); } } /** * Synchronizes the outliner selection with the actual cursor * position in the editor. */ public void synchronizeOutlinePageSelection() { synchronizeOutlinePage(computeHighlightRangeSourceReference()); } /* * Get the desktop's StatusLineManager */ protected IStatusLineManager getStatusLineManager() { IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor(); if (contributor instanceof EditorActionBarContributor) { return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager(); } return null; } /* * @see AbstractTextEditor#getAdapter(Class) */ public Object getAdapter(Class required) { if (IContentOutlinePage.class.equals(required)) { if (fOutlinePage == null) fOutlinePage= createOutlinePage(); return fOutlinePage; } if (IEncodingSupport.class.equals(required)) return fEncodingSupport; if (required == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(required); } protected void setSelection(ISourceReference reference, boolean moveCursor) { ISelection selection= getSelectionProvider().getSelection(); if (selection instanceof TextSelection) { TextSelection textSelection= (TextSelection) selection; // PR 39995: [navigation] Forward history cleared after going back in navigation history: // mark only in navigation history if the cursor is being moved (which it isn't if // this is called from a PostSelectionEvent that should only update the magnet) if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0)) markInNavigationHistory(); } if (reference != null) { StyledText textWidget= null; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer != null) textWidget= sourceViewer.getTextWidget(); if (textWidget == null) return; try { ISourceRange range= null; if (reference instanceof ILocalVariable) { IJavaElement je= ((ILocalVariable)reference).getParent(); if (je instanceof ISourceReference) range= ((ISourceReference)je).getSourceRange(); } else range= reference.getSourceRange(); if (range == null) return; int offset= range.getOffset(); int length= range.getLength(); if (offset < 0 || length < 0) return; setHighlightRange(offset, length, moveCursor); if (!moveCursor) return; offset= -1; length= -1; if (reference instanceof IMember) { range= ((IMember) reference).getNameRange(); if (range != null) { offset= range.getOffset(); length= range.getLength(); } } else if (reference instanceof ILocalVariable) { range= ((ILocalVariable)reference).getNameRange(); if (range != null) { offset= range.getOffset(); length= range.getLength(); } } else if (reference instanceof IImportDeclaration) { String name= ((IImportDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); if (content != null) { offset= range.getOffset() + content.indexOf(name); length= name.length(); } } } else if (reference instanceof IPackageDeclaration) { String name= ((IPackageDeclaration) reference).getElementName(); if (name != null && name.length() > 0) { String content= reference.getSource(); if (content != null) { offset= range.getOffset() + content.indexOf(name); length= name.length(); } } } if (offset > -1 && length > 0) { try { textWidget.setRedraw(false); sourceViewer.revealRange(offset, length); sourceViewer.setSelectedRange(offset, length); } finally { textWidget.setRedraw(true); } markInNavigationHistory(); } } catch (JavaModelException x) { } catch (IllegalArgumentException x) { } } else if (moveCursor) { resetHighlightRange(); markInNavigationHistory(); } } public void setSelection(IJavaElement element) { if (element == null || element instanceof ICompilationUnit || element instanceof 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) */ return; } IJavaElement corresponding= getCorrespondingElement(element); if (corresponding instanceof ISourceReference) { ISourceReference reference= (ISourceReference) corresponding; // set hightlight range setSelection(reference, true); // set outliner selection if (fOutlinePage != null) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select(reference); fOutlineSelectionChangedListener.install(fOutlinePage); } } } protected void doSelectionChanged(SelectionChangedEvent event) { ISourceReference reference= null; ISelection selection= event.getSelection(); Iterator iter= ((IStructuredSelection) selection).iterator(); while (iter.hasNext()) { Object o= iter.next(); if (o instanceof ISourceReference) { reference= (ISourceReference) o; break; } } if (!isActivePart() && JavaPlugin.getActivePage() != null) JavaPlugin.getActivePage().bringToTop(this); setSelection(reference, !isActivePart()); } /* * @see AbstractTextEditor#adjustHighlightRange(int, int) */ protected void adjustHighlightRange(int offset, int length) { try { IJavaElement element= getElementAt(offset); while (element instanceof ISourceReference) { ISourceRange range= ((ISourceReference) element).getSourceRange(); if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) { setHighlightRange(range.getOffset(), range.getLength(), true); if (fOutlinePage != null) { fOutlineSelectionChangedListener.uninstall(fOutlinePage); fOutlinePage.select((ISourceReference) element); fOutlineSelectionChangedListener.install(fOutlinePage); } return; } element= element.getParent(); } } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); } resetHighlightRange(); } protected boolean isActivePart() { IWorkbenchPart part= getActivePart(); return part != null && part.equals(this); } private boolean isJavaOutlinePageActive() { IWorkbenchPart part= getActivePart(); return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage; } private IWorkbenchPart getActivePart() { IWorkbenchWindow window= getSite().getWorkbenchWindow(); IPartService service= window.getPartService(); IWorkbenchPart part= service.getActivePart(); return part; } /* * @see StatusTextEditor#getStatusHeader(IStatus) */ protected String getStatusHeader(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusHeader(status); if (message != null) return message; } return super.getStatusHeader(status); } /* * @see StatusTextEditor#getStatusBanner(IStatus) */ protected String getStatusBanner(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusBanner(status); if (message != null) return message; } return super.getStatusBanner(status); } /* * @see StatusTextEditor#getStatusMessage(IStatus) */ protected String getStatusMessage(IStatus status) { if (fEncodingSupport != null) { String message= fEncodingSupport.getStatusMessage(status); if (message != null) return message; } return super.getStatusMessage(status); } /* * @see AbstractTextEditor#doSetInput */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); if (fEncodingSupport != null) fEncodingSupport.reset(); setOutlinePageInput(fOutlinePage, input); } /* * @see IWorkbenchPart#dispose() */ public void dispose() { // cancel possible running computation fMarkOccurrenceAnnotations= false; uninstallOccurrencesFinder(); if (fActivationListener != null) { Shell shell= getEditorSite().getShell(); if (shell != null && !shell.isDisposed()) shell.removeShellListener(fActivationListener); fActivationListener= null; } if (isBrowserLikeLinks()) disableBrowserLikeLinks(); if (fEncodingSupport != null) { fEncodingSupport.dispose(); fEncodingSupport= null; } if (fPropertyChangeListener != null) { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } if (fBracketMatcher != null) { fBracketMatcher.dispose(); fBracketMatcher= null; } if (fSelectionHistory != null) { fSelectionHistory.dispose(); fSelectionHistory= null; } if (fEditorSelectionChangedListener != null) { fEditorSelectionChangedListener.uninstall(getSelectionProvider()); fEditorSelectionChangedListener= null; } super.dispose(); } protected void createActions() { super.createActions(); ActionGroup oeg, ovg, jsg, sg; fActionGroups= new CompositeActionGroup(new ActionGroup[] { oeg= new OpenEditorActionGroup(this), sg= new ShowActionGroup(this), ovg= new OpenViewActionGroup(this), jsg= new JavaSearchActionGroup(this) }); fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg}); ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$ resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$ resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC); setAction("ShowJavaDoc", resAction); //$NON-NLS-1$ WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION); Action action= new GotoMatchingBracketAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET); setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE); setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE); setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY); setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action); WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION); fEncodingSupport= new DefaultEncodingSupport(); fEncodingSupport.initialize(this); fSelectionHistory= new SelectionHistory(this); action= new StructureSelectEnclosingAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, action); action= new StructureSelectNextAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT); setAction(StructureSelectionAction.NEXT, action); action= new StructureSelectPreviousAction(this, fSelectionHistory); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS); setAction(StructureSelectionAction.PREVIOUS, action); StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory); historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST); setAction(StructureSelectionAction.HISTORY, historyAction); fSelectionHistory.setHistoryAction(historyAction); action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER); setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action); action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER); setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action); action= new QuickFormatAction(); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT); setAction(IJavaEditorActionDefinitionIds.QUICK_FORMAT, action); action= new RemoveOccurrenceAnnotations(this); action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS); setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$ // add annotation actions action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$ setAction("AnnotationAction", action); //$NON-NLS-1$ } public void updatedTitleImage(Image image) { setTitleImage(image); } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return; String property= event.getProperty(); if (isJavaEditorHoverProperty(property)) updateHoverBehavior(); if (BROWSER_LIKE_LINKS.equals(property)) { if (isBrowserLikeLinks()) enableBrowserLikeLinks(); else disableBrowserLikeLinks(); return; } if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) { if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) fEditorSelectionChangedListener.selectionChanged(); return; } if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) { if (event.getNewValue() instanceof Boolean) { Boolean disable= (Boolean) event.getNewValue(); configureInsertMode(OVERWRITE, !disable.booleanValue()); } } if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) { if (event.getNewValue() instanceof Boolean) { boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue(); if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) { fMarkOccurrenceAnnotations= markOccurrenceAnnotations; if (!fMarkOccurrenceAnnotations) uninstallOccurrencesFinder(); else installOccurrencesFinder(); } } } if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) { if (event.getNewValue() instanceof Boolean) { boolean stickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue(); if (stickyOccurrenceAnnotations != fStickyOccurrenceAnnotations) { fStickyOccurrenceAnnotations= stickyOccurrenceAnnotations; // if (!fMarkOccurrenceAnnotations) // uninstallOccurrencesFinder(); // else // installOccurrencesFinder(); } } } } finally { super.handlePreferenceStoreChanged(event); } } /** * Initializes the given viewer's colors. * * @param viewer the viewer to be initialized * @since 3.0 */ protected void initializeViewerColors(ISourceViewer viewer) { // is handled by JavaSourceViewer } private boolean isJavaEditorHoverProperty(String property) { return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property); } /** * Return whether the browser like links should be enabled * according to the preference store settings. * @return <code>true</code> if the browser like links should be enabled */ private boolean isBrowserLikeLinks() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(BROWSER_LIKE_LINKS); } /** * Enables browser like links. */ private void enableBrowserLikeLinks() { if (fMouseListener == null) { fMouseListener= new MouseClickListener(); fMouseListener.install(); } } /** * Disables browser like links. */ private void disableBrowserLikeLinks() { if (fMouseListener != null) { fMouseListener.uninstall(); fMouseListener= null; } } /** * 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 */ 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()))) sourceViewer.invalidateTextPresentation(); } } /** * Returns a segmentation of the line of the given viewer's input document appropriate for * bidi rendering. The default implementation returns only the string literals of a java code * line as segments. * * @param viewer the text viewer * @param lineOffset the offset of the line * @return the line's bidi segmentation * @throws BadLocationException in case lineOffset is not valid in document */ public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException { IDocument document= viewer.getDocument(); if (document == null) return null; IRegion line= document.getLineInformationOfOffset(lineOffset); ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength()); List segmentation= new ArrayList(); for (int i= 0; i < linePartitioning.length; i++) { if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType())) segmentation.add(linePartitioning[i]); } if (segmentation.size() == 0) return null; int size= segmentation.size(); int[] segments= new int[size * 2 + 1]; int j= 0; for (int i= 0; i < size; i++) { ITypedRegion segment= (ITypedRegion) segmentation.get(i); if (i == 0) segments[j++]= 0; int offset= segment.getOffset() - lineOffset; if (offset > segments[j - 1]) segments[j++]= offset; if (offset + segment.getLength() >= line.getLength()) break; segments[j++]= offset + segment.getLength(); } if (j < segments.length) { int[] result= new int[j]; System.arraycopy(segments, 0, result, 0, j); segments= result; } return segments; } /** * Returns a segmentation of the given line appropriate for bidi rendering. The default * implementation returns only the string literals of a java code line as segments. * * @param lineOffset the offset of the line * @param line the content of the line * @return the line's bidi segmentation */ protected int[] getBidiLineSegments(int widgetLineOffset, String line) { if (line != null && line.length() > 0) { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer != null) { int lineOffset; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer; lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset); } else { IRegion visible= sourceViewer.getVisibleRegion(); lineOffset= visible.getOffset() + widgetLineOffset; } try { return getBidiLineSegments(sourceViewer, lineOffset); } catch (BadLocationException x) { // don't segment line in this case } } } return null; } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions() */ protected void updatePropertyDependentActions() { super.updatePropertyDependentActions(); if (fEncodingSupport != null) fEncodingSupport.reset(); } /* * Update the hovering behavior depending on the preferences. */ private void updateHoverBehavior() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(getSourceViewer()); for (int i= 0; i < types.length; i++) { String t= types[i]; ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension2) { // Remove existing hovers ((ITextViewerExtension2)sourceViewer).removeTextHovers(t); int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t); if (stateMasks != null) { for (int j= 0; j < stateMasks.length; j++) { int stateMask= stateMasks[j]; ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask); } } else { ITextHover textHover= configuration.getTextHover(sourceViewer, t); ((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK); } } else sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t); } } /* * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return getEditorInput().getAdapter(IJavaElement.class); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection) */ protected void doSetSelection(ISelection selection) { super.doSetSelection(selection); synchronizeOutlinePageSelection(); } /* * @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); preferences.addPropertyChangeListener(fPropertyChangeListener); IInformationControlCreator informationControlCreator= new IInformationControlCreator() { public IInformationControl createInformationControl(Shell shell) { boolean cutDown= false; int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL); return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown)); } }; fInformationPresenter= new InformationPresenter(informationControlCreator); fInformationPresenter.setSizeConstraints(60, 10, true, true); fInformationPresenter.install(getSourceViewer()); fEditorSelectionChangedListener= new EditorSelectionChangedListener(); fEditorSelectionChangedListener.install(getSelectionProvider()); if (isBrowserLikeLinks()) enableBrowserLikeLinks(); if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE)) configureInsertMode(OVERWRITE, false); if (fMarkOccurrenceAnnotations) installOccurrencesFinder(); getEditorSite().getShell().addShellListener(fActivationListener); } protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) { support.setCharacterPairMatcher(fBracketMatcher); support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR); super.configureSourceViewerDecorationSupport(support); } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker) */ public void gotoMarker(IMarker marker) { fLastMarkerTarget= marker; if (!fIsUpdatingAnnotationViews) { super.gotoMarker(marker); } } /** * 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 <code>true</code> if search direction is forward, <code>false</code> if backward */ public void gotoAnnotation(boolean forward) { ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection(); Position position= new Position(0, 0); if (false /* delayed - see bug 18316 */) { getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); selectAndReveal(position.getOffset(), position.getLength()); } else /* no delay - see bug 18316 */ { Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position); setStatusLineErrorMessage(null); setStatusLineMessage(null); if (annotation != null) { updateAnnotationViews(annotation); selectAndReveal(position.getOffset(), position.getLength()); setStatusLineMessage(annotation.getText()); } } } /** * Updates the annotation views that show the given annotation. * * @param annotation the annotation */ private void updateAnnotationViews(Annotation annotation) { IMarker marker= null; if (annotation instanceof MarkerAnnotation) marker= ((MarkerAnnotation) annotation).getMarker(); else if (annotation instanceof IJavaAnnotation) { Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator(); if (e != null) { while (e.hasNext()) { Object o= e.next(); if (o instanceof MarkerAnnotation) { marker= ((MarkerAnnotation) o).getMarker(); break; } } } } if (marker != null && !marker.equals(fLastMarkerTarget)) { 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$ 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 }); } } catch (CoreException x) { } catch (NoSuchMethodException x) { } catch (IllegalAccessException x) { } catch (InvocationTargetException x) { } // ignore exceptions, don't update any of the lists, just set statusline } } /** * Finds and marks occurrence annotations. * * @since 3.0 */ class OccurrencesFinderJob extends Job implements IDocumentListener { private IDocument fDocument; private boolean fCancelled= false; private IProgressMonitor fProgressMonitor; private Position[] fPositions; public OccurrencesFinderJob(IDocument document, Position[] positions) { super("Occurrences Marker"); //$NON-NLS-1$ fDocument= document; fPositions= positions; fDocument.addDocumentListener(this); } private boolean isCancelled() { return fCancelled || fProgressMonitor.isCanceled(); } /* * @see Job#run(org.eclipse.core.runtime.IProgressMonitor) */ public IStatus run(IProgressMonitor progressMonitor) { fProgressMonitor= progressMonitor; try { if (isCancelled()) return Status.CANCEL_STATUS; ITextViewer textViewer= getViewer(); if (textViewer == null) return Status.CANCEL_STATUS; IDocument document= textViewer.getDocument(); if (document == null) return Status.CANCEL_STATUS; IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider == null) return Status.CANCEL_STATUS; IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput()); if (annotationModel == null) return Status.CANCEL_STATUS; // Add occurrence annotations int length= fPositions.length; Map annotationMap= new HashMap(length); for (int i= 0; i < length; i++) { if (isCancelled()) return Status.CANCEL_STATUS; String message; Position position= fPositions[i]; // Create & add annotation try { message= document.get(position.offset, position.length); } catch (BadLocationException ex) { // Skip this match continue; } annotationMap.put( new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$ position); } if (isCancelled()) return Status.CANCEL_STATUS; synchronized (annotationModel) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap); } else { removeOccurrenceAnnotations(); Iterator iter= annotationMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry mapEntry= (Map.Entry)iter.next(); annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue()); } } fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]); } } finally { fDocument.removeDocumentListener(this); } return Status.OK_STATUS; } /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { fCancelled= true; } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { } } /** * Updates the occurrences annotations based * on the current selection. * * @since 3.0 */ protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) { if (!fMarkOccurrenceAnnotations) return; if (astRoot == null || selection == null) return; IDocument document= getSourceViewer().getDocument(); if (document == null) return; if (fOccurrencesFinderJob != null) fOccurrencesFinderJob.cancel(); ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder(); String message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength()); List matches= new ArrayList(); if (message == null) { matches= exceptionFinder.perform(); } if (matches.size() == 0) { ASTNode node= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength()); if (!(node instanceof Name)) { if (!fStickyOccurrenceAnnotations) removeOccurrenceAnnotations(); return; } IBinding binding= ((Name)node).resolveBinding(); if (binding == null && fStickyOccurrenceAnnotations) return; // Find the matches && extract positions so we can forget the AST OccurrencesFinder finder = new OccurrencesFinder(binding); message= finder.initialize(astRoot, selection.getOffset(), selection.getLength()); if (message == null) { matches= finder.perform(); } } Position[] positions= new Position[matches.size()]; int i= 0; for (Iterator each= matches.iterator(); each.hasNext();) { ASTNode currentNode= (ASTNode)each.next(); positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength()); } fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions); //fOccurrencesFinderJob.setPriority(Job.DECORATE); //fOccurrencesFinderJob.setSystem(true); //fOccurrencesFinderJob.schedule(); ((OccurrencesFinderJob) fOccurrencesFinderJob).run(new NullProgressMonitor()); } protected void installOccurrencesFinder() { fMarkOccurrenceAnnotations= true; fPostSelectionListenerWithAST= new ISelectionListenerWithAST() { public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) { updateOccurrenceAnnotations(selection, astRoot); } }; SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST); } protected void uninstallOccurrencesFinder() { fMarkOccurrenceAnnotations= false; if (fOccurrencesFinderJob != null) { fOccurrencesFinderJob.cancel(); fOccurrencesFinderJob= null; } if (fPostSelectionListenerWithAST != null) { SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST); fPostSelectionListenerWithAST= null; } removeOccurrenceAnnotations(); } void removeOccurrenceAnnotations() { IDocumentProvider documentProvider= getDocumentProvider(); if (documentProvider == null) return; IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput()); if (annotationModel == null || fOccurrenceAnnotations == null) return; synchronized (annotationModel) { if (annotationModel instanceof IAnnotationModelExtension) { ((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null); } else { for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++) annotationModel.removeAnnotation(fOccurrenceAnnotations[i]); } fOccurrenceAnnotations= null; } } /** * 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()); setStatusLineErrorMessage(null); setStatusLineMessage(null); if (annotation != null) { try { fIsUpdatingAnnotationViews= true; updateAnnotationViews(annotation); } finally { fIsUpdatingAnnotationViews= false; } if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem()) setStatusLineMessage(annotation.getText()); } } /** * Jumps to the matching bracket. */ public void gotoMatchingBracket() { ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); if (document == null) return; IRegion selection= getSignedSelection(sourceViewer); int selectionLength= Math.abs(selection.getLength()); if (selectionLength > 1) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } // #26314 int sourceCaretOffset= selection.getOffset() + selection.getLength(); if (isSurroundedByBrackets(document, sourceCaretOffset)) sourceCaretOffset -= selection.getLength(); IRegion region= fBracketMatcher.match(document, sourceCaretOffset); if (region == null) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } int offset= region.getOffset(); int length= region.getLength(); if (length < 1) return; int anchor= fBracketMatcher.getAnchor(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length; boolean visible= false; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer; visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1); } else { IRegion visibleRegion= sourceViewer.getVisibleRegion(); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34195 visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength()); } if (!visible) { setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$ sourceViewer.getTextWidget().getDisplay().beep(); return; } if (selection.getLength() < 0) targetOffset -= selection.getLength(); sourceViewer.setSelectedRange(targetOffset, selection.getLength()); sourceViewer.revealRange(targetOffset, selection.getLength()); } /** * Sets the given message as error message to this editor's status line. * * @param msg message to be set */ protected void setStatusLineErrorMessage(String msg) { IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(true, msg, null); } /** * Sets the given message as message to this editor's status line. * * @param msg message to be set * @since 3.0 */ protected void setStatusLineMessage(String msg) { IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class); if (statusLine != null) statusLine.setMessage(false, msg, null); } /** * Returns the signed current selection. * The length will be negative if the resulting selection * is right-to-left (RtoL). * <p> * The selection offset is model based. * </p> * * @param sourceViewer the source viewer * @return a region denoting the current signed selection, for a resulting RtoL selections lenght is < 0 */ protected IRegion getSignedSelection(ISourceViewer sourceViewer) { StyledText text= sourceViewer.getTextWidget(); Point selection= text.getSelectionRange(); if (text.getCaretOffset() == selection.x) { selection.x= selection.x + selection.y; selection.y= -selection.y; } selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x); return new Region(selection.x, selection.y); } private static boolean isBracket(char character) { for (int i= 0; i != BRACKETS.length; ++i) if (character == BRACKETS[i]) return true; return false; } private static boolean isSurroundedByBrackets(IDocument document, int offset) { if (offset == 0 || offset == document.getLength()) return false; try { return isBracket(document.getChar(offset - 1)) && isBracket(document.getChar(offset)); } catch (BadLocationException e) { return false; } } /** * 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 * @param length the region length * @param forward <code>true</code> for forwards, <code>false</code> for backward * @param annotationPosition the position of the found annotation * @return the found annotation */ private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) { Annotation nextAnnotation= null; Position nextAnnotationPosition= null; Annotation containingAnnotation= null; Position containingAnnotationPosition= null; boolean currentAnnotation= false; IDocument document= getDocumentProvider().getDocument(getEditorInput()); int endOfDocument= document.getLength(); int distance= Integer.MAX_VALUE; IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a)) continue; Position p= model.getPosition(a); if (p == null) continue; if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) { if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) { containingAnnotation= a; containingAnnotationPosition= p; currentAnnotation= p.length == length; } } else { int currentDistance= 0; if (forward) { currentDistance= p.getOffset() - offset; if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } else { currentDistance= offset + length - (p.getOffset() + p.length); if (currentDistance < 0) currentDistance= endOfDocument + currentDistance; if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) { distance= currentDistance; nextAnnotation= a; nextAnnotationPosition= p; } } } } if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) { annotationPosition.setOffset(containingAnnotationPosition.getOffset()); annotationPosition.setLength(containingAnnotationPosition.getLength()); return containingAnnotation; } if (nextAnnotationPosition != null) { annotationPosition.setOffset(nextAnnotationPosition.getOffset()); annotationPosition.setLength(nextAnnotationPosition.getLength()); } return nextAnnotation; } /** * Returns the annotation overlapping with the given range or <code>null</code>. * * @param offset the region offset * @param length the region length * @return the found annotation or <code>null</code> * @since 3.0 */ private Annotation getAnnotation(int offset, int length) { IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput()); Iterator e= new JavaAnnotationIterator(model, true, true); while (e.hasNext()) { Annotation a= (Annotation) e.next(); if (!isNavigationTarget(a)) continue; Position p= model.getPosition(a); if (p != null && p.overlapsWith(offset, length)) return a; } return null; } /** * Returns whether the given annotation is configured as a target for the * "Go to Next/Previous Annotation" actions * * @param annotation the annotation * @return <code>true</code> if this is a target, <code>false</code> * otherwise * @since 3.0 */ private boolean isNavigationTarget(Annotation annotation) { Preferences preferences= Platform.getPlugin(EditorsUI.PLUGIN_ID).getPluginPreferences(); AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation); // See bug 41689 // String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey(); String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey(); return (key != null && preferences.getBoolean(key)); } /** * 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 */ protected ISourceReference computeHighlightRangeSourceReference() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer == null) return null; StyledText styledText= sourceViewer.getTextWidget(); if (styledText == null) return null; int caret= 0; if (sourceViewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer; caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset()); } else { int offset= sourceViewer.getVisibleRegion().getOffset(); caret= offset + styledText.getCaretOffset(); } IJavaElement element= getElementAt(caret, false); if ( !(element instanceof ISourceReference)) return null; if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) { IImportDeclaration declaration= (IImportDeclaration) element; IImportContainer container= (IImportContainer) declaration.getParent(); ISourceRange srcRange= null; try { srcRange= container.getSourceRange(); } catch (JavaModelException e) { } if (srcRange != null && srcRange.getOffset() == caret) return container; } return (ISourceReference) element; } /** * Returns the most narrow java element including the given offset. * * @param offset the offset inside of the requested element * @param reconcile <code>true</code> if editor input should be reconciled in advance * @return the most narrow java element * @since 3.0 */ protected IJavaElement getElementAt(int offset, boolean reconcile) { return getElementAt(offset); } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#createChangeHover() */ protected LineChangeHover createChangeHover() { return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING); } protected boolean isPrefQuickDiffAlwaysOn() { return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions() */ protected void createNavigationActions() { super.createNavigationActions(); final StyledText textWidget= getSourceViewer().getTextWidget(); IAction action= new SmartLineStartAction(textWidget, false); action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START); setAction(ITextEditorActionDefinitionIds.LINE_START, action); action= new SmartLineStartAction(textWidget, true); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START); setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action); action= new NavigatePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL); action= new NavigateNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT); setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL); action= new DeletePreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL); action= new DeleteNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD); setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action); textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL); action= new SelectPreviousSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL); action= new SelectNextSubWordAction(); action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT); setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action); textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL); } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#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, ruler, 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(); } } }, getAnnotationAccess())); ruler.addDecorator(0, column); if (isLineNumberRulerVisible()) ruler.addDecorator(1, createLineNumberRulerColumn()); else if (isPrefQuickDiffAlwaysOn()) ruler.addDecorator(1, createChangeRulerColumn()); return ruler; } }
52,257
Bug 52257 NPE in org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.getSignedSelection
I'm editing Java and doing CVS. A dialog box comes up: File Changed The File has been changed on the file system. Do you want to load the changes? I saw yes, then these error come out: !ENTRY org.eclipse.core.filebuffers 4 0 Feb 17, 2004 23:40:36.778 !MESSAGE Exception when synchronizing !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.getSignedSelection(JavaEditor.java:3034) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$RememberedSelection.remember(CompilationUnitEditor.java:658) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.rememberSelection(CompilationUnitEditor.java:1540) at org.eclipse.ui.texteditor.AbstractTextEditor$3.run(AbstractTextEditor.java:282) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener.execute(AbstractTextEditor.java:385) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener.elementContentAboutToBeReplaced(AbstractTextEditor.java:286) at org.eclipse.ui.editors.text.TextFileDocumentProvider$FileBufferListener.bufferContentAboutToBeReplaced(TextFileDocumentProvider.java:200) at org.eclipse.core.internal.filebuffers.TextFileBufferManager.fireBufferContentAboutToBeReplaced(TextFileBufferManager.java:234) at org.eclipse.core.internal.filebuffers.ResourceTextFileBuffer.handleFileContentChanged(ResourceTextFileBuffer.java:271) at org.eclipse.core.internal.filebuffers.ResourceFileBuffer$1.execute(ResourceFileBuffer.java:142) at org.eclipse.core.internal.filebuffers.ResourceFileBuffer$SafeFileChange.run(ResourceFileBuffer.java:76) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2325) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2033) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1550) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1526) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:265) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:257) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581) !ENTRY org.eclipse.core.runtime 4 2 Feb 17, 2004 23:54:26.138 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.core.runtime". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.getSignedSelection(JavaEditor.java:3034) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$RememberedSelection.remember(CompilationUnitEditor.java:658) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor.rememberSelection(CompilationUnitEditor.java:1540) at org.eclipse.ui.texteditor.AbstractTextEditor$3.run(AbstractTextEditor.java:282) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener.execute(AbstractTextEditor.java:385) at org.eclipse.ui.texteditor.AbstractTextEditor$ElementStateListener.elementContentAboutToBeReplaced(AbstractTextEditor.java:286) at org.eclipse.ui.editors.text.TextFileDocumentProvider$FileBufferListener.bufferContentAboutToBeReplaced(TextFileDocumentProvider.java:200) at org.eclipse.core.internal.filebuffers.TextFileBufferManager.fireBufferContentAboutToBeReplaced(TextFileBufferManager.java:234) at org.eclipse.core.internal.filebuffers.ResourceTextFileBuffer.revert(ResourceTextFileBuffer.java:159) at org.eclipse.ui.editors.text.TextFileDocumentProvider$5.execute(TextFileDocumentProvider.java:873) at org.eclipse.ui.editors.text.TextFileDocumentProvider$DocumentProviderOperation.run(TextFileDocumentProvider.java:93) at org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation.execute(WorkspaceModifyDelegatingOperation.java:67) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:91) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1567) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:105) at org.eclipse.ui.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:72) at org.eclipse.ui.editors.text.WorkspaceOperationRunner.run(WorkspaceOperationRunner.java:62) at org.eclipse.ui.editors.text.TextFileDocumentProvider.executeOperation(TextFileDocumentProvider.java:391) at org.eclipse.ui.editors.text.TextFileDocumentProvider.synchronize(TextFileDocumentProvider.java:885) at org.eclipse.ui.texteditor.AbstractTextEditor.handleEditorInputChanged(AbstractTextEditor.java:2782) at org.eclipse.ui.texteditor.AbstractTextEditor.sanityCheckState(AbstractTextEditor.java:2901) at org.eclipse.ui.texteditor.StatusTextEditor.sanityCheckState(StatusTextEditor.java:193) at org.eclipse.ui.texteditor.AbstractTextEditor.safelySanityCheckState(AbstractTextEditor.java:2879) at org.eclipse.ui.texteditor.AbstractTextEditor$ActivationListener.handleActivation(AbstractTextEditor.java:711) at org.eclipse.ui.texteditor.AbstractTextEditor$ActivationListener.partActivated(AbstractTextEditor.java:657) at org.eclipse.ui.internal.PartListenerList$1.run(PartListenerList.java:49) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:819) at org.eclipse.core.runtime.Platform.run(Platform.java:493) at org.eclipse.ui.internal.PartListenerList.firePartActivated(PartListenerList.java:47) at org.eclipse.ui.internal.WWinPartService$1.partActivated(WWinPartService.java:27) at org.eclipse.ui.internal.PartListenerList2$1.run(PartListenerList2.java:45) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:819) at org.eclipse.core.runtime.Platform.run(Platform.java:493) at org.eclipse.ui.internal.PartListenerList2.firePartActivated(PartListenerList2.java:43) at org.eclipse.ui.internal.WorkbenchPage.firePartActivated(WorkbenchPage.java:1277) at org.eclipse.ui.internal.WorkbenchPage.setActivePart(WorkbenchPage.java:2565) at org.eclipse.ui.internal.WorkbenchPage.activate(WorkbenchPage.java:455) at org.eclipse.ui.internal.WorkbenchPage.showEditor(WorkbenchPage.java:2146) at org.eclipse.ui.internal.WorkbenchPage.busyOpenEditor(WorkbenchPage.java:2084) at org.eclipse.ui.internal.WorkbenchPage.access$6(WorkbenchPage.java:2042) at org.eclipse.ui.internal.WorkbenchPage$9.run(WorkbenchPage.java:2029) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.ui.internal.WorkbenchPage.openEditor(WorkbenchPage.java:2024) at org.eclipse.ui.ide.IDE.openEditor(IDE.java:265) at org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor(EditorUtility.java:134) at org.eclipse.jdt.internal.ui.javaeditor.EditorUtility.openInEditor(EditorUtility.java:112) at org.eclipse.jdt.internal.ui.actions.OpenActionUtil.open(OpenActionUtil.java:49) at org.eclipse.jdt.ui.actions.OpenAction.run(OpenAction.java:158) at org.eclipse.jdt.ui.actions.OpenAction.run(OpenAction.java:147) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerActionGroup.handleOpen(PackageExplorerActionGroup.java:329) at org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart$5.open(PackageExplorerPart.java:303) at org.eclipse.jface.viewers.StructuredViewer$2.run(StructuredViewer.java:406) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:819) at org.eclipse.core.runtime.Platform.run(Platform.java:493) at org.eclipse.jface.viewers.StructuredViewer.fireOpen(StructuredViewer.java:404) at org.eclipse.jface.viewers.StructuredViewer.handleOpen(StructuredViewer.java:614) at org.eclipse.jface.viewers.StructuredViewer$6.handleOpen(StructuredViewer.java:703) at org.eclipse.jface.util.OpenStrategy.fireOpenEvent(OpenStrategy.java:209) at org.eclipse.jface.util.OpenStrategy.access$2(OpenStrategy.java:204) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:233) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:833) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2348) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2029) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1550) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1526) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:265) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:257) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:104) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:279) at org.eclipse.core.launcher.Main.run(Main.java:742) at org.eclipse.core.launcher.Main.main(Main.java:581) Build: 200402122000 Windows 2003 Enterprise (Evaluation) Sun JDK 1.4.2_03
verified fixed
b28a95a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T16:23:54Z
2004-02-17T15:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
/******************************************************************************* * Copyright (c) 2000, 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 Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.window.Window; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistantExtension; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.editors.text.IStorageDocumentProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddBlockCommentAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.IndentAction; import org.eclipse.jdt.internal.ui.actions.RemoveBlockCommentAction; import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant; import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant; import org.eclipse.jdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy; import org.eclipse.jdt.internal.ui.text.link.ExclusivePositionUpdater; import org.eclipse.jdt.internal.ui.text.link.ILinkedListener; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.ExitFlags; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.IExitPolicy; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant { /** * Text operation code for requesting correction assist to show correction * proposals for the current position. */ public static final int CORRECTIONASSIST_PROPOSALS= 50; /** * Text operation code for requesting common prefix completion. */ public static final int CONTENTASSIST_COMPLETE_PREFIX= 60; interface ITextConverter { void customizeDocumentCommand(IDocument document, DocumentCommand command); } class AdaptedSourceViewer extends JavaSourceViewer { private List fTextConverters; private boolean fIgnoreTextConverters= false; private JavaCorrectionAssistant fCorrectionAssistant; 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: msg= fCorrectionAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case UNDO: fIgnoreTextConverters= true; break; case REDO: fIgnoreTextConverters= true; break; case CONTENTASSIST_COMPLETE_PREFIX: if (fContentAssistant instanceof IContentAssistantExtension) { msg= ((IContentAssistantExtension) fContentAssistant).completePrefix(); setStatusLineErrorMessage(msg); return; } else break; } super.doOperation(operation); } /* * @see ITextOperationTarget#canDoOperation(int) */ public boolean canDoOperation(int operation) { if (operation == CORRECTIONASSIST_PROPOSALS) return isEditable(); else if (operation == CONTENTASSIST_COMPLETE_PREFIX) return isEditable(); return super.canDoOperation(operation); } /** * @inheritDoc * @since 3.0 */ public void unconfigure() { if (fCorrectionAssistant != null) { fCorrectionAssistant.uninstall(); fCorrectionAssistant= null; } super.unconfigure(); } 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 IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int) * @since 3.0 */ public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; 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(IJavaPartitions.JAVA_PARTITIONING); prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); } } static class TabConverter implements ITextConverter { private int fTabRatio; private ILineTracker fLineTracker; public TabConverter() { } public void setNumberOfSpacesPerTab(int ratio) { fTabRatio= ratio; } public void setLineTracker(ILineTracker lineTracker) { fLineTracker= lineTracker; } 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; } 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) { } } } } private class ExitPolicy implements IExitPolicy { final char fExitCharacter; final char fEscapeCharacter; final Stack fStack; final int fSize; public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) { fExitCharacter= exitCharacter; fEscapeCharacter= escapeCharacter; fStack= stack; fSize= fStack.size(); } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(LinkedEnvironment environment, VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (fSize == fStack.size() && !isMasked(offset)) { BracketLevel level= (BracketLevel) fStack.peek(); if (level.fFirstPosition.offset > offset || level.fSecondPosition.offset < offset) return null; if (level.fSecondPosition.offset == offset && length == 0) // don't enter the character if if its the closing peer return new ExitFlags(ILinkedListener.UPDATE_CARET, false); else return new ExitFlags(ILinkedListener.UPDATE_CARET, true); } } return null; } private boolean isMasked(int offset) { IDocument document= getSourceViewer().getDocument(); try { return fEscapeCharacter == document.getChar(offset - 1); } catch (BadLocationException e) { } return false; } } private static class BracketLevel { int fOffset; int fLength; LinkedUIControl fEditor; Position fFirstPosition; Position fSecondPosition; } private class BracketInserter implements VerifyKeyListener, ILinkedListener { private boolean fCloseBrackets= true; private boolean fCloseStrings= true; private final String CATEGORY= toString(); private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY); private Stack fBracketLevelStack= new Stack(); public void setCloseBracketsEnabled(boolean enabled) { fCloseBrackets= enabled; } public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } 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 && Character.isJavaIdentifierPart(document.getChar(end)); } catch (BadLocationException e) { // be conservative return true; } } 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 && Character.isJavaIdentifierPart(document.getChar(start - 1)); } catch (BadLocationException e) { return true; } } 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; } } /* * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit || getInsertMode() != SMART_INSERT) return; final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); final Point selection= sourceViewer.getSelectedRange(); final int offset= selection.x; final int length= selection.y; switch (event.character) { case '(': if (hasCharacterToTheRight(document, offset + length, '(')) return; // fall through case '[': if (!fCloseBrackets) return; if (hasIdentifierToTheRight(document, offset + length)) return; // fall through case '\'': if (event.character == '\'') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } // fall through case '"': if (event.character == '"') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } try { ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset); if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset) return; if (!validateEditorInputState()) return; final char character= event.character; final char closingCharacter= getPeerCharacter(character); final StringBuffer buffer= new StringBuffer(); buffer.append(character); buffer.append(closingCharacter); document.replace(offset, length, buffer.toString()); BracketLevel level= new BracketLevel(); fBracketLevelStack.push(level); LinkedPositionGroup group= new LinkedPositionGroup(); group.createPosition(document, offset + 1, 0); LinkedEnvironment env= new LinkedEnvironment(); env.addLinkedListener(this); env.addGroup(group); env.forceInstall(); level.fOffset= offset; level.fLength= 2; // set up position tracking for our magic peers if (fBracketLevelStack.size() == 1) { document.addPositionCategory(CATEGORY); document.addPositionUpdater(fUpdater); } level.fFirstPosition= new Position(offset, 1); level.fSecondPosition= new Position(offset + 1, 1); document.addPosition(CATEGORY, level.fFirstPosition); document.addPosition(CATEGORY, level.fSecondPosition); level.fEditor= new LinkedUIControl(env, sourceViewer); level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack)); level.fEditor.setExitPosition(sourceViewer, offset + 2, 0, Integer.MAX_VALUE); level.fEditor.setCyclingMode(LinkedUIControl.CYCLE_NEVER); level.fEditor.enter(); IRegion newSelection= level.fEditor.getSelectedRegion(); sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit= false; } catch (BadLocationException e) { JavaPlugin.log(e); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); } break; } } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void left(LinkedEnvironment environment, int flags) { final BracketLevel level= (BracketLevel) fBracketLevelStack.pop(); if (flags != ILinkedListener.EXTERNAL_MODIFICATION) return; // remove brackets final ISourceViewer sourceViewer= getSourceViewer(); final IDocument document= sourceViewer.getDocument(); if (document instanceof IDocumentExtension) { IDocumentExtension extension= (IDocumentExtension) document; extension.registerPostNotificationReplace(null, new IDocumentExtension.IReplace() { public void perform(IDocument d, IDocumentListener owner) { if ((level.fFirstPosition.isDeleted || level.fFirstPosition.length == 0) && !level.fSecondPosition.isDeleted && level.fSecondPosition.offset == level.fFirstPosition.offset) { try { document.replace(level.fSecondPosition.offset, level.fSecondPosition.length, null); } catch (BadLocationException e) { } } if (fBracketLevelStack.size() == 0) { document.removePositionUpdater(fUpdater); try { document.removePositionCategory(CATEGORY); } catch (BadPositionCategoryException e) { } } } }); } } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void suspend(LinkedEnvironment environment) { } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void resume(LinkedEnvironment environment, int flags) { } } /** * 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(); /** The remembered selection end. */ private RememberedOffset fEndOffset= new RememberedOffset(); /** * Remember current selection. */ public void remember() { IRegion selection= getSignedSelection(getSourceViewer()); int startOffset= selection.getOffset(); int endOffset= startOffset + selection.getLength(); fStartOffset.setOffset(startOffset); fEndOffset.setOffset(endOffset); } /** * Restore remembered selection. */ public void restore() { try { int startOffset= fStartOffset.getOffset(); int endOffset= fEndOffset.getOffset(); if (startOffset == -1) startOffset= endOffset; // fallback to carret offset if (endOffset == -1) endOffset= startOffset; // fallback to other offset 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(startOffset, endOffset - startOffset)) selectAndReveal(startOffset, endOffset - startOffset); } 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; } } /** * 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; /** Remembered column for the given offset*/ private int fColumn; /** 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 JavaPlugin.log(e); clear(); } catch (JavaModelException e) { // should not happen JavaPlugin.log(e.getStatus()); clear(); } } /** * Return offset recomputed from stored visual properties. * * @return Offset in the document */ public int getOffset() { try { IJavaElement newElement= getElement(); 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; 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; if (!containsOffset(newElement, offset) && (offset == 0 || !containsOffset(newElement, offset - 1))) return -1; return offset; } catch (BadLocationException e) { // should not happen JavaPlugin.log(e); return -1; } catch (JavaModelException e) { // should not happen JavaPlugin.log(e.getStatus()); return -1; } } /** * Return Java element recomputed from stored visual properties. * * @return Java element */ public IJavaElement getElement() { if (fElement == null) return null; return findElement(fElement); } /** * Clears the stored position */ public void clear() { fLine= -1; fColumn= -1; fElement= null; fElementLine= -1; } /** * Does the given Java element contain the given offset? * @param element Java element * @param offset Offset * @return <code>true</code> iff the Java element contains the offset */ private boolean containsOffset(IJavaElement element, int offset) { int elementOffset= getOffset(element); int elementLength= getLength(element); return (elementOffset > -1 && elementLength > -1) ? (offset >= elementOffset && offset < elementOffset + elementLength) : false; } /** * Returns the offset of the given Java element. * * @param element Java element * @return Offset of the given Java element */ private int getOffset(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; } /** * 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; } /** * 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= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { synchronized (unit) { unit.reconcile(false, null); } IJavaElement[] findings= unit.findElements(element); if (findings != null && findings.length > 0) return findings[0]; } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } } /** Preference key for code formatter tab size */ private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; /** Preference key for inserting spaces rather than tabs */ private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS; /** Preference key for automatically closing strings */ private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS; /** Preference key for automatically closing brackets and parenthesis */ private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS; /** The editor's save policy */ protected ISavePolicy fSavePolicy; /** Listener to annotation model changes that updates the error tick in the tab image */ private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; /** The editor's tab converter */ private TabConverter fTabConverter; /** * The remembered selection. * @since 3.0 */ private RememberedSelection fRememberedSelection= new RememberedSelection(); /** The bracket inserter. */ private BracketInserter fBracketInserter= new BracketInserter(); /** The standard action groups added to the menu */ private GenerateActionGroup fGenerateActionGroup; private CompositeActionGroup fContextMenuGroup; /** * Creates a new compilation unit editor. */ public CompilationUnitEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider()); setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$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= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.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(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.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(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.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(JavaEditorMessages.getResourceBundle(), "ContentAssistCompletePrefix.", this, CONTENTASSIST_COMPLETE_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.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(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT); setAction("Comment", action); //$NON-NLS-1$ markAsStateDependentAction("Comment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT); setAction("Uncomment", action); //$NON-NLS-1$ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); action= new ToggleCommentAction(JavaEditorMessages.getResourceBundle(), "ToggleComment.", this, getSourceViewerConfiguration().getDefaultPrefixes(getSourceViewer(), "")); //$NON-NLS-1$ //$NON-NLS-2$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.TOGGLE_COMMENT); setAction("ToggleComment", action); //$NON-NLS-1$ markAsStateDependentAction("ToggleComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.TOGGLE_COMMENT_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT); setAction("Format", action); //$NON-NLS-1$ markAsStateDependentAction("Format", true); //$NON-NLS-1$ markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); action= new AddBlockCommentAction(JavaEditorMessages.getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_BLOCK_COMMENT); setAction("AddBlockComment", action); //$NON-NLS-1$ markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); action= new RemoveBlockCommentAction(JavaEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); setAction("RemoveBlockComment", action); //$NON-NLS-1$ markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, false); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.INDENT); setAction("Indent", action); //$NON-NLS-1$ markAsStateDependentAction("Indent", true); //$NON-NLS-1$ markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); action= new IndentAction(JavaEditorMessages.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 (getNewPreferenceStore().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 <code>reconcile</code> * is <code>true</code> the editor's input element is reconciled in advance. If it is * <code>false</code> this method only returns a result if the editor's input element * does not need to be reconciled. * * @param offset the offset included by the retrieved element * @param reconcile <code>true</code> if working copy should be reconciled */ protected IJavaElement getElementAt(int offset, boolean reconcile) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(false, null); } return unit.getElementAt(offset); } else if (unit.isConsistent()) return unit.getElementAt(offset); } catch (JavaModelException x) { if (!x.isDoesNotExist()) JavaPlugin.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) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } return null; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement() */ protected IJavaElement getInputJavaElement() { return JavaPlugin.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= JavaPlugin.getDefault().getWorkingCopyManager(); page.setInput(manager.getWorkingCopy(input)); } } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor) */ protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p; cp.setSavePolicy(fSavePolicy); } try { super.performSave(overwrite, progressMonitor); } finally { if (p instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p; cp.setSavePolicy(null); } } } /* * @see AbstractTextEditor#doSaveAs */ public void doSaveAs() { if (askIfNonWorkbenchEncodingIsOk()) { super.doSaveAs(); } } /* * @see AbstractTextEditor#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) { // editor has been closed return; } if (!askIfNonWorkbenchEncodingIsOk()) { progressMonitor.setCanceled(true); return; } if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ Shell shell= getSite().getShell(); MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { setStatusLineErrorMessage(null); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSave(false, progressMonitor); } } else performSave(false, progressMonitor); } } /** * Asks the user if it is ok to store in non-workbench encoding. * @return <true> 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= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ String msg; if (input != null) msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$ else msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$ return MessageDialog.openQuestion(shell, title, msg); } } return true; } public boolean isSaveAsAllowed() { return true; } /** * The compilation unit editor implementation of this <code>AbstractTextEditor</code> * 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 */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog= new SaveAsDialog(shell); IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; if (original != null) dialog.setOriginalFile(original); dialog.create(); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Window.CANCEL) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IPath filePath= dialog.getResult(); if (filePath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } 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) { ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ } finally { provider.changed(newInput); if (success) setInput(newInput); } if (progressMonitor != null) progressMonitor.setCanceled(!success); } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); configureTabConverter(); } private void configureTabConverter() { if (fTabConverter != null) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cup= (ICompilationUnitDocumentProvider) provider; fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); } } } private int getTabSize() { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); return preferences.getInt(CODE_FORMATTER_TAB_SIZE); } 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(); } } 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; } } private boolean isTabConversionEnabled() { IPreferenceStore store= getNewPreferenceStore(); return store.getBoolean(SPACES_FOR_TABS); } public void dispose() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.dispose(); fJavaEditorErrorTickUpdater= null; } if (fActionGroups != null) { fActionGroups.dispose(); fActionGroups= null; } super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); if (isTabConversionEnabled()) startTabConversion(); IPreferenceStore preferenceStore= getNewPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); } private static char getEscapeCharacter(char character) { switch (character) { case '"': case '\'': return '\\'; default: return 0; } } private static char getPeerCharacter(char character) { switch (character) { case '(': return ')'; case ')': return '('; case '[': return ']'; case ']': return '['; case '"': return character; case '\'': return character; default: throw new IllegalArgumentException(); } } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CLOSE_BRACKETS.equals(p)) { fBracketInserter.setCloseBracketsEnabled(getNewPreferenceStore().getBoolean(p)); return; } if (CLOSE_STRINGS.equals(p)) { fBracketInserter.setCloseStringsEnabled(getNewPreferenceStore().getBoolean(p)); return; } if (SPACES_FOR_TABS.equals(p)) { if (isTabConversionEnabled()) startTabConversion(); else stopTabConversion(); return; } if (PreferenceConstants.EDITOR_SMART_TAB.equals(p)) { if (getNewPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ } else { removeActionActivationCode("IndentOnTab"); //$NON-NLS-1$ } } IContentAssistant c= asv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getNewPreferenceStore(), event); if (CODE_FORMATTER_TAB_SIZE.equals(p)) { asv.updateIndentationPrefixes(); if (fTabConverter != null) fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } } } finally { super.handlePreferenceStoreChanged(event); } } /* * @see org.eclipse.jdt.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) { return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles); } /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { synchronizeOutlinePageSelection(); } }); } } } protected void updateStateDependentActions() { super.updateStateDependentActions(); fGenerateActionGroup.editorStateChanged(); } /* * @see AbstractTextEditor#rememberSelection() */ protected void rememberSelection() { fRememberedSelection.remember(); } /* * @see AbstractTextEditor#restoreSelection() */ protected void restoreSelection() { fRememberedSelection.restore(); } /* * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { String oldExtension= ""; //$NON-NLS-1$ if (originalElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) originalElement).getFile(); if (file != null) { String ext= file.getFileExtension(); if (ext != null) oldExtension= ext; } } String newExtension= ""; //$NON-NLS-1$ if (movedElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) movedElement).getFile(); if (file != null) newExtension= file.getFileExtension(); } return oldExtension.equals(newExtension); } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#isPrefQuickDiffAlwaysOn() */ protected boolean isPrefQuickDiffAlwaysOn() { // reestablishes the behaviour from ExtendedTextEditor which was hacked by JavaEditor // to disable the change bar for the class file (attached source) java editor. IPreferenceStore store= getNewPreferenceStore(); return store.getBoolean(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); } }
50,971
Bug 50971 Extract temp: index out of bounds error [refactoring]
I20040129 Trying to extract a local from entries[i].getPluginId() caused an exception. private MultiStatus createMultiStatus() { MultiStatus status= new MultiStatus( JavaPlugin.getPluginId(), IStatus.ERROR, RefactoringMessages.getString ("UndoManagerAction.validation_failed"), //$NON-NLS-1$ null); RefactoringStatusEntry[] entries= fPreflightStatus.getEntries (); for (int i= 0; i < entries.length; i++) { status.merge(new Status( IStatus.ERROR, entries[i].getPluginId() != null ? entries [i].getPluginId() : JavaPlugin.getPluginId(), IStatus.ERROR, entries[i].getMessage(), null)); } return status; } Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.allArra ysEqual(ExtractTempRefactoring.java:647) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getLong estArrayPrefix(ExtractTempRefactoring.java:634) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.findDee pestCommonSuperNodePathForReplacedNodes(ExtractTempRefactoring.java:619) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getNode ToInsertTempDeclarationBefore(ExtractTempRefactoring.java:595) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createA ndInsertTempDeclaration(ExtractTempRefactoring.java:525) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createT empDeclarationEdit(ExtractTempRefactoring.java:515) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getAllE dits(ExtractTempRefactoring.java:500) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.checkIn put(ExtractTempRefactoring.java:368) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:64) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:99) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:166) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302)
resolved fixed
30a745b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T19:46:38Z
2004-01-30T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test78_in.java
50,971
Bug 50971 Extract temp: index out of bounds error [refactoring]
I20040129 Trying to extract a local from entries[i].getPluginId() caused an exception. private MultiStatus createMultiStatus() { MultiStatus status= new MultiStatus( JavaPlugin.getPluginId(), IStatus.ERROR, RefactoringMessages.getString ("UndoManagerAction.validation_failed"), //$NON-NLS-1$ null); RefactoringStatusEntry[] entries= fPreflightStatus.getEntries (); for (int i= 0; i < entries.length; i++) { status.merge(new Status( IStatus.ERROR, entries[i].getPluginId() != null ? entries [i].getPluginId() : JavaPlugin.getPluginId(), IStatus.ERROR, entries[i].getMessage(), null)); } return status; } Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.allArra ysEqual(ExtractTempRefactoring.java:647) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getLong estArrayPrefix(ExtractTempRefactoring.java:634) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.findDee pestCommonSuperNodePathForReplacedNodes(ExtractTempRefactoring.java:619) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getNode ToInsertTempDeclarationBefore(ExtractTempRefactoring.java:595) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createA ndInsertTempDeclaration(ExtractTempRefactoring.java:525) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createT empDeclarationEdit(ExtractTempRefactoring.java:515) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getAllE dits(ExtractTempRefactoring.java:500) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.checkIn put(ExtractTempRefactoring.java:368) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:64) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:99) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:166) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302)
resolved fixed
30a745b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T19:46:38Z
2004-01-30T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test78_out.java
50,971
Bug 50971 Extract temp: index out of bounds error [refactoring]
I20040129 Trying to extract a local from entries[i].getPluginId() caused an exception. private MultiStatus createMultiStatus() { MultiStatus status= new MultiStatus( JavaPlugin.getPluginId(), IStatus.ERROR, RefactoringMessages.getString ("UndoManagerAction.validation_failed"), //$NON-NLS-1$ null); RefactoringStatusEntry[] entries= fPreflightStatus.getEntries (); for (int i= 0; i < entries.length; i++) { status.merge(new Status( IStatus.ERROR, entries[i].getPluginId() != null ? entries [i].getPluginId() : JavaPlugin.getPluginId(), IStatus.ERROR, entries[i].getMessage(), null)); } return status; } Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.allArra ysEqual(ExtractTempRefactoring.java:647) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getLong estArrayPrefix(ExtractTempRefactoring.java:634) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.findDee pestCommonSuperNodePathForReplacedNodes(ExtractTempRefactoring.java:619) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getNode ToInsertTempDeclarationBefore(ExtractTempRefactoring.java:595) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createA ndInsertTempDeclaration(ExtractTempRefactoring.java:525) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createT empDeclarationEdit(ExtractTempRefactoring.java:515) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getAllE dits(ExtractTempRefactoring.java:500) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.checkIn put(ExtractTempRefactoring.java:368) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:64) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:99) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:166) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302)
resolved fixed
30a745b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T19:46:38Z
2004-01-30T16:26:40Z
org.eclipse.jdt.ui.tests.refactoring/test
50,971
Bug 50971 Extract temp: index out of bounds error [refactoring]
I20040129 Trying to extract a local from entries[i].getPluginId() caused an exception. private MultiStatus createMultiStatus() { MultiStatus status= new MultiStatus( JavaPlugin.getPluginId(), IStatus.ERROR, RefactoringMessages.getString ("UndoManagerAction.validation_failed"), //$NON-NLS-1$ null); RefactoringStatusEntry[] entries= fPreflightStatus.getEntries (); for (int i= 0; i < entries.length; i++) { status.merge(new Status( IStatus.ERROR, entries[i].getPluginId() != null ? entries [i].getPluginId() : JavaPlugin.getPluginId(), IStatus.ERROR, entries[i].getMessage(), null)); } return status; } Caused by: java.lang.ArrayIndexOutOfBoundsException: 10 at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.allArra ysEqual(ExtractTempRefactoring.java:647) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getLong estArrayPrefix(ExtractTempRefactoring.java:634) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.findDee pestCommonSuperNodePathForReplacedNodes(ExtractTempRefactoring.java:619) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getNode ToInsertTempDeclarationBefore(ExtractTempRefactoring.java:595) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createA ndInsertTempDeclaration(ExtractTempRefactoring.java:525) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.createT empDeclarationEdit(ExtractTempRefactoring.java:515) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.getAllE dits(ExtractTempRefactoring.java:500) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractTempRefactoring.checkIn put(ExtractTempRefactoring.java:368) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:64) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:99) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:166) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302)
resolved fixed
30a745b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2004-02-23T19:46:38Z
2004-01-30T16:26:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java