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
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
org.eclipse.jdt.ui/core
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InvocationAnalyzer.java
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
org.eclipse.jdt.ui/core
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceProvider.java
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
org.eclipse.jdt.ui/core
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/TargetProvider.java
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
org.eclipse.jdt.ui/core
25,501
Bug 25501 inline method: syntax errors after
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
resolved fixed
40e2847
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T14:31:05Z
2002-10-29T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
26,096
Bug 26096 inline method: incorrectly inling method that refers to 'this'
class A{ void m(C c){ c.m(this); } } class C{ void m(A a){ //method } } class Client{ void f(){ A a= null; C c= null; a.m(c); } } inlining A.m results in (in Client.f()): c.m(this); which does not compile
resolved fixed
58fd42e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T15:20:31Z
2002-11-13T15:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_in/TestThisExpression.java
26,096
Bug 26096 inline method: incorrectly inling method that refers to 'this'
class A{ void m(C c){ c.m(this); } } class C{ void m(A a){ //method } } class Client{ void f(){ A a= null; C c= null; a.m(c); } } inlining A.m results in (in Client.f()): c.m(this); which does not compile
resolved fixed
58fd42e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T15:20:31Z
2002-11-13T15:06:40Z
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/receiver_out/TestThisExpression.java
26,096
Bug 26096 inline method: incorrectly inling method that refers to 'this'
class A{ void m(C c){ c.m(this); } } class C{ void m(A a){ //method } } class Client{ void f(){ A a= null; C c= null; a.m(c); } } inlining A.m results in (in Client.f()): c.m(this); which does not compile
resolved fixed
58fd42e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T15:20:31Z
2002-11-13T15:06:40Z
org.eclipse.jdt.ui.tests.refactoring/test
26,096
Bug 26096 inline method: incorrectly inling method that refers to 'this'
class A{ void m(C c){ c.m(this); } } class C{ void m(A a){ //method } } class Client{ void f(){ A a= null; C c= null; a.m(c); } } inlining A.m results in (in Client.f()): c.m(this); which does not compile
resolved fixed
58fd42e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T15:20:31Z
2002-11-13T15:06:40Z
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
26,096
Bug 26096 inline method: incorrectly inling method that refers to 'this'
class A{ void m(C c){ c.m(this); } } class C{ void m(A a){ //method } } class Client{ void f(){ A a= null; C c= null; a.m(c); } } inlining A.m results in (in Client.f()): c.m(this); which does not compile
resolved fixed
58fd42e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T15:20:31Z
2002-11-13T15:06:40Z
org.eclipse.jdt.ui/core
26,096
Bug 26096 inline method: incorrectly inling method that refers to 'this'
class A{ void m(C c){ c.m(this); } } class C{ void m(A a){ //method } } class Client{ void f(){ A a= null; C c= null; a.m(c); } } inlining A.m results in (in Client.f()): c.m(this); which does not compile
resolved fixed
58fd42e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T15:20:31Z
2002-11-13T15:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceAnalyzer.java
30,706
Bug 30706 Problem with linked folders, filters and refactoring.
I am trying to use the refactoring support in an environment where the project source tree is accessed via links and some parts of the raw tree are filtered out. Specifically I am trying to rename a class and when the refactoring dialog comes up I select all the options which forces a preview. When I select the "preview" button, the system works for a moment, flashes up another dialog or message box which disappears before it can be seen and finally presents a dialog that states that an internal processing error has occurred and that details will be found in the log. When I look at the log below !SESSION Jan 31, 2003 07:56:09.772 -------------------------------------------- - java.version=1.4.1_01 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86 -data E:\CRYPTOAdminWorkspace-6.0 -showlocation -install file:E:/Eclipse- I20030129/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Jan 31, 2003 07:56:09.772 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:61) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 969] Release/com/cryptocard/HalfPint [in CRYPTOAdmin-6.0] does not exist. at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeRefactoring.checkI nput(RenameTypeRefactoring.java:389) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) ... 2 more we see that the system is complaining about Release/com/cryptocard/HalfPint. This is one of the directories that has been filtered out of the project. I am attaching the .project and .classpath files for the project as supporting material. Regards Jonathan Gossage
resolved fixed
a041704
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T18:26:26Z
2003-01-31T13:33:20Z
org.eclipse.jdt.ui/core
30,706
Bug 30706 Problem with linked folders, filters and refactoring.
I am trying to use the refactoring support in an environment where the project source tree is accessed via links and some parts of the raw tree are filtered out. Specifically I am trying to rename a class and when the refactoring dialog comes up I select all the options which forces a preview. When I select the "preview" button, the system works for a moment, flashes up another dialog or message box which disappears before it can be seen and finally presents a dialog that states that an internal processing error has occurred and that details will be found in the log. When I look at the log below !SESSION Jan 31, 2003 07:56:09.772 -------------------------------------------- - java.version=1.4.1_01 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86 -data E:\CRYPTOAdminWorkspace-6.0 -showlocation -install file:E:/Eclipse- I20030129/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Jan 31, 2003 07:56:09.772 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:61) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95) Caused by: Java Model Exception: Core Exception [code 969] Release/com/cryptocard/HalfPint [in CRYPTOAdmin-6.0] does not exist. at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeRefactoring.checkI nput(RenameTypeRefactoring.java:389) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) ... 2 more we see that the system is complaining about Release/com/cryptocard/HalfPint. This is one of the directories that has been filtered out of the project. I am attaching the .project and .classpath files for the project as supporting material. Regards Jonathan Gossage
resolved fixed
a041704
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T18:26:26Z
2003-01-31T13:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/TextMatchFinder.java
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InvocationAnalyzer.java
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/Invocations.java
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/TargetProvider.java
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui
24,914
Bug 24914 inline method - breaks code when inlining into overridden methods [refactoring]
I-20021016 linux-gtk: public class Boo { private static class A { void foo() { } } private static class B extends A { void foo() { super.foo(); } } } Issue 1: 1. select foo in "super.foo" 2. inline method 3. get a dialog saying "No method invocation or declaration selected." Issue 2: 1. select foo declration in class A 2. inline method 3. press finish 4. observe that the method foo() from A is gone, leaving class B with compile errors
resolved fixed
58b020e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T19:02:39Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringWizard.java
24,921
Bug 24921 inline method - breaks code when inlining methods with try catch blocks [refactoring]
I-20021016 linux-gtk: import java.io.IOException; public class Loo { void foo() throws IOException { try { throw new IOException(); } catch (IOException e) { } } void goo() { try { foo(); } catch (IOException e) { System.err.println(); } } } 1. select foo in goo 2. inline method 3. press finish 4. observe that two try catch blocks for IOException are produced with a compile error for unreachable catch block
resolved wontfix
3361652
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T20:09:13Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,921
Bug 24921 inline method - breaks code when inlining methods with try catch blocks [refactoring]
I-20021016 linux-gtk: import java.io.IOException; public class Loo { void foo() throws IOException { try { throw new IOException(); } catch (IOException e) { } } void goo() { try { foo(); } catch (IOException e) { System.err.println(); } } } 1. select foo in goo 2. inline method 3. press finish 4. observe that two try catch blocks for IOException are produced with a compile error for unreachable catch block
resolved wontfix
3361652
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T20:09:13Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/base/RefactoringStatusCodes.java
24,921
Bug 24921 inline method - breaks code when inlining methods with try catch blocks [refactoring]
I-20021016 linux-gtk: import java.io.IOException; public class Loo { void foo() throws IOException { try { throw new IOException(); } catch (IOException e) { } } void goo() { try { foo(); } catch (IOException e) { System.err.println(); } } } 1. select foo in goo 2. inline method 3. press finish 4. observe that two try catch blocks for IOException are produced with a compile error for unreachable catch block
resolved wontfix
3361652
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T20:09:13Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/core
24,921
Bug 24921 inline method - breaks code when inlining methods with try catch blocks [refactoring]
I-20021016 linux-gtk: import java.io.IOException; public class Loo { void foo() throws IOException { try { throw new IOException(); } catch (IOException e) { } } void goo() { try { foo(); } catch (IOException e) { System.err.println(); } } } 1. select foo in goo 2. inline method 3. press finish 4. observe that two try catch blocks for IOException are produced with a compile error for unreachable catch block
resolved wontfix
3361652
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-13T20:09:13Z
2002-10-17T10:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InvocationAnalyzer.java
27,935
Bug 27935 [Markers] MarkerHelpRegistry.hasResolutions is a performance problem
MarkerHelpRegistry.hasResolutions is used to get the enablement state for the 'quick fix' menu entry in the task view as well as to evaluate if a light bulb needs to be shown in the (Java) editor. The current implementation of MarkerHelpRegistry.hasResolutions is MarkerHelpRegistry.getResolutions().length; creating all proposals, which can be very expensive as it involves evaluating the problem context and returning the full and exact number of proposals. It would be better if the IMarkerResolutionGenerator would also offer a 'hasResolutions', so the implementor of the genenator can do a cheap guess, and do the more expensive proposal creations only when the dialog is shown. We do the same thing with the quick fixes in the editor, where the light bulb shows up on all error types that are handles, even it is still possible that the exact evaluation will find out that for this particular scenario, no corrections can be offered. Supporting now also contributed MarkerResultions, the performance problem of MarkerHelpRegistry.hasResolutions will show up as more and more contributions are coming. The problem is already now showing up for the context menu of the task bar for Java errors, as for calculating the resolution an AST has to be built.
resolved fixed
af2a19d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T14:34:53Z
2002-12-09T13:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.IMarkerResolutionGenerator; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation; import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal; /** */ public class CorrectionMarkerResolutionGenerator implements IMarkerResolutionGenerator { public static class CorrectionMarkerResolution implements IMarkerResolution { private IEditorInput fEditorInput; private IJavaCompletionProposal fProposal; /** * Constructor for CorrectionMarkerResolution. */ public CorrectionMarkerResolution(IEditorInput editorInput, IJavaCompletionProposal proposal) { fEditorInput= editorInput; fProposal= proposal; } /* (non-Javadoc) * @see IMarkerResolution#getLabel() */ public String getLabel() { return fProposal.getDisplayString(); } /* (non-Javadoc) * @see IMarkerResolution#run(IMarker) */ public void run(IMarker marker) { IDocument doc= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(fEditorInput); if (doc != null) { fProposal.apply(doc); } } } private static final IMarkerResolution[] NO_RESOLUTIONS= new IMarkerResolution[0]; /** * Constructor for CorrectionMarkerResolutionGenerator. */ public CorrectionMarkerResolutionGenerator() { super(); } /* (non-Javadoc) * @see IMarkerResolutionGenerator#getResolutions(IMarker) */ public IMarkerResolution[] getResolutions(IMarker marker) { int id= marker.getAttribute(IJavaModelMarker.ID, -1); if (!JavaCorrectionProcessor.hasCorrections(id)) { return NO_RESOLUTIONS; } try { ICompilationUnit cu= getCompilationUnit(marker); if (cu != null && JavaModelUtil.isEditable(cu)) { IEditorInput input= EditorUtility.getEditorInput(cu); if (input != null) { // only works with element open in editor CorrectionContext context= findCorrectionContext(input, marker); if (context != null) { ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); int nProposals= proposals.size(); IMarkerResolution[] resolutions= new IMarkerResolution[nProposals]; for (int i= 0; i < nProposals; i++) { resolutions[i]= new CorrectionMarkerResolution(input, (IJavaCompletionProposal) proposals.get(i)); } return resolutions; } } } } catch (JavaModelException e) { JavaPlugin.log(e); } return new IMarkerResolution[0]; } private ICompilationUnit getCompilationUnit(IMarker marker) { IResource res= marker.getResource(); if (res instanceof IFile && res.isAccessible()) { return JavaCore.createCompilationUnitFrom((IFile) res); } return null; } private CorrectionContext findCorrectionContext(IEditorInput input, IMarker marker) throws JavaModelException { IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(input); if (model != null) { Iterator iter= model.getAnnotationIterator(); while (iter.hasNext()) { Object curr= iter.next(); if (curr instanceof JavaMarkerAnnotation) { JavaMarkerAnnotation annot= (JavaMarkerAnnotation) curr; if (marker.equals(annot.getMarker())) { Position pos= model.getPosition(annot); if (pos != null) { ICompilationUnit cu= getCompilationUnit(marker); return new CorrectionContext(JavaModelUtil.toWorkingCopy(cu), pos.getOffset(), pos.getLength(), annot.getId(), annot.getArguments()); } } } } } return null; } }
31,649
Bug 31649 Quick assist surround proposals need different label
20030211 All uix fix/assist proposals have a descriptive label 'Remove xx', 'Change to..' The surround template proposals should follow this rule as well. e.g. 'Surround with {0} template'
resolved fixed
aa5534c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:06:11Z
2003-02-12T11:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavaCorrectionProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.text.Collator; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMarkerHelpRegistry; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator; import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal; public class JavaCorrectionProcessor implements IContentAssistProcessor { private static class CorrectionsComparator implements Comparator { private static Collator fgCollator= Collator.getInstance(); public int compare(Object o1, Object o2) { if ((o1 instanceof IJavaCompletionProposal) && (o2 instanceof IJavaCompletionProposal)) { IJavaCompletionProposal e1= (IJavaCompletionProposal) o1; IJavaCompletionProposal e2= (IJavaCompletionProposal) o2; int del= e2.getRelevance() - e1.getRelevance(); if (del != 0) { return del; } return fgCollator.compare(e1.getDisplayString(), e1.getDisplayString()); } return fgCollator.compare(((ICompletionProposal) o1).getDisplayString(), ((ICompletionProposal) o1).getDisplayString()); } } private static ICorrectionProcessor[] fCodeManipulationProcessors= null; public static ICorrectionProcessor[] getCodeManipulationProcessors() { if (fCodeManipulationProcessors == null) { fCodeManipulationProcessors= new ICorrectionProcessor[] { new QuickFixProcessor(), new QuickAssistProcessor() }; } return fCodeManipulationProcessors; } public static boolean hasCorrections(int problemId) { return QuickFixProcessor.hasCorrections(problemId); } public static boolean hasCorrections(IJavaAnnotation annotation) { int problemId= annotation.getId(); if (problemId == -1) { if (annotation instanceof MarkerAnnotation) { return hasCorrections(((MarkerAnnotation) annotation).getMarker()); } return false; } else { return hasCorrections(problemId); } } public static boolean hasCorrections(IMarker marker) { if (marker == null || !marker.exists()) return false; try { if (marker.isSubtypeOf(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER)) { int problemId= marker.getAttribute(IJavaModelMarker.ID, -1); return problemId != -1 && hasCorrections(problemId); } else { IMarkerHelpRegistry registry= PlatformUI.getWorkbench().getMarkerHelpRegistry(); return registry != null && registry.hasResolutions(marker); } } catch (CoreException e) { JavaPlugin.log(e); return false; } } private IEditorPart fEditor; private QuickTemplateProcessor fQuickTemplateProcessor; /** * Constructor for JavaCorrectionProcessor. */ public JavaCorrectionProcessor(IEditorPart editor) { fEditor= editor; fQuickTemplateProcessor= new QuickTemplateProcessor(editor); } /* * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) */ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { if (areMultipleLinesSelected(viewer)){ ICompletionProposal[] templateProposals= fQuickTemplateProcessor.computeCompletionProposals(viewer, documentOffset); if (templateProposals != null && templateProposals.length > 0) return templateProposals; else return new ICompletionProposal[]{new NoCorrectionProposal(null, null)}; } ICompilationUnit cu= JavaUI.getWorkingCopyManager().getWorkingCopy(fEditor.getEditorInput()); IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput()); ArrayList proposals= new ArrayList(); if (model != null) { int length= viewer != null ? viewer.getSelectedRange().y : 0; processProblemAnnotations(cu, model, documentOffset, length, proposals); } if (proposals.isEmpty()) { proposals.add(new NoCorrectionProposal(null, null)); } ICompletionProposal[] res= (ICompletionProposal[]) proposals.toArray(new ICompletionProposal[proposals.size()]); Arrays.sort(res, new CorrectionsComparator()); return res; } private boolean isAtPosition(int offset, Position pos) { return (pos != null) && (offset >= pos.getOffset() && offset <= (pos.getOffset() + pos.getLength())); } private void processProblemAnnotations(ICompilationUnit cu, IAnnotationModel model, int offset, int length, ArrayList proposals) { CorrectionContext context= new CorrectionContext(cu); boolean noProbemFound= true; HashSet idsProcessed= new HashSet(); Iterator iter= new JavaAnnotationIterator(model, true); while (iter.hasNext()) { IJavaAnnotation annot= (IJavaAnnotation) iter.next(); Position pos= model.getPosition((Annotation) annot); if (isAtPosition(offset, pos)) { int problemId= annot.getId(); if (problemId != -1) { if (idsProcessed.add(new Integer(problemId))) { // collect only once per problem id context.initialize(pos.getOffset(), pos.getLength(), annot.getId(), annot.getArguments()); collectCorrections(context, proposals); if (proposals.isEmpty()) { //proposals.add(new NoCorrectionProposal(pp, annot.getMessage())); } } noProbemFound= false; } else { if (annot instanceof MarkerAnnotation) { IMarker marker= ((MarkerAnnotation) annot).getMarker(); IMarkerResolution[] res= PlatformUI.getWorkbench().getMarkerHelpRegistry().getResolutions(marker); if (res.length > 0) { noProbemFound= false; for (int i= 0; i < res.length; i++) { proposals.add(new MarkerResolutionProposal(res[i], marker)); } } } } } } if (noProbemFound) { context.initialize(offset, length, 0, null); collectCorrections(context, proposals); } } public static void collectCorrections(CorrectionContext context, ArrayList proposals) { ICorrectionProcessor[] processors= getCodeManipulationProcessors(); for (int i= 0; i < processors.length; i++) { try { processors[i].process(context, proposals); } catch (CoreException e) { JavaPlugin.log(e); } } } /** * Returns <code>true</code> if one line is completely selected or if multiple lines are selected. * Being completely selected means that all characters except the new line characters are * selected. * * @return <code>true</code> if one or multiple lines are selected * @since 2.1 */ private boolean areMultipleLinesSelected(ITextViewer viewer) { if (viewer == null) return false; Point s= viewer.getSelectedRange(); if (s.y == 0) return false; try { IDocument document= viewer.getDocument(); int startLine= document.getLineOfOffset(s.x); int endLine= document.getLineOfOffset(s.x + s.y); IRegion line= document.getLineInformation(startLine); return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength()); } catch (BadLocationException x) { return false; } } /* * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) */ public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) { return null; } /* * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() */ public char[] getCompletionProposalAutoActivationCharacters() { return null; } /* * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() */ public char[] getContextInformationAutoActivationCharacters() { return null; } /* * @see IContentAssistProcessor#getContextInformationValidator() */ public IContextInformationValidator getContextInformationValidator() { return null; } /* * @see IContentAssistProcessor#getErrorMessage() */ public String getErrorMessage() { return null; } }
31,649
Bug 31649 Quick assist surround proposals need different label
20030211 All uix fix/assist proposals have a descriptive label 'Remove xx', 'Change to..' The surround template proposals should follow this rule as well. e.g. 'Surround with {0} template'
resolved fixed
aa5534c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:06:11Z
2003-02-12T11:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickTemplateProcessor.java
/********************************************************************** Copyright (c) 2000, 2003 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.io.IOException; import java.util.Arrays; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.internal.corext.template.ContextType; import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry; import org.eclipse.jdt.internal.corext.template.java.JavaContextType; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.JavaCodeReader; import org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComparator; import org.eclipse.jdt.internal.ui.text.template.TemplateEngine; import org.eclipse.jdt.internal.ui.text.template.TemplateProposal; /** * Quick template processor. */ public class QuickTemplateProcessor implements IContentAssistProcessor { private IEditorPart fEditor; private IWorkingCopyManager fManager; private JavaCompletionProposalComparator fComparator; private TemplateEngine fTemplateEngine; public QuickTemplateProcessor(IEditorPart editor) { fEditor= editor; fManager= JavaPlugin.getDefault().getWorkingCopyManager(); ContextType contextType= ContextTypeRegistry.getInstance().getContextType(JavaContextType.NAME); if (contextType != null) fTemplateEngine= new TemplateEngine(contextType); fComparator= new JavaCompletionProposalComparator(); } private boolean looksLikeMethod(JavaCodeReader reader) throws IOException { int curr= reader.read(); while (curr != JavaCodeReader.EOF && Character.isWhitespace((char) curr)) curr= reader.read(); if (curr == JavaCodeReader.EOF) return false; return Character.isJavaIdentifierPart((char) curr) || Character.isJavaIdentifierStart((char) curr); } private int guessContextInformationPosition(ITextViewer viewer, int offset) { int contextPosition= offset; IDocument document= viewer.getDocument(); try { JavaCodeReader reader= new JavaCodeReader(); reader.configureBackwardReader(document, offset, true, true); int nestingLevel= 0; int curr= reader.read(); while (curr != JavaCodeReader.EOF) { if (')' == (char) curr) ++ nestingLevel; else if ('(' == (char) curr) { -- nestingLevel; if (nestingLevel < 0) { int start= reader.getOffset(); if (looksLikeMethod(reader)) return start + 1; } } curr= reader.read(); } } catch (IOException e) { } return contextPosition; } /** * Order the given proposals. */ private ICompletionProposal[] order(ICompletionProposal[] proposals) { Arrays.sort(proposals, fComparator); return proposals; } public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) { int contextInformationPosition= guessContextInformationPosition(viewer, documentOffset); return internalComputeCompletionProposals(viewer, documentOffset, contextInformationPosition); } private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) { ICompilationUnit unit= fManager.getWorkingCopy(fEditor.getEditorInput()); TemplateProposal[] templateResults= null; if (fTemplateEngine != null) { try { fTemplateEngine.reset(); fTemplateEngine.complete(viewer, offset, unit); } catch (JavaModelException ex) { Shell shell= viewer.getTextWidget().getShell(); ErrorDialog.openError(shell, CorrectionMessages.getString("QuickTemplateProcessor.error.accessing.title"), CorrectionMessages.getString("QuickTemplateProcessor.error.accessing.message"), ex.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ } templateResults= fTemplateEngine.getResults(); } /* * Order here and not in result collector to make sure that the order * applies to all proposals and not just those of the compilation unit. */ return order(templateResults); } /* * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) */ public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) { return null; } /* * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() */ public char[] getCompletionProposalAutoActivationCharacters() { return null; } /* * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() */ public char[] getContextInformationAutoActivationCharacters() { return null; } /* * @see IContentAssistProcessor#getContextInformationValidator() */ public IContextInformationValidator getContextInformationValidator() { return null; } /* * @see IContentAssistProcessor#getErrorMessage() */ public String getErrorMessage() { return null; } }
31,649
Bug 31649 Quick assist surround proposals need different label
20030211 All uix fix/assist proposals have a descriptive label 'Remove xx', 'Change to..' The surround template proposals should follow this rule as well. e.g. 'Surround with {0} template'
resolved fixed
aa5534c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:06:11Z
2003-02-12T11:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProcessor.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.List; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationExtension; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.core.ICompilationUnit; 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.internal.corext.template.ContextType; import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.text.JavaCodeReader; import org.eclipse.jdt.internal.ui.text.template.TemplateEngine; import org.eclipse.jdt.internal.ui.text.template.TemplateProposal; /** * Java completion processor. */ public class JavaCompletionProcessor implements IContentAssistProcessor { private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension { private final IContextInformation fContextInformation; private int fPosition; public ContextInformationWrapper(IContextInformation contextInformation) { fContextInformation= contextInformation; } /* * @see IContextInformation#getContextDisplayString() */ public String getContextDisplayString() { return fContextInformation.getContextDisplayString(); } /* * @see IContextInformation#getImage() */ public Image getImage() { return fContextInformation.getImage(); } /* * @see IContextInformation#getInformationDisplayString() */ public String getInformationDisplayString() { return fContextInformation.getInformationDisplayString(); } /* * @see IContextInformationExtension#getContextInformationPosition() */ public int getContextInformationPosition() { return fPosition; } public void setContextInformationPosition(int position) { fPosition= position; } }; private final static String VISIBILITY= JavaCore.CODEASSIST_VISIBILITY_CHECK; private final static String ENABLED= "enabled"; //$NON-NLS-1$ private final static String DISABLED= "disabled"; //$NON-NLS-1$ protected IWorkingCopyManager fManager; private IEditorPart fEditor; private ResultCollector fCollector; private IContextInformationValidator fValidator; private char[] fProposalAutoActivationSet; private JavaCompletionProposalComparator fComparator; private boolean fAllowAddImports; private TemplateEngine fTemplateEngine; private ExperimentalResultCollector fExperimentalCollector; private int fNumberOfComputedResults= 0; public JavaCompletionProcessor(IEditorPart editor) { fEditor= editor; fCollector= new ResultCollector(); fManager= JavaPlugin.getDefault().getWorkingCopyManager(); ContextType contextType= ContextTypeRegistry.getInstance().getContextType("java"); //$NON-NLS-1$ if (contextType != null) fTemplateEngine= new TemplateEngine(contextType); fExperimentalCollector= new ExperimentalResultCollector(); fAllowAddImports= true; fComparator= new JavaCompletionProposalComparator(); } /** * Sets this processor's set of characters triggering the activation of the * completion proposal computation. * * @param activationSet the activation set */ public void setCompletionProposalAutoActivationCharacters(char[] activationSet) { fProposalAutoActivationSet= activationSet; } /** * Tells this processor to restrict its proposal to those element * visible in the actual invocation context. * * @param restrict <code>true</code> if proposals should be restricted */ public void restrictProposalsToVisibility(boolean restrict) { Hashtable options= JavaCore.getOptions(); Object value= options.get(VISIBILITY); if (value instanceof String) { String newValue= restrict ? ENABLED : DISABLED; if ( !newValue.equals((String) value)) { options.put(VISIBILITY, newValue); JavaCore.setOptions(options); } } } /** * Tells this processor to order the proposals alphabetically. * * @param order <code>true</code> if proposals should be ordered. */ public void orderProposalsAlphabetically(boolean order) { fComparator.setOrderAlphabetically(order); } /** * Tells this processor to restrict is proposals to those * starting with matching cases. * * @param restrict <code>true</code> if proposals should be restricted */ public void restrictProposalsToMatchingCases(boolean restrict) { // not yet supported } /** * Tells this processor to add import statement for proposals that have * a fully qualified type name * * @param restrict <code>true</code> if import can be added */ public void allowAddingImports(boolean allowAddingImports) { fAllowAddImports= allowAddingImports; } /** * @see IContentAssistProcessor#getErrorMessage() */ public String getErrorMessage() { if (fNumberOfComputedResults == 0) return JavaUIMessages.getString("JavaEditor.codeassist.noCompletions"); //$NON-NLS-1$ if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)) { return fExperimentalCollector.getErrorMessage(); } else { return fCollector.getErrorMessage(); } } /** * @see IContentAssistProcessor#getContextInformationValidator() */ public IContextInformationValidator getContextInformationValidator() { if (fValidator == null) fValidator= new JavaParameterListValidator(); return fValidator; } /** * @see IContentAssistProcessor#getContextInformationAutoActivationCharacters() */ public char[] getContextInformationAutoActivationCharacters() { return null; } /** * @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters() */ public char[] getCompletionProposalAutoActivationCharacters() { return fProposalAutoActivationSet; } private boolean looksLikeMethod(JavaCodeReader reader) throws IOException { int curr= reader.read(); while (curr != JavaCodeReader.EOF && Character.isWhitespace((char) curr)) curr= reader.read(); if (curr == JavaCodeReader.EOF) return false; return Character.isJavaIdentifierPart((char) curr) || Character.isJavaIdentifierStart((char) curr); } private int guessContextInformationPosition(ITextViewer viewer, int offset) { int contextPosition= offset; IDocument document= viewer.getDocument(); try { JavaCodeReader reader= new JavaCodeReader(); reader.configureBackwardReader(document, offset, true, true); int nestingLevel= 0; int curr= reader.read(); while (curr != JavaCodeReader.EOF) { if (')' == (char) curr) ++ nestingLevel; else if ('(' == (char) curr) { -- nestingLevel; if (nestingLevel < 0) { int start= reader.getOffset(); if (looksLikeMethod(reader)) return start + 1; } } curr= reader.read(); } } catch (IOException e) { } return contextPosition; } private List addContextInformations(ITextViewer viewer, int offset) { ICompletionProposal[] proposals= internalComputeCompletionProposals(viewer, offset, -1); List result= new ArrayList(); for (int i= 0; i < proposals.length; i++) { IContextInformation contextInformation= proposals[i].getContextInformation(); if (contextInformation != null) { ContextInformationWrapper wrapper= new ContextInformationWrapper(contextInformation); wrapper.setContextInformationPosition(offset); result.add(wrapper); } } return result; } /** * @see IContentAssistProcessor#computeContextInformation(ITextViewer, int) */ public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) { int contextInformationPosition= guessContextInformationPosition(viewer, offset); List result= addContextInformations(viewer, contextInformationPosition); return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]); } /** * Order the given proposals. */ private ICompletionProposal[] order(ICompletionProposal[] proposals) { Arrays.sort(proposals, fComparator); return proposals; } /** * @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int) */ public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) { int contextInformationPosition= guessContextInformationPosition(viewer, offset); return internalComputeCompletionProposals(viewer, offset, contextInformationPosition); } private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) { ICompilationUnit unit= fManager.getWorkingCopy(fEditor.getEditorInput()); IJavaCompletionProposal[] results; ResultCollector collector; if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)) { collector= fExperimentalCollector; } else { collector= fCollector; } try { if (unit != null) { collector.setPreventEating(false); collector.reset(offset, contextOffset, unit.getJavaProject(), fAllowAddImports ? unit : null); collector.setViewer(viewer); Point selection= viewer.getSelectedRange(); if (selection.y > 0) collector.setReplacementLength(selection.y); unit.codeComplete(offset, collector); } } catch (JavaModelException x) { Shell shell= viewer.getTextWidget().getShell(); ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ } results= collector.getResults(); if (fTemplateEngine != null) { try { fTemplateEngine.reset(); fTemplateEngine.complete(viewer, offset, unit); } catch (JavaModelException x) { Shell shell= viewer.getTextWidget().getShell(); ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$ } TemplateProposal[] templateResults= fTemplateEngine.getResults(); // update relavance of template proposals that match with a keyword JavaCompletionProposal[] keyWordResults= collector.getKeywordCompletions(); for (int i= 0; i < keyWordResults.length; i++) { String keyword= keyWordResults[i].getReplacementString(); for (int k= 0; k < templateResults.length; k++) { TemplateProposal curr= templateResults[k]; if (keyword.equals(curr.getTemplateName())) { curr.setRelevance(keyWordResults[i].getRelevance()); } } } // concatenate arrays IJavaCompletionProposal[] total= new IJavaCompletionProposal[results.length + templateResults.length]; System.arraycopy(templateResults, 0, total, 0, templateResults.length); System.arraycopy(results, 0, total, templateResults.length, results.length); results= total; } fNumberOfComputedResults= (results == null ? 0 : results.length); /* * Order here and not in result collector to make sure that the order * applies to all proposals and not just those of the compilation unit. */ return order(results); } }
31,649
Bug 31649 Quick assist surround proposals need different label
20030211 All uix fix/assist proposals have a descriptive label 'Remove xx', 'Change to..' The surround template proposals should follow this rule as well. e.g. 'Surround with {0} template'
resolved fixed
aa5534c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:06:11Z
2003-02-12T11:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/template/TemplateProposal.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.text.template; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; 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.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateBuffer; import org.eclipse.jdt.internal.corext.template.TemplateContext; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplatePosition; import org.eclipse.jdt.internal.corext.template.java.GlobalVariables; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * A template proposal. */ public class TemplateProposal implements IJavaCompletionProposal { private final Template fTemplate; private final TemplateContext fContext; private final ITextViewer fViewer; private final Image fImage; private final IRegion fRegion; private int fRelevance; private TemplateBuffer fTemplateBuffer; private IRegion fSelectedRegion; // initialized by apply() /** * Creates a template proposal with a template and its context. * @param template the template * @param context the context in which the template was requested. * @param image the icon of the proposal. */ public TemplateProposal(Template template, TemplateContext context, IRegion region, ITextViewer viewer, Image image) { Assert.isNotNull(template); Assert.isNotNull(context); Assert.isNotNull(region); Assert.isNotNull(viewer); fTemplate= template; fContext= context; fViewer= viewer; fImage= image; fRegion= region; if (context instanceof JavaContext) { switch (((JavaContext) context).getCharacterBeforeStart()) { // high relevance after whitespace case ' ': case '\r': case '\n': case '\t': fRelevance= 90; break; default: fRelevance= 0; } } else { fRelevance= 90; } } /* * @see ICompletionProposal#apply(IDocument) */ public void apply(IDocument document) { try { Position position= new Position(fRegion.getOffset(), fRegion.getLength()); final String category= "__template_position_" + System.currentTimeMillis(); //$NON-NLS-1$ IPositionUpdater updater= new DefaultPositionUpdater(category); document.addPositionCategory(category); document.addPositionUpdater(updater); document.addPosition(position); fContext.setReadOnly(false); fTemplateBuffer= fContext.evaluate(fTemplate); document.removePosition(position); document.removePositionUpdater(updater); document.removePositionCategory(category); int start= position.getOffset(); int end= position.getOffset() + position.getLength(); // insert template string String templateString= fTemplateBuffer.getString(); document.replace(start, end - start, templateString); // translate positions LinkedPositionManager manager= new LinkedPositionManager(document); TemplatePosition[] variables= fTemplateBuffer.getVariables(); for (int i= 0; i != variables.length; i++) { TemplatePosition variable= variables[i]; if (variable.isResolved()) continue; int[] offsets= variable.getOffsets(); int length= variable.getLength(); for (int j= 0; j != offsets.length; j++) manager.addPosition(offsets[j] + start, length); } LinkedPositionUI editor= new LinkedPositionUI(fViewer, manager); editor.setFinalCaretOffset(getCaretOffset(fTemplateBuffer) + start); editor.enter(); fSelectedRegion= editor.getSelectedRegion(); } catch (BadLocationException e) { JavaPlugin.log(e); openErrorDialog(e); fSelectedRegion= fRegion; } catch (BadPositionCategoryException e) { JavaPlugin.log(e); openErrorDialog(e); fSelectedRegion= fRegion; } catch (CoreException e) { handleException(e); fSelectedRegion= fRegion; } } private int getCaretOffset(TemplateBuffer buffer) { TemplatePosition[] variables= buffer.getVariables(); for (int i= 0; i != variables.length; i++) { TemplatePosition variable= variables[i]; if (variable.getName().equals(GlobalVariables.Cursor.NAME)) return variable.getOffsets()[0]; } return buffer.getString().length(); } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { try { fContext.setReadOnly(true); fTemplateBuffer= fContext.evaluate(fTemplate); return textToHTML(fTemplateBuffer.getString()); } catch (CoreException e) { handleException(e); return null; } } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { return fTemplate.getName() + TemplateMessages.getString("TemplateProposal.delimiter") + fTemplate.getDescription(); // $NON-NLS-1$ //$NON-NLS-1$ } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return fImage; } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return null; } private static String textToHTML(String string) { StringBuffer buffer= new StringBuffer(string.length()); buffer.append("<pre>"); //$NON-NLS-1$ for (int i= 0; i != string.length(); i++) { char ch= string.charAt(i); switch (ch) { case '&': buffer.append("&amp;"); //$NON-NLS-1$ break; case '<': buffer.append("&lt;"); //$NON-NLS-1$ break; case '>': buffer.append("&gt;"); //$NON-NLS-1$ break; case '\t': buffer.append(" "); //$NON-NLS-1$ break; case '\n': buffer.append("<br>"); //$NON-NLS-1$ break; default: buffer.append(ch); break; } } buffer.append("</pre>"); //$NON-NLS-1$ return buffer.toString(); } private void openErrorDialog(Exception e) { Shell shell= fViewer.getTextWidget().getShell(); MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ } private void handleException(CoreException e) { Shell shell= fViewer.getTextWidget().getShell(); ExceptionHandler.handle(e, shell, TemplateMessages.getString("TemplateEvaluator.error.title"), null); //$NON-NLS-1$ } /* * @see IJavaCompletionProposal#getRelevance() */ public int getRelevance() { return fRelevance; } public void setRelevance(int relevance) { fRelevance= relevance; } public String getTemplateName() { return fTemplate.getName(); } }
26,035
Bug 26035 Local history uses wrong character encoding
i set the windows->preferences->editors->TextFileEncoding to GBK it a Chinese charactor set.and then i wrote some Chinese in the println method just as System.out.println("2UEU"); after some modify,i replace this code back from Local History.a mistake appeared.it left a mess in the println sentence.the same mistake appear in WebSphere Application Developer 5.0
resolved fixed
2729322
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:10:21Z
2002-11-12T14:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaCompareUtilities.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.io.*; import java.net.*; import java.util.*; import org.eclipse.swt.graphics.Image; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.util.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.core.JavaElement; import org.eclipse.jdt.internal.ui.*; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.ui.text.JavaTextTools; class JavaCompareUtilities { static int getTabSize() { String string= (String) JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_SIZE); try { int i= Integer.parseInt(string); if (i >= 0) { return i; } } catch (NumberFormatException e) { } return 4; } static String getString(ResourceBundle bundle, String key, String dfltValue) { if (bundle != null) { try { return bundle.getString(key); } catch (MissingResourceException x) { } } return dfltValue; } static String getString(ResourceBundle bundle, String key) { return getString(bundle, key, key); } static int getInteger(ResourceBundle bundle, String key, int dfltValue) { if (bundle != null) { try { String s= bundle.getString(key); if (s != null) return Integer.parseInt(s); } catch (NumberFormatException x) { } catch (MissingResourceException x) { } } return dfltValue; } static ImageDescriptor getImageDescriptor(int type) { switch (type) { case IMember.INITIALIZER: case IMember.METHOD: return getImageDescriptor("obj16/compare_method.gif"); //$NON-NLS-1$ case IMember.FIELD: return getImageDescriptor("obj16/compare_field.gif"); //$NON-NLS-1$ case IMember.PACKAGE_DECLARATION: return JavaPluginImages.DESC_OBJS_PACKDECL; case IMember.IMPORT_DECLARATION: return JavaPluginImages.DESC_OBJS_IMPDECL; case IMember.IMPORT_CONTAINER: return JavaPluginImages.DESC_OBJS_IMPCONT; case IMember.COMPILATION_UNIT: return JavaPluginImages.DESC_OBJS_CUNIT; } return ImageDescriptor.getMissingImageDescriptor(); } static ImageDescriptor getTypeImageDescriptor(boolean isClass) { if (isClass) return JavaPluginImages.DESC_OBJS_CLASS; return JavaPluginImages.DESC_OBJS_INTERFACE; } static ImageDescriptor getImageDescriptor(IMember element) { int t= element.getElementType(); if (t == IMember.TYPE) { IType type= (IType) element; try { return getTypeImageDescriptor(type.isClass()); } catch (CoreException e) { JavaPlugin.log(e); return JavaPluginImages.DESC_OBJS_GHOST; } } return getImageDescriptor(t); } /** * Returns a name for the given Java element that uses the same conventions * as the JavaNode name of a corresponding element. */ static String getJavaElementID(IJavaElement je) { if (je instanceof IMember && ((IMember)je).isBinary()) return null; StringBuffer sb= new StringBuffer(); switch (je.getElementType()) { case JavaElement.COMPILATION_UNIT: sb.append(JavaElement.JEM_COMPILATIONUNIT); break; case JavaElement.TYPE: sb.append(JavaElement.JEM_TYPE); sb.append(je.getElementName()); break; case JavaElement.FIELD: sb.append(JavaElement.JEM_FIELD); sb.append(je.getElementName()); break; case JavaElement.METHOD: sb.append(JavaElement.JEM_METHOD); sb.append(JavaElementLabels.getElementLabel(je, JavaElementLabels.M_PARAMETER_TYPES)); break; case JavaElement.INITIALIZER: String id= je.getHandleIdentifier(); int pos= id.lastIndexOf(JavaElement.JEM_INITIALIZER); if (pos >= 0) sb.append(id.substring(pos)); break; case JavaElement.PACKAGE_DECLARATION: sb.append(JavaElement.JEM_PACKAGEDECLARATION); break; case JavaElement.IMPORT_CONTAINER: sb.append('<'); break; case JavaElement.IMPORT_DECLARATION: sb.append(JavaElement.JEM_IMPORTDECLARATION); sb.append(je.getElementName()); break; default: return null; } return sb.toString(); } /** * Returns a name which identifies the given typed name. * The type is encoded as a single character at the beginning of the string. */ static String buildID(int type, String name) { StringBuffer sb= new StringBuffer(); switch (type) { case JavaNode.CU: sb.append(JavaElement.JEM_COMPILATIONUNIT); break; case JavaNode.CLASS: case JavaNode.INTERFACE: sb.append(JavaElement.JEM_TYPE); sb.append(name); break; case JavaNode.FIELD: sb.append(JavaElement.JEM_FIELD); sb.append(name); break; case JavaNode.CONSTRUCTOR: case JavaNode.METHOD: sb.append(JavaElement.JEM_METHOD); sb.append(name); break; case JavaNode.INIT: sb.append(JavaElement.JEM_INITIALIZER); sb.append(name); break; case JavaNode.PACKAGE: sb.append(JavaElement.JEM_PACKAGEDECLARATION); break; case JavaNode.IMPORT: sb.append(JavaElement.JEM_IMPORTDECLARATION); sb.append(name); break; case JavaNode.IMPORT_CONTAINER: sb.append('<'); break; default: Assert.isTrue(false); break; } return sb.toString(); } static ImageDescriptor getImageDescriptor(String relativePath) { JavaPlugin plugin= JavaPlugin.getDefault(); URL installURL= null; if (plugin != null) installURL= plugin.getDescriptor().getInstallURL(); if (installURL != null) { try { URL url= new URL(installURL, "icons/full/" + relativePath); //$NON-NLS-1$ return ImageDescriptor.createFromURL(url); } catch (MalformedURLException e) { Assert.isTrue(false); } } return null; } static Image getImage(IMember member) { ImageDescriptor id= getImageDescriptor(member); return id.createImage(); } static JavaTextTools getJavaTextTools() { JavaPlugin plugin= JavaPlugin.getDefault(); if (plugin != null) return plugin.getJavaTextTools(); return null; } static IDocumentPartitioner createJavaPartitioner() { JavaTextTools tools= getJavaTextTools(); if (tools != null) return tools.createDocumentPartitioner(); return null; } /** * Returns null if an error occurred. */ static String readString(InputStream is) { if (is == null) return null; BufferedReader reader= null; try { StringBuffer buffer= new StringBuffer(); char[] part= new char[2048]; int read= 0; reader= new BufferedReader(new InputStreamReader(is, ResourcesPlugin.getEncoding())); while ((read= reader.read(part)) != -1) buffer.append(part, 0, read); return buffer.toString(); } catch (IOException ex) { } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { JavaPlugin.log(ex); } } } return null; } /** * Breaks the given string into lines. */ static String[] readLines(InputStream is) { try { StringBuffer sb= new StringBuffer(); List list= new ArrayList(); while (true) { int c= is.read(); if (c == -1) break; sb.append((char)c); if (c == '\r') { // single CR or a CR followed by LF c= is.read(); if (c == -1) break; sb.append((char)c); if (c == '\n') { list.add(sb.toString()); sb= new StringBuffer(); } } else if (c == '\n') { // a single LF list.add(sb.toString()); sb= new StringBuffer(); } } if (sb.length() > 0) list.add(sb.toString()); return (String[]) list.toArray(new String[list.size()]); } catch (IOException ex) { return null; } finally { if (is != null) { try { is.close(); } catch (IOException ex) { } } } } }
26,035
Bug 26035 Local history uses wrong character encoding
i set the windows->preferences->editors->TextFileEncoding to GBK it a Chinese charactor set.and then i wrote some Chinese in the println method just as System.out.println("2UEU"); after some modify,i replace this code back from Local History.a mistake appeared.it left a mess in the println sentence.the same mistake appear in WebSphere Application Developer 5.0
resolved fixed
2729322
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:10:21Z
2002-11-12T14:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/JavaHistoryAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.io.*; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.action.*; import org.eclipse.jface.viewers.*; import org.eclipse.ui.IActionDelegate; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.core.resources.*; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.*; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider; import org.eclipse.compare.*; /** * Base class for the "Replace with local history" * and "Add from local history" actions. */ public abstract class JavaHistoryAction implements IActionDelegate { /** * Implements the IStreamContentAccessor and ITypedElement protocols * for a TextBuffer. */ class JavaTextBufferNode implements ITypedElement, IStreamContentAccessor { private TextBuffer fBuffer; private boolean fInEditor; JavaTextBufferNode(TextBuffer buffer, boolean inEditor) { fBuffer= buffer; fInEditor= inEditor; } public String getName() { if (fInEditor) return CompareMessages.getString("Editor_Buffer"); //$NON-NLS-1$ return CompareMessages.getString("Workspace_File"); //$NON-NLS-1$ } public String getType() { return "java"; //$NON-NLS-1$ } public Image getImage() { return null; } public InputStream getContents() { return new ByteArrayInputStream(fBuffer.getContent().getBytes()); } } private boolean fModifiesFile; private ISelection fSelection; JavaHistoryAction(boolean modifiesFile) { fModifiesFile= modifiesFile; } ISelection getSelection() { return fSelection; } protected IFile getFile(Object input) { // extract CU from input ICompilationUnit cu= null; if (input instanceof ICompilationUnit) cu= (ICompilationUnit) input; else if (input instanceof IMember) cu= ((IMember)input).getCompilationUnit(); if (cu == null || !cu.exists()) return null; // get to original CU if (cu.isWorkingCopy()) cu= (ICompilationUnit) cu.getOriginalElement(); // find underlying file IFile file= (IFile) cu.getResource(); if (file != null && file.exists()) return file; return null; } protected ITypedElement[] buildEditions(ITypedElement target, IFile file) { // setup array of editions IFileState[] states= null; // add available editions try { states= file.getHistory(null); } catch (CoreException ex) { JavaPlugin.log(ex); } int count= 1; if (states != null) count+= states.length; ITypedElement[] editions= new ITypedElement[count]; editions[0]= new ResourceNode(file); if (states != null) for (int i= 0; i < states.length; i++) editions[i+1]= new HistoryItem(target, states[i]); return editions; } /** * Tries to find the given element in a workingcopy. */ protected IJavaElement getWorkingCopy(IJavaElement input) { try { return EditorUtility.getWorkingCopy(input, true); } catch (JavaModelException ex) { } return null; } /** * Returns true if the given file is open in an editor. */ boolean beingEdited(IFile file) { CompilationUnitDocumentProvider dp= JavaPlugin.getDefault().getCompilationUnitDocumentProvider(); FileEditorInput input= new FileEditorInput(file); return dp.getDocument(input) != null; } /** * Returns an IMember or null. */ IMember getEditionElement(ISelection selection) { if (selection instanceof IStructuredSelection) { IStructuredSelection ss= (IStructuredSelection) selection; if (ss.size() == 1) { Object o= ss.getFirstElement(); if (o instanceof IMember) { IMember m= (IMember) o; if (m.exists() && !m.isBinary() && JavaStructureCreator.hasEdition(m)) return m; } } } return null; } protected boolean isEnabled(IFile file) { if (file == null) return false; return !(fModifiesFile && file.isReadOnly()); } protected boolean isEnabled(ISelection selection) { IMember m= getEditionElement(selection); if (m == null) return false; IFile file= getFile(m); if (!isEnabled(file)) return false; if (file != null && beingEdited(file)) return getWorkingCopy(m) != null; return true; } /** * Notifies this action delegate that the selection in the workbench has changed. * <p> * Implementers can use this opportunity to change the availability of the * action or to modify other presentation properties. * </p> * * @param action the action proxy that handles presentation portion of the action * @param selection the current selection in the workbench */ public void selectionChanged(IAction action, ISelection selection) { fSelection= selection; action.setEnabled(isEnabled(selection)); } }
31,384
Bug 31384 Deleting a Link deletes the content of the link result in loss of data
I20030206 - create a normal Java project - create a folder and link the folder to an existing workspace. Observe: the link is rendered as an empty package and a lot of ghost folders are rendered as well. - delete the link folder/package Observe: this also deletes folders from the source folder as well (the .metadata directory and sometimes projects as well), resulting in Loss of DATA. Note that the dialog that pops up states that only the link will be removed from the workspace.
resolved wontfix
575595f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:32:06Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/core
31,384
Bug 31384 Deleting a Link deletes the content of the link result in loss of data
I20030206 - create a normal Java project - create a folder and link the folder to an existing workspace. Observe: the link is rendered as an empty package and a lot of ghost folders are rendered as well. - delete the link folder/package Observe: this also deletes folders from the source folder as well (the .metadata directory and sometimes projects as well), resulting in Loss of DATA. Note that the dialog that pops up states that only the link will be removed from the workspace.
resolved wontfix
575595f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:32:06Z
2003-02-07T23:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/DeleteRefactoring.java
31,384
Bug 31384 Deleting a Link deletes the content of the link result in loss of data
I20030206 - create a normal Java project - create a folder and link the folder to an existing workspace. Observe: the link is rendered as an empty package and a lot of ghost folders are rendered as well. - delete the link folder/package Observe: this also deletes folders from the source folder as well (the .metadata directory and sometimes projects as well), resulting in Loss of DATA. Note that the dialog that pops up states that only the link will be removed from the workspace.
resolved wontfix
575595f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T16:32:06Z
2003-02-07T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/DeleteResourcesAction.java
package org.eclipse.jdt.internal.ui.reorg; import java.text.MessageFormat; import java.util.Iterator; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.MultiStatus; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.actions.DeleteResourceAction; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.actions.SelectionDispatchAction; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.refactoring.reorg.DeleteRefactoring; import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery; import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils; import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil; public class DeleteResourcesAction extends SelectionDispatchAction { protected DeleteResourcesAction(IWorkbenchSite site) { super(site); } /* * @see SelectionDispatchAction#run(IStructuredSelection) */ protected void run(IStructuredSelection selection) { if (ClipboardActionUtil.hasOnlyProjects(selection)){ deleteProjects(selection); return; } DeleteRefactoring refactoring= new DeleteRefactoring(selection.toList(), createRootManipulationQuery()); if (!confirmDelete(selection)) return; if (hasReadOnlyResources(selection) && !isOkToDeleteReadOnly()) return; try{ if (! confirmDeleteSourceFolderAsSubresource(selection)) return; MultiStatus status= ClipboardActionUtil.perform(refactoring); if (!status.isOK()) { JavaPlugin.log(status); ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), ReorgMessages.getString("DeleteResourceAction.delete"), ReorgMessages.getString("DeleteResourceAction.exception"), status); //$NON-NLS-1$ //$NON-NLS-2$ } } catch (CoreException e){ ExceptionHandler.handle(e, ReorgMessages.getString("DeleteResourceAction.delete"), ReorgMessages.getString("DeleteResourceAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$ return; } } private IPackageFragmentRootManipulationQuery createRootManipulationQuery(){ String messagePattern= ReorgMessages.getString("DeleteResourcesAction.referenced"); //$NON-NLS-1$ return new PackageFragmentRootManipulationQuery(getShell(), ReorgMessages.getString("DeleteResourcesAction.Delete"), messagePattern); //$NON-NLS-1$ } private static void deleteProjects(IStructuredSelection selection){ DeleteResourceAction action= new DeleteResourceAction(JavaPlugin.getActiveWorkbenchShell()); action.selectionChanged(selection); action.run(); } private static boolean isOkToDeleteReadOnly(){ String msg= ReorgMessages.getString("deleteAction.confirmReadOnly"); //$NON-NLS-1$ String title= ReorgMessages.getString("deleteAction.checkDeletion"); //$NON-NLS-1$ return MessageDialog.openQuestion( JavaPlugin.getActiveWorkbenchShell(), title, msg); } private static boolean hasReadOnlyResources(IStructuredSelection selection){ for (Iterator iter= selection.iterator(); iter.hasNext();){ if (ReorgUtils.shouldConfirmReadOnly(iter.next())) return true; } return false; } private static boolean confirmDeleteSourceFolderAsSubresource(IStructuredSelection selection) throws CoreException { if (! containsSourceFolderAsSubresource(selection)) return true; String title= ReorgMessages.getString("deleteAction.confirm.title"); //$NON-NLS-1$ String label= ReorgMessages.getString("DeleteResourcesAction.deleteAction.confirm.message"); //$NON-NLS-1$ return MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, label); } private static boolean containsSourceFolderAsSubresource(IStructuredSelection selection) throws CoreException{ for (Iterator iter= selection.iterator(); iter.hasNext();){ Object each= iter.next(); if (each instanceof IFolder && containsSourceFolder((IFolder)each)) return true; } return false; } private static boolean containsSourceFolder(IFolder folder) throws CoreException{ IResource[] subFolders= folder.members(); for (int i = 0; i < subFolders.length; i++) { if (! (subFolders[i] instanceof IFolder)) continue; IJavaElement element= JavaCore.create((IFolder)folder); if (element instanceof IPackageFragmentRoot) return true; if (element instanceof IPackageFragment) continue; if (containsSourceFolder((IFolder)subFolders[i])) return true; } return false; } /* * @see SelectionDispatchAction#selectionChanged(IStructuredSelection) */ protected void selectionChanged(IStructuredSelection selection) { if (selection.isEmpty()) setEnabled(false); else setEnabled(ClipboardActionUtil.canActivate(new DeleteRefactoring(selection.toList(), null))); } private static boolean confirmDelete(IStructuredSelection selection) { Assert.isTrue(ClipboardActionUtil.getSelectedProjects(selection).isEmpty()); String title= ReorgMessages.getString("deleteAction.confirm.title"); //$NON-NLS-1$ String label= createConfirmationString(selection); return MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, label); } private static String createConfirmationString(IStructuredSelection selection) { if (selection.size() == 1){ Object firstElement= selection.getFirstElement(); String pattern= createConfirmationStringForSingleElement(firstElement); return MessageFormat.format(pattern, new String[]{getName(firstElement)}); } else { String pattern= createConfirmationStringForMultipleElements(selection); return MessageFormat.format(pattern, new String[]{String.valueOf(selection.size())}); } } private static String createConfirmationStringForSingleElement(Object firstElement) { if (isLinkedResource(firstElement)) return ReorgMessages.getString("DeleteResourcesAction.sure_delete_linked_single"); //$NON-NLS-1$ else return ReorgMessages.getString("DeleteResourcesAction.sure_delete"); //$NON-NLS-1$ } private static String createConfirmationStringForMultipleElements(IStructuredSelection selection) { if (containsLinkedResources(selection)) return ReorgMessages.getString("DeleteResourcesAction.sure_delete_linked_multiple"); //$NON-NLS-1$ else return ReorgMessages.getString("DeleteResourcesAction.sure_delete_resources"); //$NON-NLS-1$ } private static boolean containsLinkedResources(IStructuredSelection selection) { for (Iterator iter= selection.iterator(); iter.hasNext();) { if (isLinkedResource(iter.next())) return true; } return false; } private static boolean isLinkedResource(Object element) { IResource resource= ResourceUtil.getResource(element); return (resource != null && resource.isLinked()); } private static String getName(Object element){ //need to render 1 case differently if (element instanceof IPackageFragment && ((IPackageFragment)element).isDefaultPackage()) return ReorgMessages.getString("DeleteResourcesAction.default_package"); //$NON-NLS-1$ else return ReorgUtils.getName(element); } }
31,634
Bug 31634 Quickfix should do a team checkout
2.1 M5 / clearcase / eclipse-ccase plugin 0.9.3 Quickfix says no corrections available for a read only file that is under source control (i.e. not checked out). Quickfix should propose the corrections and check the file out automatically to implement them.
resolved fixed
570190f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T17:12:22Z
2003-02-12T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierChangeCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; public class ModifierChangeCompletionProposal extends ASTRewriteCorrectionProposal { private IBinding fBinding; private ASTNode fNode; private boolean fIsInDifferentCU; private int fIncludedModifiers; private int fExcludedModifiers; public ModifierChangeCompletionProposal(String label, ICompilationUnit targetCU, IBinding binding, ASTNode node, int includedModifiers, int excludedModifiers, int relevance, Image image) { super(label, targetCU, null, relevance, image); fBinding= binding; fNode= node; fIncludedModifiers= includedModifiers; fExcludedModifiers= excludedModifiers; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode boundNode= astRoot.findDeclaringNode(fBinding); ASTNode declNode= null; if (boundNode != null) { fIsInDifferentCU= false; declNode= boundNode; } else { fIsInDifferentCU= true; CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true); declNode= newRoot.findDeclaringNode(fBinding.getKey()); } if (declNode != null) { ASTRewrite rewrite= new ASTRewrite(declNode.getParent()); AST ast= declNode.getAST(); if (declNode instanceof MethodDeclaration) { MethodDeclaration methodDecl= (MethodDeclaration) declNode; int newModifiers= (methodDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; MethodDeclaration modifiedNode= ast.newMethodDeclaration(); modifiedNode.setConstructor(methodDecl.isConstructor()); // no change modifiedNode.setExtraDimensions(methodDecl.getExtraDimensions()); // no change modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(methodDecl, modifiedNode); } else if (declNode instanceof VariableDeclarationFragment) { ASTNode parent= declNode.getParent(); if (parent instanceof FieldDeclaration) { FieldDeclaration fieldDecl= (FieldDeclaration) parent; int newModifiers= (fieldDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; FieldDeclaration modifiedNode= ast.newFieldDeclaration(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(fieldDecl, modifiedNode); } else if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent; int newModifiers= (varDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; VariableDeclarationStatement modifiedNode= ast.newVariableDeclarationStatement(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(varDecl, modifiedNode); } else if (parent instanceof VariableDeclarationExpression) { VariableDeclarationExpression varDecl= (VariableDeclarationExpression) parent; int newModifiers= (varDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; VariableDeclarationExpression modifiedNode= ast.newVariableDeclarationExpression(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(varDecl, modifiedNode); } } else if (declNode instanceof SingleVariableDeclaration) { SingleVariableDeclaration variableDeclaration= (SingleVariableDeclaration) declNode; int newModifiers= (variableDeclaration.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; SingleVariableDeclaration modifiedNode= ast.newSingleVariableDeclaration(); modifiedNode.setExtraDimensions(variableDeclaration.getExtraDimensions()); // no change modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(variableDeclaration, modifiedNode); } else if (declNode instanceof TypeDeclaration) { TypeDeclaration typeDecl= (TypeDeclaration) declNode; int newModifiers= (typeDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; TypeDeclaration modifiedNode= ast.newTypeDeclaration(); modifiedNode.setInterface(typeDecl.isInterface()); // no change modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(typeDecl, modifiedNode); } return rewrite; } return null; } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (fIsInDifferentCU) { change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(getCompilationUnit(), true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
31,634
Bug 31634 Quickfix should do a team checkout
2.1 M5 / clearcase / eclipse-ccase plugin 0.9.3 Quickfix says no corrections available for a read only file that is under source control (i.e. not checked out). Quickfix should propose the corrections and check the file out automatically to implement them.
resolved fixed
570190f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T17:12:22Z
2003-02-12T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPluginImages; /** */ public class ModifierCorrectionSubProcessor { public static final int TO_STATIC= 1; public static final int TO_VISIBLE= 2; public static final int TO_NON_PRIVATE= 3; public static final int TO_NON_STATIC= 4; public static void addNonAccessibleMemberProposal(ICorrectionContext context, List proposals, int kind) throws JavaModelException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } IBinding binding=null; switch (selectedNode.getNodeType()) { case ASTNode.SIMPLE_NAME: binding= ((SimpleName) selectedNode).resolveBinding(); break; case ASTNode.QUALIFIED_NAME: binding= ((QualifiedName) selectedNode).resolveBinding(); break; case ASTNode.SIMPLE_TYPE: binding= ((SimpleType) selectedNode).resolveBinding(); break; case ASTNode.METHOD_INVOCATION: binding= ((MethodInvocation) selectedNode).getName().resolveBinding(); break; case ASTNode.SUPER_METHOD_INVOCATION: binding= ((SuperMethodInvocation) selectedNode).getName().resolveBinding(); break; case ASTNode.SUPER_FIELD_ACCESS: binding= ((SuperFieldAccess) selectedNode).getName().resolveBinding(); break; case ASTNode.CLASS_INSTANCE_CREATION: binding= ((ClassInstanceCreation) selectedNode).resolveConstructorBinding(); break; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: binding= ((SuperConstructorInvocation) selectedNode).resolveConstructorBinding(); break; default: return; } ITypeBinding typeBinding= null; String name; if (binding instanceof IMethodBinding) { typeBinding= ((IMethodBinding) binding).getDeclaringClass(); name= binding.getName() + "()"; //$NON-NLS-1$ } else if (binding instanceof IVariableBinding) { typeBinding= ((IVariableBinding) binding).getDeclaringClass(); name= binding.getName(); } else if (binding instanceof ITypeBinding) { typeBinding= (ITypeBinding) binding; name= binding.getName(); } else { return; } if (typeBinding != null && typeBinding.isFromSource()) { int includedModifiers= 0; int excludedModifiers= 0; String label; if (kind == TO_VISIBLE) { excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC; includedModifiers= getNeededVisibility(selectedNode, typeBinding); label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changevisibility.description", new String[] { name, getVisibilityString(includedModifiers) }); //$NON-NLS-1$ } else if (kind == TO_STATIC) { label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertostatic.description", name); //$NON-NLS-1$ includedModifiers= Modifier.STATIC; } else if (kind == TO_NON_STATIC) { label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertononstatic.description", name); //$NON-NLS-1$ excludedModifiers= Modifier.STATIC; } else if (kind == TO_NON_PRIVATE) { label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertoprotected.description", name); //$NON-NLS-1$ excludedModifiers= Modifier.PRIVATE; includedModifiers= Modifier.PROTECTED; } else { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), typeBinding); if (targetCU != null && JavaModelUtil.isEditable(targetCU)) { Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); proposals.add(new ModifierChangeCompletionProposal(label, targetCU, binding, selectedNode, includedModifiers, excludedModifiers, 0, image)); } } } public static void addNonFinalLocalProposal(ICorrectionContext context, List proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (!(selectedNode instanceof SimpleName)) { return; } IBinding binding= ((SimpleName) selectedNode).resolveBinding(); if (binding instanceof IVariableBinding) { Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertofinal.description", binding.getName()); //$NON-NLS-1$ proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, 0, image)); } } private static String getVisibilityString(int code) { if (Modifier.isPublic(code)) { return "public"; //$NON-NLS-1$ }else if (Modifier.isProtected(code)) { return "protected"; //$NON-NLS-1$ } return "default"; //$NON-NLS-1$ } private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType) { ITypeBinding currNodeBinding= ASTResolving.getBindingOfParentType(currNode); if (currNodeBinding == null) { // import return Modifier.PUBLIC; } ITypeBinding curr= currNodeBinding; while (curr != null) { if (curr.getKey().equals(targetType.getKey())) { return Modifier.PROTECTED; } curr= curr.getSuperclass(); } if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) { return 0; } return Modifier.PUBLIC; } public static void addAbstractMethodProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } MethodDeclaration decl; if (selectedNode instanceof SimpleName) { decl= (MethodDeclaration) selectedNode.getParent(); } else if (selectedNode instanceof MethodDeclaration) { decl= (MethodDeclaration) selectedNode; } else { return; } ASTNode parentType= ASTResolving.findParentType(decl); TypeDeclaration parentTypeDecl= null; boolean parentIsAbstractClass= false; if (parentType instanceof TypeDeclaration) { parentTypeDecl= (TypeDeclaration) parentType; parentIsAbstractClass= !parentTypeDecl.isInterface() && Modifier.isAbstract(parentTypeDecl.getModifiers()); } boolean hasNoBody= (decl.getBody() == null); if (context.getProblemId() == IProblem.AbstractMethodInAbstractClass || parentIsAbstractClass) { ASTRewrite rewrite= new ASTRewrite(decl.getParent()); AST ast= astRoot.getAST(); MethodDeclaration modifiedNode= ast.newMethodDeclaration(); modifiedNode.setConstructor(decl.isConstructor()); modifiedNode.setExtraDimensions(decl.getExtraDimensions()); modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.ABSTRACT); rewrite.markAsModified(decl, modifiedNode); if (hasNoBody) { Block newBody= ast.newBlock(); rewrite.markAsInserted(newBody); decl.setBody(newBody); Expression expr= ASTResolving.getInitExpression(decl.getReturnType(), decl.getExtraDimensions()); if (expr != null) { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(expr); newBody.statements().add(returnStatement); } } String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removeabstract.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image); proposal.ensureNoModifications(); proposals.add(proposal); } if (!hasNoBody && context.getProblemId() == IProblem.BodyForAbstractMethod) { ASTRewrite rewrite= new ASTRewrite(decl.getParent()); rewrite.markAsRemoved(decl.getBody()); String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removebody.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image); proposal2.ensureNoModifications(); proposals.add(proposal2); } if (context.getProblemId() == IProblem.AbstractMethodInAbstractClass && (parentTypeDecl != null)) { ASTRewriteCorrectionProposal proposal= getMakeTypeStaticProposal(cu, parentTypeDecl); proposals.add(proposal); } } public static void addNativeMethodProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } MethodDeclaration decl; if (selectedNode instanceof SimpleName) { decl= (MethodDeclaration) selectedNode.getParent(); } else if (selectedNode instanceof MethodDeclaration) { decl= (MethodDeclaration) selectedNode; } else { return; } { ASTRewrite rewrite= new ASTRewrite(decl.getParent()); AST ast= astRoot.getAST(); MethodDeclaration modifiedNode= ast.newMethodDeclaration(); modifiedNode.setConstructor(decl.isConstructor()); modifiedNode.setExtraDimensions(decl.getExtraDimensions()); modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.NATIVE); rewrite.markAsModified(decl, modifiedNode); Block newBody= ast.newBlock(); rewrite.markAsInserted(newBody); decl.setBody(newBody); Expression expr= ASTResolving.getInitExpression(decl.getReturnType(), decl.getExtraDimensions()); if (expr != null) { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(expr); newBody.statements().add(returnStatement); } String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removenative.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image); proposal.ensureNoModifications(); proposals.add(proposal); } if (decl.getBody() != null) { ASTRewrite rewrite= new ASTRewrite(decl.getParent()); rewrite.markAsRemoved(decl.getBody()); String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removebody.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 0, image); proposal2.ensureNoModifications(); proposals.add(proposal2); } } public static ASTRewriteCorrectionProposal getMakeTypeStaticProposal(ICompilationUnit cu, TypeDeclaration typeDeclaration) throws CoreException { ASTRewrite rewrite= new ASTRewrite(typeDeclaration.getParent()); AST ast= typeDeclaration.getAST(); TypeDeclaration modifiedNode= ast.newTypeDeclaration(); modifiedNode.setInterface(typeDeclaration.isInterface()); modifiedNode.setModifiers(typeDeclaration.getModifiers() | Modifier.ABSTRACT); rewrite.markAsModified(typeDeclaration, modifiedNode); String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.addabstract.description", typeDeclaration.getName().getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image); proposal.ensureNoModifications(); return proposal; } public static void addMethodRequiresBodyProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); AST ast= context.getASTRoot().getAST(); ASTNode selectedNode= context.getCoveringNode(); if (!(selectedNode instanceof MethodDeclaration)) { return; } MethodDeclaration decl= (MethodDeclaration) selectedNode; ASTRewrite rewrite= new ASTRewrite(decl); MethodDeclaration modifiedNode= ast.newMethodDeclaration(); modifiedNode.setConstructor(decl.isConstructor()); modifiedNode.setExtraDimensions(decl.getExtraDimensions()); modifiedNode.setModifiers(decl.getModifiers() & ~Modifier.ABSTRACT); rewrite.markAsModified(decl, modifiedNode); Block body= ast.newBlock(); decl.setBody(body); rewrite.markAsInserted(body); String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.addmissingbody.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 3, image); proposal.ensureNoModifications(); proposals.add(proposal); } public static void addNeedToEmulateProposal(ICorrectionContext context, List proposals) { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (!(selectedNode instanceof SimpleName)) { return; } IBinding binding= ((SimpleName) selectedNode).resolveBinding(); if (binding instanceof IVariableBinding) { Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertofinal.description", binding.getName()); //$NON-NLS-1$ proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, Modifier.FINAL, 0, 0, image)); } } }
31,634
Bug 31634 Quickfix should do a team checkout
2.1 M5 / clearcase / eclipse-ccase plugin 0.9.3 Quickfix says no corrections available for a read only file that is under source control (i.e. not checked out). Quickfix should propose the corrections and check the file out automatically to implement them.
resolved fixed
570190f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T17:12:22Z
2003-02-12T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.NamingConventions; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class NewMethodCompletionProposal extends ASTRewriteCorrectionProposal { private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation private List fArguments; private ITypeBinding fSenderBinding; private boolean fIsInDifferentCU; public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) { super(label, targetCU, null, relevance, image); fNode= invocationNode; fArguments= arguments; fSenderBinding= binding; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; if (typeDecl != null) { fIsInDifferentCU= false; newTypeDecl= typeDecl; } else { fIsInDifferentCU= true; CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true); newTypeDecl= newRoot.findDeclaringNode(fSenderBinding.getKey()); } if (newTypeDecl != null) { ASTRewrite rewrite= new ASTRewrite(newTypeDecl); List methods; if (fSenderBinding.isAnonymous()) { methods= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations(); } else { methods= ((TypeDeclaration) newTypeDecl).bodyDeclarations(); } MethodDeclaration newStub= getStub(rewrite, newTypeDecl); if (!fIsInDifferentCU) { methods.add(findInsertIndex(methods, fNode.getStartPosition()), newStub); } else if (isConstructor()) { methods.add(0, newStub); } else { methods.add(newStub); } rewrite.markAsInserted(newStub); return rewrite; } return null; } private boolean isConstructor() { return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION; } private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException { AST ast= targetTypeDecl.getAST(); MethodDeclaration decl= ast.newMethodDeclaration(); decl.setConstructor(isConstructor()); decl.setModifiers(evaluateModifiers(targetTypeDecl)); decl.setName(ast.newSimpleName(getMethodName())); List arguments= fArguments; List params= decl.parameters(); int nArguments= arguments.size(); ArrayList names= new ArrayList(nArguments); for (int i= 0; i < arguments.size(); i++) { Expression elem= (Expression) arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); Type type= getParameterType(ast, elem); param.setType(type); param.setName(ast.newSimpleName(getParameterName(names, elem, type))); params.add(param); } Block body= null; String bodyStatement= ""; //$NON-NLS-1$ if (!isConstructor()) { Type returnType= evaluateMethodType(ast); if (returnType == null) { decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID)); } else { decl.setReturnType(returnType); } if (!fSenderBinding.isInterface() && returnType != null) { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(ASTResolving.getInitExpression(returnType, 0)); bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n')); } } if (!fSenderBinding.isInterface()) { body= ast.newBlock(); String placeHolder= StubUtility.getMethodBodyContent(isConstructor(), getCompilationUnit().getJavaProject(), fSenderBinding.getName(), getMethodName(), bodyStatement); if (placeHolder != null) { ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT); body.statements().add(todoNode); } } decl.setBody(body); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (settings.createComments && !fSenderBinding.isAnonymous()) { String string= StubUtility.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null); if (string != null) { Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC); decl.setJavadoc(javadoc); } } return decl; } private String getParameterName(ArrayList takenNames, Expression argNode, Type type) { if (argNode instanceof SimpleName) { String name= ((SimpleName) argNode).getIdentifier(); while (takenNames.contains(name)) { name += '1'; } takenNames.add(name); return name; } int dim= 0; if (type.isArrayType()) { ArrayType arrayType= (ArrayType) type; dim= arrayType.getDimensions(); type= arrayType.getElementType(); } String typeName= ASTNodes.getTypeName(type); String packName= Signature.getQualifier(typeName); IJavaProject project= getCompilationUnit().getJavaProject(); String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]); String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames); takenNames.add(names[0]); return names[0]; } private int findInsertIndex(List decls, int currPos) { int nDecls= decls.size(); for (int i= 0; i < nDecls; i++) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) { return i + 1; } } return nDecls; } private String getMethodName() { if (fNode instanceof MethodInvocation) { return ((MethodInvocation)fNode).getName().getIdentifier(); } else if (fNode instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)fNode).getName().getIdentifier(); } else { return fSenderBinding.getName(); // name of the class } } private int evaluateModifiers(ASTNode targetTypeDecl) { if (fSenderBinding.isInterface()) { // for interface members copy the modifiers from an existing field MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods(); if (methodDecls.length > 0) { return methodDecls[0].getModifiers(); } return 0; } if (fNode instanceof MethodInvocation) { int modifiers= 0; Expression expression= ((MethodInvocation)fNode).getExpression(); if (expression != null) { if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } else if (ASTResolving.isInStaticContext(fNode)) { modifiers |= Modifier.STATIC; } ASTNode node= ASTResolving.findParentType(fNode); if (targetTypeDecl.equals(node)) { modifiers |= Modifier.PRIVATE; } else if (node instanceof AnonymousClassDeclaration) { modifiers |= Modifier.PROTECTED; } else { modifiers |= Modifier.PUBLIC; } return modifiers; } return Modifier.PUBLIC; } private Type evaluateMethodType(AST ast) throws CoreException { ITypeBinding binding= ASTResolving.guessBindingForReference(fNode); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return null; } private Type getParameterType(AST ast, Expression elem) throws CoreException { ITypeBinding binding= ASTResolving.normalizeTypeBinding(elem.resolveTypeBinding()); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (fIsInDifferentCU) { change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(getCompilationUnit(), true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
31,634
Bug 31634 Quickfix should do a team checkout
2.1 M5 / clearcase / eclipse-ccase plugin 0.9.3 Quickfix says no corrections available for a read only file that is under source control (i.e. not checked out). Quickfix should propose the corrections and check the file out automatically to implement them.
resolved fixed
570190f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T17:12:22Z
2003-02-12T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewVariableCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; public class NewVariableCompletionProposal extends ASTRewriteCorrectionProposal { public static final int LOCAL= 1; public static final int FIELD= 2; public static final int PARAM= 3; private int fVariableKind; private SimpleName fOriginalNode; private ITypeBinding fSenderBinding; private boolean fIsInDifferentCU; public NewVariableCompletionProposal(String label, ICompilationUnit cu, int variableKind, SimpleName node, ITypeBinding senderBinding, int relevance, Image image) { super(label, cu, null, relevance, image); fVariableKind= variableKind; fOriginalNode= node; fSenderBinding= senderBinding; fIsInDifferentCU= false; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit cu= ASTResolving.findParentCompilationUnit(fOriginalNode); if (fVariableKind == PARAM) { return doAddParam(cu); } else if (fVariableKind == FIELD) { return doAddField(cu); } else { // LOCAL return doAddLocal(cu); } } private ASTRewrite doAddParam(CompilationUnit cu) throws CoreException { AST ast= cu.getAST(); SimpleName node= fOriginalNode; BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration) { ASTRewrite rewrite= new ASTRewrite(decl); SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration(); newDecl.setType(evaluateVariableType(ast)); newDecl.setName(ast.newSimpleName(node.getIdentifier())); rewrite.markAsInserted(newDecl); ((MethodDeclaration)decl).parameters().add(newDecl); return rewrite; } return null; } private ASTRewrite doAddLocal(CompilationUnit cu) throws CoreException { AST ast= cu.getAST(); SimpleName node= fOriginalNode; BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration || decl instanceof Initializer) { ASTRewrite rewrite= new ASTRewrite(decl); VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag); Type type= evaluateVariableType(ast); newDecl.setType(type); newDeclFrag.setName(ast.newSimpleName(node.getIdentifier())); newDeclFrag.setInitializer(ASTResolving.getInitExpression(type, 0)); ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) parent; if (node.equals(assignment.getLeftHandSide())) { int parentParentKind= parent.getParent().getNodeType(); if (parentParentKind == ASTNode.EXPRESSION_STATEMENT) { Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); newDeclFrag.setInitializer(placeholder); rewrite.markAsReplaced(assignment.getParent(), newDecl); return rewrite; } else if (parentParentKind == ASTNode.FOR_STATEMENT) { ForStatement forStatement= (ForStatement) parent.getParent(); if (forStatement.initializers().size() == 1 && assignment.equals(forStatement.initializers().get(0))) { VariableDeclarationFragment frag= ast.newVariableDeclarationFragment(); VariableDeclarationExpression expression= ast.newVariableDeclarationExpression(frag); frag.setName(ast.newSimpleName(node.getIdentifier())); Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); frag.setInitializer(placeholder); expression.setType(evaluateVariableType(ast)); rewrite.markAsReplaced(assignment, expression); return rewrite; } } } } else if (parent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) { rewrite.markAsReplaced(parent, newDecl); return rewrite; } Statement statement= ASTResolving.findParentStatement(node); if (statement != null && statement.getParent() instanceof Block) { Block block= (Block) statement.getParent(); List statements= block.statements(); statements.add(0, newDecl); rewrite.markAsInserted(newDecl); return rewrite; } } return null; } private ASTRewrite doAddField(CompilationUnit astRoot) throws CoreException { SimpleName node= fOriginalNode; ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding); if (newTypeDecl != null) { } else { astRoot= AST.parseCompilationUnit(getCompilationUnit(), true); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); fIsInDifferentCU= true; } if (newTypeDecl != null) { ASTRewrite rewrite= new ASTRewrite(newTypeDecl); AST ast= newTypeDecl.getAST(); VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(node.getIdentifier())); Type type= evaluateVariableType(ast); FieldDeclaration newDecl= ast.newFieldDeclaration(fragment); newDecl.setType(type); newDecl.setModifiers(evaluateFieldModifiers(newTypeDecl)); if (fSenderBinding.isInterface()) { fragment.setInitializer(ASTResolving.getInitExpression(type, 0)); } boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION; List decls= isAnonymous ? ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations() : ((TypeDeclaration) newTypeDecl).bodyDeclarations(); decls.add(findInsertIndex(decls, node.getStartPosition()), newDecl); rewrite.markAsInserted(newDecl); return rewrite; } return null; } private int findInsertIndex(List decls, int currPos) { for (int i= decls.size() - 1; i >= 0; i--) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof FieldDeclaration && currPos > curr.getStartPosition() + curr.getLength()) { return i + 1; } } return 0; } private Type evaluateVariableType(AST ast) throws CoreException { ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } private int evaluateFieldModifiers(ASTNode newTypeDecl) { if (fSenderBinding.isInterface()) { // for interface members copy the modifiers from an existing field FieldDeclaration[] fieldDecls= ((TypeDeclaration) newTypeDecl).getFields(); if (fieldDecls.length > 0) { return fieldDecls[0].getModifiers(); } return 0; } int modifiers= 0; ASTNode node= ASTResolving.findParentType(fOriginalNode); if (newTypeDecl.equals(node)) { modifiers |= Modifier.PRIVATE; if (ASTResolving.isInStaticContext(fOriginalNode)) { modifiers |= Modifier.STATIC; } } else if (node instanceof AnonymousClassDeclaration) { modifiers |= Modifier.PROTECTED; } else { modifiers |= Modifier.PUBLIC; ASTNode parent= fOriginalNode.getParent(); if (parent instanceof QualifiedName) { Name qualifier= ((QualifiedName)parent).getQualifier(); if (qualifier.resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } } return modifiers; } /** * Returns the variable kind. * @return int */ public int getVariableKind() { return fVariableKind; } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (fIsInDifferentCU) { change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(getCompilationUnit(), true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
31,634
Bug 31634 Quickfix should do a team checkout
2.1 M5 / clearcase / eclipse-ccase plugin 0.9.3 Quickfix says no corrections available for a read only file that is under source control (i.e. not checked out). Quickfix should propose the corrections and check the file out automatically to implement them.
resolved fixed
570190f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T17:12:22Z
2003-02-12T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;[email protected]&gt; - New class/interface with wizard ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit; import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class UnresolvedElementsSubProcessor { public static void getVariableProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (selectedNode == null) { return; } // type that defines the variable, null if local ITypeBinding binding= null; ITypeBinding declaringTypeBinding= ASTResolving.getBindingOfParentType(selectedNode); if (declaringTypeBinding == null) { return; } // possible kind of the node int similarNodeKind= SimilarElementsRequestor.VARIABLES; Name node= null; if (selectedNode instanceof SimpleName) { node= (SimpleName) selectedNode; ASTNode parent= node.getParent(); if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) { similarNodeKind |= SimilarElementsRequestor.CLASSES; } } else if (selectedNode instanceof QualifiedName) { QualifiedName qualifierName= (QualifiedName) selectedNode; ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding(); if (qualifierBinding != null) { node= qualifierName.getName(); binding= qualifierBinding; } else { node= qualifierName.getQualifier(); if (node.isSimpleName()) { similarNodeKind |= SimilarElementsRequestor.REF_TYPES; } else { similarNodeKind= SimilarElementsRequestor.REF_TYPES; } } } else if (selectedNode instanceof FieldAccess) { FieldAccess access= (FieldAccess) selectedNode; Expression expression= access.getExpression(); if (expression != null) { binding= expression.resolveTypeBinding(); if (binding != null) { node= access.getName(); } } } else if (selectedNode instanceof SuperFieldAccess) { binding= declaringTypeBinding.getSuperclass(); } else if (selectedNode instanceof SimpleType) { similarNodeKind= SimilarElementsRequestor.REF_TYPES; node= ((SimpleType) selectedNode).getName(); } if (node == null) { return; } // avoid corrections like int i= i; String assignedName= null; ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier(); } // corrections SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, similarNodeKind); for (int i= 0; i < elements.length; i++) { SimilarElement curr= elements[i]; if ((curr.getKind() & SimilarElementsRequestor.VARIABLES) != 0 && !curr.getName().equals(assignedName)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", curr.getName()); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), curr.getName(), 3)); } } // add type proposals if ((similarNodeKind & SimilarElementsRequestor.ALL_TYPES) != 0) { int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0; addSimilarTypeProposals(elements, cu, node, relevance + 1, proposals); addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals); } if ((similarNodeKind & SimilarElementsRequestor.VARIABLES) == 0) { return; } SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName(); // new variables ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding; if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) { String label; Image image; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image)); if (binding == null && senderBinding.isAnonymous()) { ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding); if (anonymDecl != null) { senderBinding= ASTResolving.getBindingOfParentType(anonymDecl.getParent()); if (!senderBinding.isAnonymous()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image)); } } } } if (binding == null) { BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node); int type= bodyDeclaration.getNodeType(); if (type == ASTNode.METHOD_DECLARATION) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 1, image)); } if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 3, image)); } } } public static void getTypeProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } int kind= SimilarElementsRequestor.ALL_TYPES; ASTNode parent= selectedNode.getParent(); switch (parent.getNodeType()) { case ASTNode.TYPE_DECLARATION: TypeDeclaration typeDeclaration=(TypeDeclaration) parent; if (typeDeclaration.superInterfaces().contains(selectedNode)) { kind= SimilarElementsRequestor.INTERFACES; } else if (selectedNode.equals(typeDeclaration.getSuperclass())) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration= (MethodDeclaration) parent; if (methodDeclaration.thrownExceptions().contains(selectedNode)) { kind= SimilarElementsRequestor.CLASSES; } else if (selectedNode.equals(methodDeclaration.getReturnType())) { kind= SimilarElementsRequestor.REF_TYPES | SimilarElementsRequestor.VOIDTYPE; } break; case ASTNode.INSTANCEOF_EXPRESSION: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.THROW_STATEMENT: case ASTNode.CLASS_INSTANCE_CREATION: kind= SimilarElementsRequestor.CLASSES; break; case ASTNode.SINGLE_VARIABLE_DECLARATION: int superParent= parent.getParent().getNodeType(); if (superParent == ASTNode.CATCH_CLAUSE) { kind= SimilarElementsRequestor.CLASSES; } break; default: } Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); } } else if (selectedNode instanceof Name) { node= (Name) selectedNode; } else { return; } SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind); addSimilarTypeProposals(elements, cu, node, 3, proposals); // add type addNewTypeProposals(cu, node, kind, 0, proposals); } private static void addSimilarTypeProposals(SimilarElement[] elements, ICompilationUnit cu, Name node, int relevance, List proposals) throws JavaModelException { // try to resolve type in context -> highest severity String resolvedTypeName= null; ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node); if (binding != null) { if (binding.isArray()) { binding= binding.getElementType(); } resolvedTypeName= Bindings.getFullyQualifiedName(binding); proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2)); } // add all similar elements for (int i= 0; i < elements.length; i++) { SimilarElement elem= elements[i]; if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) { String fullName= elem.getName(); if (!fullName.equals(resolvedTypeName)) { proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance)); } } } } private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws JavaModelException { CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$ ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String simpleName= importEdit.addImport(fullName); TextEdit root= proposal.getRootTextEdit(); if (!importEdit.isEmpty()) { root.add(importEdit); //$NON-NLS-1$ } if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL)); proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", fullName)); //$NON-NLS-1$ proposal.setRelevance(relevance + 20); } else { root.add(SimpleTextEdit.createReplace(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$ proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", simpleName)); //$NON-NLS-1$ proposal.setRelevance(relevance); } return proposal; } private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, List proposals) throws JavaModelException { Name node= refNode; do { String typeName= ASTResolving.getSimpleName(node); Name qualifier= null; // only propose to create types for qualifiers when the name starts with upper case boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode); if (isPossibleName) { IPackageFragment enclosingPackage= null; IType enclosingType= null; if (node.isSimpleName()) { enclosingPackage= (IPackageFragment) cu.getParent(); // don't sugest member type, user can select it in wizard } else { Name qualifierName= ((QualifiedName) node).getQualifier(); // 24347 // IBinding binding= qualifierName.resolveBinding(); // if (binding instanceof ITypeBinding) { // enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject()); IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength()); if (res!= null && res.length > 0 && res[0] instanceof IType) { enclosingType= (IType) res[0]; } else { qualifier= qualifierName; enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName)); } } // new top level type if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$ if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance)); } } // new member type if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) { if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance)); } } } node= qualifier; } while (node != null); } public static void getMethodProposals(ICorrectionContext context, boolean needsNewName, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveringNode(); if (!(selectedNode instanceof SimpleName)) { return; } SimpleName nameNode= (SimpleName) selectedNode; List arguments; Expression sender; boolean isSuperInvocation; ASTNode invocationNode= nameNode.getParent(); if (invocationNode instanceof MethodInvocation) { MethodInvocation methodImpl= (MethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getExpression(); isSuperInvocation= false; } else if (invocationNode instanceof SuperMethodInvocation) { SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getQualifier(); isSuperInvocation= true; } else { return; } String methodName= nameNode.getIdentifier(); // corrections SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, nameNode, SimilarElementsRequestor.METHODS); ArrayList parameterMismatchs= new ArrayList(); for (int i= 0; i < elements.length; i++) { String curr= elements[i].getName(); if (curr.equals(methodName) && needsNewName) { //parameterMismatchs.add(elements[i]); continue; } String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, context.getCompilationUnit(), context.getOffset(), context.getLength(), curr, 2)); } if (parameterMismatchs.size() == 1) { SimilarElement elem= (SimilarElement) parameterMismatchs.get(0); String[] paramTypes= elem.getParameterTypes(); ITypeBinding[] argTypes= getArgumentTypes(arguments); if (paramTypes != null && argTypes != null) { } } // new method ITypeBinding binding= null; if (sender != null) { binding= sender.resolveTypeBinding(); } else { binding= ASTResolving.getBindingOfParentType(invocationNode); if (isSuperInvocation && binding != null) { binding= binding.getSuperclass(); } } if (binding != null && binding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); if (targetCU != null && JavaModelUtil.isEditable(targetCU)) { String label; Image image; if (cu.equals(targetCU)) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", methodName); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { methodName, targetCU.getElementName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image)); if (binding.isAnonymous() && cu.equals(targetCU)) { ASTNode anonymDecl= astRoot.findDeclaringNode(binding); if (anonymDecl != null) { binding= ASTResolving.getBindingOfParentType(anonymDecl.getParent()); if (!binding.isAnonymous()) { String[] args= new String[] { methodName, binding.getName() }; label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image)); } } } } } } private static ITypeBinding[] getArgumentTypes(List arguments) { ITypeBinding[] res= new ITypeBinding[arguments.size()]; for (int i= 0; i < res.length; i++) { Expression expression= (Expression) arguments.get(i); ITypeBinding curr= expression.resolveTypeBinding(); if (curr == null) { return null; } curr= ASTResolving.normalizeTypeBinding(curr); if (curr == null) { curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } res[i]= curr; } return res; } public static void getConstructorProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } ITypeBinding targetBinding= null; List arguments= null; int type= selectedNode.getNodeType(); if (type == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; IBinding binding= creation.getName().resolveBinding(); if (binding instanceof ITypeBinding) { targetBinding= (ITypeBinding) binding; arguments= creation.arguments(); } } else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding.getSuperclass(); arguments= ((SuperConstructorInvocation) selectedNode).arguments(); } } else if (type == ASTNode.CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding; arguments= ((ConstructorInvocation) selectedNode).arguments(); } } if (targetBinding != null && targetBinding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding); if (targetCU != null && JavaModelUtil.isEditable(targetCU)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", targetBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 1, image)); } } } public static void getAmbiguosTypeReferenceProposals(ICorrectionContext context, List proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= context.getOffset(); int len= context.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType) { String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 1, image); ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings()); importEdit.addImport(qualifiedTypeName); importEdit.setFindAmbiguosImports(true); proposal.getRootTextEdit().add(importEdit); proposals.add(proposal); } } } }
31,821
Bug 31821 Quick fix for unused imports
build I20030211 It would be nice to have a quick fix for unused import warnings which simply removes the import.
resolved fixed
da63070
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T19:34:05Z
2003-02-13T21:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CUCorrectionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.compare.contentmergeviewer.ITokenComparator; import org.eclipse.compare.rangedifferencer.RangeDifference; import org.eclipse.compare.rangedifferencer.RangeDifferencer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.internal.corext.refactoring.base.Change; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.MultiTextEdit; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit; import org.eclipse.jdt.internal.corext.textmanipulation.TextRegion; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.compare.JavaTokenComparator; public class CUCorrectionProposal extends ChangeCorrectionProposal { private ICompilationUnit fCompilationUnit; private TextEdit fRootEdit; public CUCorrectionProposal(String name, ICompilationUnit cu, int relevance) { this(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); } public CUCorrectionProposal(String name, ICompilationUnit cu, int relevance, Image image) { super(name, null, relevance, image); fRootEdit= new MultiTextEdit(); fCompilationUnit= cu; } public CUCorrectionProposal(String name, CompilationUnitChange change, int relevance, Image image) { super(name, change, relevance, image); fCompilationUnit= change.getCompilationUnit(); } protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException { CompilationUnitChange change= new CompilationUnitChange(name, cu); change.setEdit(rootEdit); change.setSave(false); return change; } /* * @see ChangeCorrectionProposal#getChange() */ protected Change getChange() throws CoreException { Change change= super.getChange(); if (change == null) { change= createCompilationUnitChange(getDisplayString(), fCompilationUnit, fRootEdit); setChange(change); } return change; } protected final void addEdits(CompilationUnitChange change) throws CoreException { } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { StringBuffer buf= new StringBuffer(); try { CompilationUnitChange change= getCompilationUnitChange(); TextBuffer previewConent= change.getPreviewTextBuffer(); String currentConentString= change.getCurrentContent(); ITokenComparator leftSide= new JavaTokenComparator(previewConent.getContent(), true); ITokenComparator rightSide= new JavaTokenComparator(currentConentString, true); RangeDifference[] differences= RangeDifferencer.findRanges(leftSide, rightSide); for (int i= 0; i < differences.length; i++) { RangeDifference curr= differences[i]; int start= leftSide.getTokenStart(curr.leftStart()); int end= leftSide.getTokenStart(curr.leftEnd()); if (curr.kind() == RangeDifference.CHANGE && curr.leftLength() > 0) { buf.append("<b>"); //$NON-NLS-1$ appendContent(previewConent, start, end, buf, false); buf.append("</b>"); //$NON-NLS-1$ } else if (curr.kind() == RangeDifference.NOCHANGE) { appendContent(previewConent, start, end, buf, true); } } } catch (CoreException e) { JavaPlugin.log(e); } return buf.toString(); } private final int surroundLines= 1; private void appendContent(TextBuffer text, int startOffset, int endOffset, StringBuffer buf, boolean surroundLinesOnly) { int startLine= text.getLineOfOffset(startOffset); int endLine= text.getLineOfOffset(endOffset); boolean dotsAdded= false; if (surroundLinesOnly && startOffset == 0) { // no surround lines for the top no-change range startLine= Math.max(endLine - surroundLines, 0); buf.append("...<br>"); //$NON-NLS-1$ dotsAdded= true; } for (int i= startLine; i <= endLine; i++) { if (surroundLinesOnly) { if ((i - startLine > surroundLines) && (endLine - i > surroundLines)) { if (!dotsAdded) { buf.append("...<br>"); //$NON-NLS-1$ dotsAdded= true; } else if (endOffset == text.getLength()) { return; // no surround lines for the bottom no-change range } continue; } } TextRegion lineInfo= text.getLineInformation(i); int start= lineInfo.getOffset(); int end= start + lineInfo.getLength(); int from= Math.max(start, startOffset); int to= Math.min(end, endOffset); String content= text.getContent(from, to - from); if (surroundLinesOnly && (from == start) && Strings.containsOnlyWhitespaces(content)) { continue; // ignore empty lines exept when range started in the middle of a line } buf.append(content); if (to == end && to != endOffset) { // new line when at the end of the line, and not end of range buf.append("<br>"); //$NON-NLS-1$ } } } /** * Gets the compilationUnitChange. * @return Returns a CompilationUnitChange */ public CompilationUnitChange getCompilationUnitChange() throws CoreException { return (CompilationUnitChange) getChange(); } /** * @return Returns the root text edit */ public TextEdit getRootTextEdit() { return fRootEdit; } /** * Returns the compilationUnit. * @return ICompilationUnit */ public ICompilationUnit getCompilationUnit() { return fCompilationUnit; } }
31,821
Bug 31821 Quick fix for unused imports
build I20030211 It would be nice to have a quick fix for unused import warnings which simply removes the import.
resolved fixed
da63070
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T19:34:05Z
2003-02-13T21:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.IMarkerResolutionGenerator; import org.eclipse.ui.IMarkerResolutionGenerator2; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation; import org.eclipse.jdt.internal.ui.text.java.IJavaCompletionProposal; /** */ public class CorrectionMarkerResolutionGenerator implements IMarkerResolutionGenerator, IMarkerResolutionGenerator2 { public static class CorrectionMarkerResolution implements IMarkerResolution { private IEditorInput fEditorInput; private IJavaCompletionProposal fProposal; /** * Constructor for CorrectionMarkerResolution. */ public CorrectionMarkerResolution(IEditorInput editorInput, IJavaCompletionProposal proposal) { fEditorInput= editorInput; fProposal= proposal; } /* (non-Javadoc) * @see IMarkerResolution#getLabel() */ public String getLabel() { return fProposal.getDisplayString(); } /* (non-Javadoc) * @see IMarkerResolution#run(IMarker) */ public void run(IMarker marker) { IDocument doc= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(fEditorInput); if (doc != null) { fProposal.apply(doc); } } } private static final IMarkerResolution[] NO_RESOLUTIONS= new IMarkerResolution[0]; /** * Constructor for CorrectionMarkerResolutionGenerator. */ public CorrectionMarkerResolutionGenerator() { super(); } /* (non-Javadoc) * @see org.eclipse.ui.IMarkerResolutionGenerator2#hasResolutions(org.eclipse.core.resources.IMarker) */ public boolean hasResolutions(IMarker marker) { int id= marker.getAttribute(IJavaModelMarker.ID, -1); return JavaCorrectionProcessor.hasCorrections(id); } /* (non-Javadoc) * @see IMarkerResolutionGenerator#getResolutions(IMarker) */ public IMarkerResolution[] getResolutions(IMarker marker) { int id= marker.getAttribute(IJavaModelMarker.ID, -1); if (!JavaCorrectionProcessor.hasCorrections(id)) { return NO_RESOLUTIONS; } try { ICompilationUnit cu= getCompilationUnit(marker); if (cu != null && JavaModelUtil.isEditable(cu)) { IEditorInput input= EditorUtility.getEditorInput(cu); if (input != null) { // only works with element open in editor CorrectionContext context= findCorrectionContext(input, marker); if (context != null) { ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(context, proposals); int nProposals= proposals.size(); IMarkerResolution[] resolutions= new IMarkerResolution[nProposals]; for (int i= 0; i < nProposals; i++) { resolutions[i]= new CorrectionMarkerResolution(input, (IJavaCompletionProposal) proposals.get(i)); } return resolutions; } } } } catch (JavaModelException e) { JavaPlugin.log(e); } return new IMarkerResolution[0]; } private ICompilationUnit getCompilationUnit(IMarker marker) { IResource res= marker.getResource(); if (res instanceof IFile && res.isAccessible()) { return JavaCore.createCompilationUnitFrom((IFile) res); } return null; } private CorrectionContext findCorrectionContext(IEditorInput input, IMarker marker) throws JavaModelException { IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(input); if (model != null) { Iterator iter= model.getAnnotationIterator(); while (iter.hasNext()) { Object curr= iter.next(); if (curr instanceof JavaMarkerAnnotation) { JavaMarkerAnnotation annot= (JavaMarkerAnnotation) curr; if (marker.equals(annot.getMarker())) { Position pos= model.getPosition(annot); if (pos != null) { ICompilationUnit cu= getCompilationUnit(marker); return new CorrectionContext(JavaModelUtil.toWorkingCopy(cu), pos.getOffset(), pos.getLength(), annot.getId(), annot.getArguments()); } } } } } return null; } }
31,821
Bug 31821 Quick fix for unused imports
build I20030211 It would be nice to have a quick fix for unused import warnings which simply removes the import.
resolved fixed
da63070
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T19:34:05Z
2003-02-13T21:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierChangeCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationExpression; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.core.dom.VariableDeclarationStatement; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Resources; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; public class ModifierChangeCompletionProposal extends ASTRewriteCorrectionProposal { private IBinding fBinding; private ASTNode fNode; private boolean fIsInDifferentCU; private int fIncludedModifiers; private int fExcludedModifiers; public ModifierChangeCompletionProposal(String label, ICompilationUnit targetCU, IBinding binding, ASTNode node, int includedModifiers, int excludedModifiers, int relevance, Image image) { super(label, targetCU, null, relevance, image); fBinding= binding; fNode= node; fIncludedModifiers= includedModifiers; fExcludedModifiers= excludedModifiers; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode boundNode= astRoot.findDeclaringNode(fBinding); ASTNode declNode= null; if (boundNode != null) { fIsInDifferentCU= false; declNode= boundNode; } else { fIsInDifferentCU= true; CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true); declNode= newRoot.findDeclaringNode(fBinding.getKey()); } if (declNode != null) { ASTRewrite rewrite= new ASTRewrite(declNode.getParent()); AST ast= declNode.getAST(); if (declNode instanceof MethodDeclaration) { MethodDeclaration methodDecl= (MethodDeclaration) declNode; int newModifiers= (methodDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; MethodDeclaration modifiedNode= ast.newMethodDeclaration(); modifiedNode.setConstructor(methodDecl.isConstructor()); // no change modifiedNode.setExtraDimensions(methodDecl.getExtraDimensions()); // no change modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(methodDecl, modifiedNode); } else if (declNode instanceof VariableDeclarationFragment) { ASTNode parent= declNode.getParent(); if (parent instanceof FieldDeclaration) { FieldDeclaration fieldDecl= (FieldDeclaration) parent; int newModifiers= (fieldDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; FieldDeclaration modifiedNode= ast.newFieldDeclaration(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(fieldDecl, modifiedNode); } else if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement varDecl= (VariableDeclarationStatement) parent; int newModifiers= (varDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; VariableDeclarationStatement modifiedNode= ast.newVariableDeclarationStatement(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(varDecl, modifiedNode); } else if (parent instanceof VariableDeclarationExpression) { VariableDeclarationExpression varDecl= (VariableDeclarationExpression) parent; int newModifiers= (varDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; VariableDeclarationExpression modifiedNode= ast.newVariableDeclarationExpression(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(varDecl, modifiedNode); } } else if (declNode instanceof SingleVariableDeclaration) { SingleVariableDeclaration variableDeclaration= (SingleVariableDeclaration) declNode; int newModifiers= (variableDeclaration.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; SingleVariableDeclaration modifiedNode= ast.newSingleVariableDeclaration(); modifiedNode.setExtraDimensions(variableDeclaration.getExtraDimensions()); // no change modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(variableDeclaration, modifiedNode); } else if (declNode instanceof TypeDeclaration) { TypeDeclaration typeDecl= (TypeDeclaration) declNode; int newModifiers= (typeDecl.getModifiers() & ~fExcludedModifiers) | fIncludedModifiers; TypeDeclaration modifiedNode= ast.newTypeDeclaration(); modifiedNode.setInterface(typeDecl.isInterface()); // no change modifiedNode.setModifiers(newModifiers); rewrite.markAsModified(typeDecl, modifiedNode); } return rewrite; } return null; } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (fIsInDifferentCU) { ICompilationUnit unit= getCompilationUnit(); IStatus status= Resources.makeCommittable(JavaModelUtil.toOriginal(unit).getResource(), null); if (!status.isOK()) { String label= CorrectionMessages.getString("ModifierChangeCompletionProposal.error.title"); //$NON-NLS-1$ String message= CorrectionMessages.getString("ModifierChangeCompletionProposal.error.message"); //$NON-NLS-1$ ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), label, message, status); return; } change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(unit, true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
31,821
Bug 31821 Quick fix for unused imports
build I20030211 It would be nice to have a quick fix for unused import warnings which simply removes the import.
resolved fixed
da63070
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T19:34:05Z
2003-02-13T21:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.NamingConventions; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Resources; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class NewMethodCompletionProposal extends ASTRewriteCorrectionProposal { private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation private List fArguments; private ITypeBinding fSenderBinding; private boolean fIsInDifferentCU; public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) { super(label, targetCU, null, relevance, image); fNode= invocationNode; fArguments= arguments; fSenderBinding= binding; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; if (typeDecl != null) { fIsInDifferentCU= false; newTypeDecl= typeDecl; } else { fIsInDifferentCU= true; CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true); newTypeDecl= newRoot.findDeclaringNode(fSenderBinding.getKey()); } if (newTypeDecl != null) { ASTRewrite rewrite= new ASTRewrite(newTypeDecl); List methods; if (fSenderBinding.isAnonymous()) { methods= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations(); } else { methods= ((TypeDeclaration) newTypeDecl).bodyDeclarations(); } MethodDeclaration newStub= getStub(rewrite, newTypeDecl); if (!fIsInDifferentCU) { methods.add(findInsertIndex(methods, fNode.getStartPosition()), newStub); } else if (isConstructor()) { methods.add(0, newStub); } else { methods.add(newStub); } rewrite.markAsInserted(newStub); return rewrite; } return null; } private boolean isConstructor() { return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION; } private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException { AST ast= targetTypeDecl.getAST(); MethodDeclaration decl= ast.newMethodDeclaration(); decl.setConstructor(isConstructor()); decl.setModifiers(evaluateModifiers(targetTypeDecl)); decl.setName(ast.newSimpleName(getMethodName())); List arguments= fArguments; List params= decl.parameters(); int nArguments= arguments.size(); ArrayList names= new ArrayList(nArguments); for (int i= 0; i < arguments.size(); i++) { Expression elem= (Expression) arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); Type type= getParameterType(ast, elem); param.setType(type); param.setName(ast.newSimpleName(getParameterName(names, elem, type))); params.add(param); } Block body= null; String bodyStatement= ""; //$NON-NLS-1$ if (!isConstructor()) { Type returnType= evaluateMethodType(ast); if (returnType == null) { decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID)); } else { decl.setReturnType(returnType); } if (!fSenderBinding.isInterface() && returnType != null) { ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(ASTResolving.getInitExpression(returnType, 0)); bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n')); } } if (!fSenderBinding.isInterface()) { body= ast.newBlock(); String placeHolder= StubUtility.getMethodBodyContent(isConstructor(), getCompilationUnit().getJavaProject(), fSenderBinding.getName(), getMethodName(), bodyStatement); if (placeHolder != null) { ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT); body.statements().add(todoNode); } } decl.setBody(body); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (settings.createComments && !fSenderBinding.isAnonymous()) { String string= StubUtility.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null); if (string != null) { Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC); decl.setJavadoc(javadoc); } } return decl; } private String getParameterName(ArrayList takenNames, Expression argNode, Type type) { if (argNode instanceof SimpleName) { String name= ((SimpleName) argNode).getIdentifier(); while (takenNames.contains(name)) { name += '1'; } takenNames.add(name); return name; } int dim= 0; if (type.isArrayType()) { ArrayType arrayType= (ArrayType) type; dim= arrayType.getDimensions(); type= arrayType.getElementType(); } String typeName= ASTNodes.getTypeName(type); String packName= Signature.getQualifier(typeName); IJavaProject project= getCompilationUnit().getJavaProject(); String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]); String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames); takenNames.add(names[0]); return names[0]; } private int findInsertIndex(List decls, int currPos) { int nDecls= decls.size(); for (int i= 0; i < nDecls; i++) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) { return i + 1; } } return nDecls; } private String getMethodName() { if (fNode instanceof MethodInvocation) { return ((MethodInvocation)fNode).getName().getIdentifier(); } else if (fNode instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)fNode).getName().getIdentifier(); } else { return fSenderBinding.getName(); // name of the class } } private int evaluateModifiers(ASTNode targetTypeDecl) { if (fSenderBinding.isInterface()) { // for interface members copy the modifiers from an existing field MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods(); if (methodDecls.length > 0) { return methodDecls[0].getModifiers(); } return 0; } if (fNode instanceof MethodInvocation) { int modifiers= 0; Expression expression= ((MethodInvocation)fNode).getExpression(); if (expression != null) { if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } else if (ASTResolving.isInStaticContext(fNode)) { modifiers |= Modifier.STATIC; } ASTNode node= ASTResolving.findParentType(fNode); if (targetTypeDecl.equals(node)) { modifiers |= Modifier.PRIVATE; } else if (node instanceof AnonymousClassDeclaration) { modifiers |= Modifier.PROTECTED; } else { modifiers |= Modifier.PUBLIC; } return modifiers; } return Modifier.PUBLIC; } private Type evaluateMethodType(AST ast) throws CoreException { ITypeBinding binding= ASTResolving.guessBindingForReference(fNode); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return null; } private Type getParameterType(AST ast, Expression elem) throws CoreException { ITypeBinding binding= ASTResolving.normalizeTypeBinding(elem.resolveTypeBinding()); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (fIsInDifferentCU) { ICompilationUnit unit= getCompilationUnit(); IStatus status= Resources.makeCommittable(JavaModelUtil.toOriginal(unit).getResource(), null); if (!status.isOK()) { String label= CorrectionMessages.getString("NewMethodCompletionProposal.error.title"); //$NON-NLS-1$ String message= CorrectionMessages.getString("NewMethodCompletionProposal.error.message"); //$NON-NLS-1$ ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), label, message, status); return; } change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(unit, true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
31,821
Bug 31821 Quick fix for unused imports
build I20030211 It would be nice to have a quick fix for unused import warnings which simply removes the import.
resolved fixed
da63070
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-14T19:34:05Z
2003-02-13T21:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewVariableCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Resources; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; public class NewVariableCompletionProposal extends ASTRewriteCorrectionProposal { public static final int LOCAL= 1; public static final int FIELD= 2; public static final int PARAM= 3; private int fVariableKind; private SimpleName fOriginalNode; private ITypeBinding fSenderBinding; private boolean fIsInDifferentCU; public NewVariableCompletionProposal(String label, ICompilationUnit cu, int variableKind, SimpleName node, ITypeBinding senderBinding, int relevance, Image image) { super(label, cu, null, relevance, image); fVariableKind= variableKind; fOriginalNode= node; fSenderBinding= senderBinding; fIsInDifferentCU= false; } protected ASTRewrite getRewrite() throws CoreException { CompilationUnit cu= ASTResolving.findParentCompilationUnit(fOriginalNode); if (fVariableKind == PARAM) { return doAddParam(cu); } else if (fVariableKind == FIELD) { return doAddField(cu); } else { // LOCAL return doAddLocal(cu); } } private ASTRewrite doAddParam(CompilationUnit cu) throws CoreException { AST ast= cu.getAST(); SimpleName node= fOriginalNode; BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration) { ASTRewrite rewrite= new ASTRewrite(decl); SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration(); newDecl.setType(evaluateVariableType(ast)); newDecl.setName(ast.newSimpleName(node.getIdentifier())); rewrite.markAsInserted(newDecl); ((MethodDeclaration)decl).parameters().add(newDecl); return rewrite; } return null; } private ASTRewrite doAddLocal(CompilationUnit cu) throws CoreException { AST ast= cu.getAST(); SimpleName node= fOriginalNode; BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration || decl instanceof Initializer) { ASTRewrite rewrite= new ASTRewrite(decl); VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag); Type type= evaluateVariableType(ast); newDecl.setType(type); newDeclFrag.setName(ast.newSimpleName(node.getIdentifier())); newDeclFrag.setInitializer(ASTResolving.getInitExpression(type, 0)); ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) parent; if (node.equals(assignment.getLeftHandSide())) { int parentParentKind= parent.getParent().getNodeType(); if (parentParentKind == ASTNode.EXPRESSION_STATEMENT) { Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); newDeclFrag.setInitializer(placeholder); rewrite.markAsReplaced(assignment.getParent(), newDecl); return rewrite; } else if (parentParentKind == ASTNode.FOR_STATEMENT) { ForStatement forStatement= (ForStatement) parent.getParent(); if (forStatement.initializers().size() == 1 && assignment.equals(forStatement.initializers().get(0))) { VariableDeclarationFragment frag= ast.newVariableDeclarationFragment(); VariableDeclarationExpression expression= ast.newVariableDeclarationExpression(frag); frag.setName(ast.newSimpleName(node.getIdentifier())); Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); frag.setInitializer(placeholder); expression.setType(evaluateVariableType(ast)); rewrite.markAsReplaced(assignment, expression); return rewrite; } } } } else if (parent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) { rewrite.markAsReplaced(parent, newDecl); return rewrite; } Statement statement= ASTResolving.findParentStatement(node); if (statement != null && statement.getParent() instanceof Block) { Block block= (Block) statement.getParent(); List statements= block.statements(); statements.add(0, newDecl); rewrite.markAsInserted(newDecl); return rewrite; } } return null; } private ASTRewrite doAddField(CompilationUnit astRoot) throws CoreException { SimpleName node= fOriginalNode; ASTNode newTypeDecl= astRoot.findDeclaringNode(fSenderBinding); if (newTypeDecl != null) { } else { astRoot= AST.parseCompilationUnit(getCompilationUnit(), true); newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey()); fIsInDifferentCU= true; } if (newTypeDecl != null) { ASTRewrite rewrite= new ASTRewrite(newTypeDecl); AST ast= newTypeDecl.getAST(); VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(node.getIdentifier())); Type type= evaluateVariableType(ast); FieldDeclaration newDecl= ast.newFieldDeclaration(fragment); newDecl.setType(type); newDecl.setModifiers(evaluateFieldModifiers(newTypeDecl)); if (fSenderBinding.isInterface()) { fragment.setInitializer(ASTResolving.getInitExpression(type, 0)); } boolean isAnonymous= newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION; List decls= isAnonymous ? ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations() : ((TypeDeclaration) newTypeDecl).bodyDeclarations(); decls.add(findInsertIndex(decls, node.getStartPosition()), newDecl); rewrite.markAsInserted(newDecl); return rewrite; } return null; } private int findInsertIndex(List decls, int currPos) { for (int i= decls.size() - 1; i >= 0; i--) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof FieldDeclaration && currPos > curr.getStartPosition() + curr.getLength()) { return i + 1; } } return 0; } private Type evaluateVariableType(AST ast) throws CoreException { ITypeBinding binding= ASTResolving.guessBindingForReference(fOriginalNode); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$ } private int evaluateFieldModifiers(ASTNode newTypeDecl) { if (fSenderBinding.isInterface()) { // for interface members copy the modifiers from an existing field FieldDeclaration[] fieldDecls= ((TypeDeclaration) newTypeDecl).getFields(); if (fieldDecls.length > 0) { return fieldDecls[0].getModifiers(); } return 0; } int modifiers= 0; ASTNode node= ASTResolving.findParentType(fOriginalNode); if (newTypeDecl.equals(node)) { modifiers |= Modifier.PRIVATE; if (ASTResolving.isInStaticContext(fOriginalNode)) { modifiers |= Modifier.STATIC; } } else if (node instanceof AnonymousClassDeclaration) { modifiers |= Modifier.PROTECTED; } else { modifiers |= Modifier.PUBLIC; ASTNode parent= fOriginalNode.getParent(); if (parent instanceof QualifiedName) { Name qualifier= ((QualifiedName)parent).getQualifier(); if (qualifier.resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } } return modifiers; } /** * Returns the variable kind. * @return int */ public int getVariableKind() { return fVariableKind; } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (fIsInDifferentCU) { ICompilationUnit unit= getCompilationUnit(); IStatus status= Resources.makeCommittable(JavaModelUtil.toOriginal(unit).getResource(), null); if (!status.isOK()) { String label= CorrectionMessages.getString("NewVariableCompletionProposal.error.title"); //$NON-NLS-1$ String message= CorrectionMessages.getString("NewVariableCompletionProposal.error.message"); //$NON-NLS-1$ ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), label, message, status); return; } change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(unit, true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
31,929
Bug 31929 Missing projects in Packages Explorer with Closed Project filter on
build i2003-02-14, win2k, J9 I have "hide closed projects" selected in my filter settings for the packages explorer view. When I exit my workspace and come back in, the Packages Explorer only displays some of my open projects. When I change the filter settings to show closed projects (hit ok) and then back to hiding the closed projects, the display is correct.
resolved fixed
4ac1413
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T16:54:13Z
2003-02-14T22:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/ClosedProjectFilter.java
31,708
Bug 31708 Make changes to RefreshAction to sync up code with workbench
null
resolved fixed
1f960ae
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T17:36:41Z
2003-02-12T20:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/RefreshAction.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Action for refreshing the workspace from the local file system for * the selected resources and all of their descendents. This action * also considers external Jars managed by the Java Model. * <p> * Action is applicable to selections containing resources and Java * elements down to compilation units. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class RefreshAction extends SelectionDispatchAction { /** * Creates a new <code>RefreshAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public RefreshAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("RefreshAction.label")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("RefreshAction.toolTip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.REFRESH_ACTION); } /* (non-Javadoc) * Method declared in SelectionDispatchAction */ protected void selectionChanged(IStructuredSelection selection) { setEnabled(checkEnabled(selection)); } private boolean checkEnabled(IStructuredSelection selection) { if (selection.isEmpty()) return true; for (Iterator iter= selection.iterator(); iter.hasNext();) { Object element= (Object) iter.next(); if (element instanceof IAdaptable) { IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class); if (resource == null) return false; } else { return false; } } return true; } /* (non-Javadoc) * Method declared in SelectionDispatchAction */ protected void run(IStructuredSelection selection) { final IResource[] resources= getResources(selection); IWorkspaceRunnable operation= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { monitor.beginTask(ActionMessages.getString("RefreshAction.progressMessage"), resources.length * 2); //$NON-NLS-1$ monitor.subTask(""); //$NON-NLS-1$ List javaElements= new ArrayList(5); for (int i= 0; i < resources.length; i++) { IResource resource= resources[i]; resource.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1)); if (resource.getType() == IResource.PROJECT) { checkLocationDeleted(((IProject)resource)); } IJavaElement jElement= JavaCore.create(resource); if (jElement != null && jElement.exists()) javaElements.add(jElement); } IJavaModel model= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); model.refreshExternalArchives( (IJavaElement[]) javaElements.toArray(new IJavaElement[javaElements.size()]), new SubProgressMonitor(monitor, resources.length)); } }; try { new ProgressMonitorDialog(getShell()).run(true, true, new WorkbenchRunnableAdapter(operation)); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("RefreshAction.error.title"), //$NON-NLS-1$ ActionMessages.getString("RefreshAction.error.message")); //$NON-NLS-1$ } catch (InterruptedException e) { // canceled } } private IResource[] getResources(IStructuredSelection selection) { if (selection.isEmpty()) { return new IResource[] {ResourcesPlugin.getWorkspace().getRoot()}; } List result= new ArrayList(selection.size()); for (Iterator iter= selection.iterator(); iter.hasNext();) { Object element= (Object) iter.next(); if (element instanceof IAdaptable) { IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class); if (resource != null) result.add(resource); } } for (Iterator iter= result.iterator(); iter.hasNext();) { IResource resource= (IResource) iter.next(); if (isDescendent(result, resource)) iter.remove(); } return (IResource[]) result.toArray(new IResource[result.size()]); } private boolean isDescendent(List candidates, IResource element) { IResource parent= element.getParent(); while (parent != null) { if (candidates.contains(parent)) return true; parent= parent.getParent(); } return false; } private void checkLocationDeleted(IProject project) throws CoreException { if (!project.exists()) return; File location = project.getLocation().toFile(); if (!location.exists()) { final String message = ActionMessages.getFormattedString( "RefreshAction.locationDeleted.message", //$NON-NLS-1$ new Object[] {project.getName(), location.getAbsolutePath()}); final boolean[] result= new boolean[1]; // Must prompt user in UI thread (we're in the operation thread here). getShell().getDisplay().syncExec(new Runnable() { public void run() { result[0]= MessageDialog.openQuestion(getShell(), ActionMessages.getString("RefreshAction.locationDeleted.title"), //$NON-NLS-1$ message); } }); if (result[0]) { project.delete(true, true, null); } } } }
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
org.eclipse.jdt.ui/core
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/RefactoringSearchEngine.java
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
org.eclipse.jdt.ui/core
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchOperation.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.search; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class JavaSearchOperation extends WorkspaceModifyOperation { private IWorkspace fWorkspace; private IJavaElement fElementPattern; private int fLimitTo; private String fStringPattern; private boolean fIsCaseSensitive; private int fSearchFor; private IJavaSearchScope fScope; private String fScopeDescription; private JavaSearchResultCollector fCollector; protected JavaSearchOperation( IWorkspace workspace, int limitTo, IJavaSearchScope scope, String scopeDescription, JavaSearchResultCollector collector) { fWorkspace= workspace; fLimitTo= limitTo; fScope= scope; fScopeDescription= scopeDescription; fCollector= collector; fCollector.setOperation(this); } public JavaSearchOperation( IWorkspace workspace, IJavaElement pattern, int limitTo, IJavaSearchScope scope, String scopeDescription, JavaSearchResultCollector collector) { this(workspace, limitTo, scope, scopeDescription, collector); fElementPattern= pattern; } public JavaSearchOperation( IWorkspace workspace, String pattern, boolean caseSensitive, int searchFor, int limitTo, IJavaSearchScope scope, String scopeDescription, JavaSearchResultCollector collector) { this(workspace, limitTo, scope, scopeDescription, collector); fStringPattern= pattern; fIsCaseSensitive= caseSensitive; fSearchFor= searchFor; } protected void execute(IProgressMonitor monitor) throws CoreException { fCollector.setProgressMonitor(monitor); // Also search working copies SearchEngine engine= new SearchEngine(JavaUI.getSharedWorkingCopies()); if (fElementPattern != null) engine.search(fWorkspace, fElementPattern, fLimitTo, fScope, fCollector); else engine.search(fWorkspace, SearchEngine.createSearchPattern(fStringPattern, fSearchFor, fLimitTo, fIsCaseSensitive), fScope, fCollector); } String getSingularLabel() { String desc= null; if (fElementPattern != null) { if (fLimitTo == IJavaSearchConstants.REFERENCES && fElementPattern.getElementType() == IJavaElement.METHOD) desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)fElementPattern); else desc= fElementPattern.getElementName(); if ("".equals(desc) && fElementPattern.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$ desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$ } else desc= fStringPattern; String[] args= new String[] {desc, fScopeDescription}; //$NON-NLS-1$ switch (fLimitTo) { case IJavaSearchConstants.IMPLEMENTORS: return SearchMessages.getFormattedString("JavaSearchOperation.singularImplementorsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.DECLARATIONS: return SearchMessages.getFormattedString("JavaSearchOperation.singularDeclarationsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.REFERENCES: return SearchMessages.getFormattedString("JavaSearchOperation.singularReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.ALL_OCCURRENCES: return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.READ_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.singularReadReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.WRITE_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.singularWriteReferencesPostfix", args); //$NON-NLS-1$ default: return SearchMessages.getFormattedString("JavaSearchOperation.singularOccurrencesPostfix", args); //$NON-NLS-1$; } } String getPluralLabelPattern() { String desc= null; if (fElementPattern != null) { if (fLimitTo == IJavaSearchConstants.REFERENCES && fElementPattern.getElementType() == IJavaElement.METHOD) desc= PrettySignature.getUnqualifiedMethodSignature((IMethod)fElementPattern); else desc= fElementPattern.getElementName(); if ("".equals(desc) && fElementPattern.getElementType() == IJavaElement.PACKAGE_FRAGMENT) //$NON-NLS-1$ desc= SearchMessages.getString("JavaSearchOperation.default_package"); //$NON-NLS-1$ } else desc= fStringPattern; String[] args= new String[] {desc, "{0}", fScopeDescription}; //$NON-NLS-1$ switch (fLimitTo) { case IJavaSearchConstants.IMPLEMENTORS: return SearchMessages.getFormattedString("JavaSearchOperation.pluralImplementorsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.DECLARATIONS: return SearchMessages.getFormattedString("JavaSearchOperation.pluralDeclarationsPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.REFERENCES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.ALL_OCCURRENCES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.READ_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralReadReferencesPostfix", args); //$NON-NLS-1$ case IJavaSearchConstants.WRITE_ACCESSES: return SearchMessages.getFormattedString("JavaSearchOperation.pluralWriteReferencesPostfix", args); //$NON-NLS-1$ default: return SearchMessages.getFormattedString("JavaSearchOperation.pluralOccurrencesPostfix", args); //$NON-NLS-1$; } } ImageDescriptor getImageDescriptor() { if (fLimitTo == IJavaSearchConstants.IMPLEMENTORS || fLimitTo == IJavaSearchConstants.DECLARATIONS) return JavaPluginImages.DESC_OBJS_SEARCH_DECL; else return JavaPluginImages.DESC_OBJS_SEARCH_REF; } }
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchUtil.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.search; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Platform; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.browsing.JavaElementTypeComparator; import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * This class contains some utility methods for J Search. */ public class SearchUtil extends JavaModelUtil { // LRU working sets public static int LRU_WORKINGSET_LIST_SIZE= 3; private static LRUWorkingSetsList fgLRUWorkingSets; // Settings store private static final String DIALOG_SETTINGS_KEY= "JavaElementSearchActions"; //$NON-NLS-1$ private static final String STORE_LRU_WORKING_SET_NAMES= "lastUsedWorkingSetNames"; //$NON-NLS-1$ private static final JavaElementTypeComparator fgJavaElementTypeComparator= new JavaElementTypeComparator(); private static IDialogSettings fgSettingsStore; private static final String BIN_PRIM_CONST_WARN_DIALOG_ID= "BinaryPrimitiveConstantWarningDialog"; //$NON-NLS-1$ public static IJavaElement getJavaElement(IMarker marker) { if (marker == null || !marker.exists()) return null; try { String handleId= (String)marker.getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID); IJavaElement je= JavaCore.create(handleId); if (je == null) return null; if (!marker.getAttribute(IJavaSearchUIConstants.ATT_IS_WORKING_COPY, false)) { if (je != null && je.exists()) return je; } if (isBinary(je) || fgJavaElementTypeComparator.compare(je, IJavaElement.COMPILATION_UNIT) > 0) return je; ICompilationUnit cu= findCompilationUnit(je); if (cu == null || !cu.exists()) { cu= (ICompilationUnit)JavaCore.create(marker.getResource()); } // Find working copy element IWorkingCopy[] workingCopies= JavaUI.getSharedWorkingCopies(); int i= 0; while (i < workingCopies.length) { if (workingCopies[i].getOriginalElement().equals(cu)) { je= findInWorkingCopy(workingCopies[i], je, true); break; } i++; } if (je != null && !je.exists()) { IJavaElement[] jElements= cu.findElements(je); if (jElements == null || jElements.length == 0) je= cu.getElementAt(marker.getAttribute(IMarker.CHAR_START, 0)); else je= jElements[0]; } return je; } catch (CoreException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.createJavaElement.title"), SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-2$ //$NON-NLS-1$ return null; } } public static IJavaElement getJavaElement(Object entry) { if (entry != null && isISearchResultViewEntry(entry)) return getJavaElement((ISearchResultViewEntry)entry); return null; } public static IResource getResource(Object entry) { if (entry != null && isISearchResultViewEntry(entry)) return ((ISearchResultViewEntry)entry).getResource(); return null; } public static IJavaElement getJavaElement(ISearchResultViewEntry entry) { if (entry != null) return getJavaElement(entry.getSelectedMarker()); return null; } public static boolean isSearchPlugInActivated() { return Platform.getPluginRegistry().getPluginDescriptor("org.eclipse.search").isPluginActivated(); //$NON-NLS-1$ } public static boolean isISearchResultViewEntry(Object object) { return object != null && isSearchPlugInActivated() && (object instanceof ISearchResultViewEntry); } private static boolean isBinary(IJavaElement jElement) { if (jElement instanceof IMember) return ((IMember)jElement).isBinary(); IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)jElement.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT); if (pkgRoot != null && pkgRoot.isArchive()) return true; return false; } /** * Returns the working copy of the given java element. * @param javaElement the javaElement for which the working copyshould be found * @param reconcile indicates whether the working copy must be reconcile prior to searching it * @return the working copy of the given element or <code>null</code> if none */ private static IJavaElement findInWorkingCopy(IWorkingCopy workingCopy, IJavaElement element, boolean reconcile) throws JavaModelException { if (workingCopy != null) { if (reconcile) { JavaModelUtil.reconcile(workingCopy); return SearchUtil.findInCompilationUnit((ICompilationUnit)workingCopy, element); } else { return SearchUtil.findInCompilationUnit((ICompilationUnit)workingCopy, element); } } return null; } /** * Returns the compilation unit for the given java element. * * @param element the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ static ICompilationUnit findCompilationUnit(IJavaElement element) { if (element == null) return null; if (element.getElementType() == IJavaElement.COMPILATION_UNIT) return (ICompilationUnit)element; if (element instanceof IMember) return ((IMember)element).getCompilationUnit(); return findCompilationUnit(element.getParent()); } /* * Copied from JavaModelUtil and patched to allow members which do not exist. * The only case where this is a problem is for methods which have same name and * paramters as a constructor. The constructor will win in such a situation. * * @see JavaModelUtil#findMemberInCompilationUnit(ICompilationUnit, IMember) */ public static IMember findInCompilationUnit(ICompilationUnit cu, IMember member) throws JavaModelException { if (member.getElementType() == IJavaElement.TYPE) { return findTypeInCompilationUnit(cu, getTypeQualifiedName((IType)member)); } else { IType declaringType= findTypeInCompilationUnit(cu, getTypeQualifiedName(member.getDeclaringType())); if (declaringType != null) { IMember result= null; switch (member.getElementType()) { case IJavaElement.FIELD: result= declaringType.getField(member.getElementName()); break; case IJavaElement.METHOD: IMethod meth= (IMethod) member; // XXX: Begin patch --------------------- boolean isConstructor; if (meth.exists()) isConstructor= meth.isConstructor(); else isConstructor= declaringType.getElementName().equals(meth.getElementName()); // XXX: End patch ----------------------- result= findMethod(meth.getElementName(), meth.getParameterTypes(), isConstructor, declaringType); break; case IJavaElement.INITIALIZER: result= declaringType.getInitializer(1); break; } if (result != null && result.exists()) { return result; } } } return null; } /* * XXX: Unchanged copy from JavaModelUtil */ public static IJavaElement findInCompilationUnit(ICompilationUnit cu, IJavaElement element) throws JavaModelException { if (element instanceof IMember) return findInCompilationUnit(cu, (IMember)element); int type= element.getElementType(); switch (type) { case IJavaElement.IMPORT_CONTAINER: return cu.getImportContainer(); case IJavaElement.PACKAGE_DECLARATION: return find(cu.getPackageDeclarations(), element.getElementName()); case IJavaElement.IMPORT_DECLARATION: return find(cu.getImports(), element.getElementName()); case IJavaElement.COMPILATION_UNIT: return cu; } return null; } /* * XXX: Unchanged copy from JavaModelUtil */ private static IJavaElement find(IJavaElement[] elements, String name) { if (elements == null || name == null) return null; for (int i= 0; i < elements.length; i++) { if (name.equals(elements[i].getElementName())) return elements[i]; } return null; } public static String toString(IWorkingSet[] workingSets) { Arrays.sort(workingSets, new WorkingSetComparator()); String result= ""; //$NON-NLS-1$ if (workingSets != null && workingSets.length > 0) { boolean firstFound= false; for (int i= 0; i < workingSets.length; i++) { String workingSetName= workingSets[i].getName(); if (firstFound) result= SearchMessages.getFormattedString("SearchUtil.workingSetConcatenation", new String[] {result, workingSetName}); //$NON-NLS-1$ else { result= workingSetName; firstFound= true; } } } return result; } // ---------- LRU working set handling ---------- /** * Updates the LRU list of working sets. * * @param workingSets the workings sets to be added to the LRU list */ public static void updateLRUWorkingSets(IWorkingSet[] workingSets) { if (workingSets == null || workingSets.length < 1) return; getLRUWorkingSets().add(workingSets); saveState(); } private static void saveState() { IWorkingSet[] workingSets; Iterator iter= fgLRUWorkingSets.iterator(); int i= 0; while (iter.hasNext()) { workingSets= (IWorkingSet[])iter.next(); String[] names= new String[workingSets.length]; for (int j= 0; j < workingSets.length; j++) names[j]= workingSets[j].getName(); fgSettingsStore.put(STORE_LRU_WORKING_SET_NAMES + i, names); i++; } } public static LRUWorkingSetsList getLRUWorkingSets() { if (fgLRUWorkingSets == null) { restoreState(); } return fgLRUWorkingSets; } static void restoreState() { fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE); fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY); if (fgSettingsStore == null) fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY); boolean foundLRU= false; for (int i= LRU_WORKINGSET_LIST_SIZE - 1; i >= 0; i--) { String[] lruWorkingSetNames= fgSettingsStore.getArray(STORE_LRU_WORKING_SET_NAMES + i); if (lruWorkingSetNames != null) { Set workingSets= new HashSet(2); for (int j= 0; j < lruWorkingSetNames.length; j++) { IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[j]); if (workingSet != null) { workingSets.add(workingSet); } } foundLRU= true; if (!workingSets.isEmpty()) fgLRUWorkingSets.add((IWorkingSet[])workingSets.toArray(new IWorkingSet[workingSets.size()])); } } if (!foundLRU) // try old preference format restoreFromOldFormat(); } private static void restoreFromOldFormat() { fgLRUWorkingSets= new LRUWorkingSetsList(LRU_WORKINGSET_LIST_SIZE); fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().getSection(DIALOG_SETTINGS_KEY); if (fgSettingsStore == null) fgSettingsStore= JavaPlugin.getDefault().getDialogSettings().addNewSection(DIALOG_SETTINGS_KEY); boolean foundLRU= false; String[] lruWorkingSetNames= fgSettingsStore.getArray(STORE_LRU_WORKING_SET_NAMES); if (lruWorkingSetNames != null) { for (int i= lruWorkingSetNames.length - 1; i >= 0; i--) { IWorkingSet workingSet= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(lruWorkingSetNames[i]); if (workingSet != null) { foundLRU= true; fgLRUWorkingSets.add(new IWorkingSet[]{workingSet}); } } } if (foundLRU) // save in new format saveState(); } public static void warnIfBinaryConstant(IJavaElement element, Shell shell) { if (isBinaryPrimitveConstantOrString(element)) OptionalMessageDialog.open( BIN_PRIM_CONST_WARN_DIALOG_ID, shell, SearchMessages.getString("Search.FindReferencesAction.BinPrimConstWarnDialog.title"), //$NON-NLS-1$ null, SearchMessages.getString("Search.FindReferencesAction.BinPrimConstWarnDialog.message"), //$NON-NLS-1$ OptionalMessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); } private static boolean isBinaryPrimitveConstantOrString(IJavaElement element) { if (element != null && element.getElementType() == IJavaElement.FIELD) { IField field= (IField)element; int flags; try { flags= field.getFlags(); } catch (JavaModelException ex) { return false; } return field.isBinary() && Flags.isStatic(flags) && Flags.isFinal(flags) && isPrimitiveOrString(field); } return false; } private static boolean isPrimitiveOrString(IField field) { String fieldType; try { fieldType= field.getTypeSignature(); } catch (JavaModelException ex) { return false; } char first= fieldType.charAt(0); return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED && first != Signature.C_ARRAY) || (first == Signature.C_RESOLVED && fieldType.substring(1, fieldType.length() - 1).equals(String.class.getName())); } }
31,473
Bug 31473 Search Engine should not search in working copies that aren't on the build path
null
resolved fixed
62bc18c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T18:21:51Z
2003-02-10T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaUI.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IPath; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.util.Assert; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.jdt.core.IBufferFactory; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.SharedImages; import org.eclipse.jdt.internal.ui.dialogs.MainTypeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.MultiMainTypeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.MultiTypeSelectionDialog; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; /** * Central access point for the Java UI plug-in (id <code>"org.eclipse.jdt.ui"</code>). * This class provides static methods for: * <ul> * <li> creating various kinds of selection dialogs to present a collection * of Java elements to the user and let them make a selection.</li> * <li> opening a Java editor on a compilation unit.</li> * </ul> * <p> * This class provides static methods and fields only; it is not intended to be * instantiated or subclassed by clients. * </p> */ public final class JavaUI { private static ISharedImages fgSharedImages= null; private JavaUI() { // prevent instantiation of JavaUI. } /** * The id of the Java plugin (value <code>"org.eclipse.jdt.ui"</code>). */ public static final String ID_PLUGIN= "org.eclipse.jdt.ui"; //$NON-NLS-1$ /** * The id of the Java perspective * (value <code>"org.eclipse.jdt.ui.JavaPerspective"</code>). */ public static final String ID_PERSPECTIVE= "org.eclipse.jdt.ui.JavaPerspective"; //$NON-NLS-1$ /** * The id of the Java hierarchy perspective * (value <code>"org.eclipse.jdt.ui.JavaHierarchyPerspective"</code>). */ public static final String ID_HIERARCHYPERSPECTIVE= "org.eclipse.jdt.ui.JavaHierarchyPerspective"; //$NON-NLS-1$ /** * The id of the Java action set * (value <code>"org.eclipse.jdt.ui.JavaActionSet"</code>). */ public static final String ID_ACTION_SET= "org.eclipse.jdt.ui.JavaActionSet"; //$NON-NLS-1$ /** * The id of the Java Element Creation action set * (value <code>"org.eclipse.jdt.ui.JavaElementCreationActionSet"</code>). * * @since 2.0 */ public static final String ID_ELEMENT_CREATION_ACTION_SET= "org.eclipse.jdt.ui.JavaElementCreationActionSet"; //$NON-NLS-1$ /** * The id of the Java Coding action set * (value <code>"org.eclipse.jdt.ui.CodingActionSet"</code>). * * @since 2.0 */ public static final String ID_CODING_ACTION_SET= "org.eclipse.jdt.ui.CodingActionSet"; //$NON-NLS-1$ /** * The id of the Java action set for open actions * (value <code>"org.eclipse.jdt.ui.A_OpenActionSet"</code>). * * @since 2.0 */ public static final String ID_OPEN_ACTION_SET= "org.eclipse.jdt.ui.A_OpenActionSet"; //$NON-NLS-1$ /** * The id of the Java Search action set * (value <code>org.eclipse.jdt.ui.SearchActionSet"</code>). * * @since 2.0 */ public static final String ID_SEARCH_ACTION_SET= "org.eclipse.jdt.ui.SearchActionSet"; //$NON-NLS-1$ /** * The editor part id of the editor that presents Java compilation units * (value <code>"org.eclipse.jdt.ui.CompilationUnitEditor"</code>). */ public static final String ID_CU_EDITOR= "org.eclipse.jdt.ui.CompilationUnitEditor"; //$NON-NLS-1$ /** * The editor part id of the editor that presents Java binary class files * (value <code>"org.eclipse.jdt.ui.ClassFileEditor"</code>). */ public static final String ID_CF_EDITOR= "org.eclipse.jdt.ui.ClassFileEditor"; //$NON-NLS-1$ /** * The editor part id of the code snippet editor * (value <code>"org.eclipse.jdt.ui.SnippetEditor"</code>). */ public static final String ID_SNIPPET_EDITOR= "org.eclipse.jdt.ui.SnippetEditor"; //$NON-NLS-1$ /** * The view part id of the Packages view * (value <code>"org.eclipse.jdt.ui.PackageExplorer"</code>). * <p> * When this id is used to access * a view part with <code>IWorkbenchPage.findView</code> or * <code>showView</code>, the returned <code>IViewPart</code> * can be safely cast to an <code>IPackagesViewPart</code>. * </p> * * @see IPackagesViewPart * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) */ public static final String ID_PACKAGES= "org.eclipse.jdt.ui.PackageExplorer"; //$NON-NLS-1$ /** * The view part id of the type hierarchy part. * (value <code>"org.eclipse.jdt.ui.TypeHierarchy"</code>). * <p> * When this id is used to access * a view part with <code>IWorkbenchPage.findView</code> or * <code>showView</code>, the returned <code>IViewPart</code> * can be safely cast to an <code>ITypeHierarchyViewPart</code>. * </p> * * @see ITypeHierarchyViewPart * @see org.eclipse.ui.IWorkbenchPage#findView(java.lang.String) * @see org.eclipse.ui.IWorkbenchPage#showView(java.lang.String) */ public static final String ID_TYPE_HIERARCHY= "org.eclipse.jdt.ui.TypeHierarchy"; //$NON-NLS-1$ /** * The id of the Java Browsing Perspective * (value <code>"org.eclipse.jdt.ui.JavaBrowsingPerspective"</code>). * * @since 2.0 */ public static String ID_BROWSING_PERSPECTIVE= "org.eclipse.jdt.ui.JavaBrowsingPerspective"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Projects view * (value <code>"org.eclipse.jdt.ui.ProjectsView"</code>). * * @since 2.0 */ public static String ID_PROJECTS_VIEW= "org.eclipse.jdt.ui.ProjectsView"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Packages view * (value <code>"org.eclipse.jdt.ui.PackagesView"</code>). * * @since 2.0 */ public static String ID_PACKAGES_VIEW= "org.eclipse.jdt.ui.PackagesView"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Types view * (value <code>"org.eclipse.jdt.ui.TypesView"</code>). * * @since 2.0 */ public static String ID_TYPES_VIEW= "org.eclipse.jdt.ui.TypesView"; //$NON-NLS-1$ /** * The view part id of the Java Browsing Members view * (value <code>"org.eclipse.jdt.ui.MembersView"</code>). * * @since 2.0 */ public static String ID_MEMBERS_VIEW= "org.eclipse.jdt.ui.MembersView"; //$NON-NLS-1$ /** * The class org.eclipse.debug.core.model.IProcess allows attaching * String properties to processes. The Java UI contributes a property * page for IProcess that will show the contents of the property * with this key. * The intent of this property is to show the command line a process * was launched with. * @deprecated */ public final static String ATTR_CMDLINE= "org.eclipse.jdt.ui.launcher.cmdLine"; //$NON-NLS-1$ /** * Returns the shared images for the Java UI. * * @return the shared images manager */ public static ISharedImages getSharedImages() { if (fgSharedImages == null) fgSharedImages= new SharedImages(); return fgSharedImages; } /** * Creates a selection dialog that lists all packages of the given Java project. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected package (of type * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param project the Java project * @param style flags defining the style of the dialog; the valid flags are: * <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, indicating that * packages from binary package fragment roots should be included in addition * to those from source package fragment roots; * <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that * packages from required projects should be included as well. * @param filter the initial pattern to filter the set of packages. For example "com" shows * all packages starting with "com". The meta character '?' representing any character and * '*' representing any string are supported. Clients can pass an empty string if no filtering * is required. * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened * * @since 2.0 */ public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style, String filter) throws JavaModelException { Assert.isTrue((style | IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) == (IJavaElementSearchConstants.CONSIDER_BINARIES | IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS)); IPackageFragmentRoot[] roots= null; if ((style & IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS) != 0) { roots= project.getAllPackageFragmentRoots(); } else { roots= project.getPackageFragmentRoots(); } List consideredRoots= null; if ((style & IJavaElementSearchConstants.CONSIDER_BINARIES) != 0) { consideredRoots= Arrays.asList(roots); } else { consideredRoots= new ArrayList(roots.length); for (int i= 0; i < roots.length; i++) { IPackageFragmentRoot root= roots[i]; if (root.getKind() != IPackageFragmentRoot.K_BINARY) consideredRoots.add(root); } } int flags= JavaElementLabelProvider.SHOW_DEFAULT; if (consideredRoots.size() > 1) flags= flags | JavaElementLabelProvider.SHOW_ROOT; List packages= new ArrayList(); Iterator iter= consideredRoots.iterator(); while(iter.hasNext()) { IPackageFragmentRoot root= (IPackageFragmentRoot)iter.next(); packages.addAll(Arrays.asList(root.getChildren())); } ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(flags)); dialog.setIgnoreCase(false); dialog.setElements(packages.toArray()); // XXX inefficient dialog.setFilter(filter); return dialog; } /** * Creates a selection dialog that lists all packages of the given Java project. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected package (of type * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param project the Java project * @param style flags defining the style of the dialog; the valid flags are: * <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, indicating that * packages from binary package fragment roots should be included in addition * to those from source package fragment roots; * <code>IJavaElementSearchConstants.CONSIDER_REQUIRED_PROJECTS</code>, indicating that * packages from required projects should be included as well. * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createPackageDialog(Shell parent, IJavaProject project, int style) throws JavaModelException { return createPackageDialog(parent, project, style, ""); //$NON-NLS-1$ } /** * Creates a selection dialog that lists all packages under the given package * fragment root. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected package (of type * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param root the package fragment root * @param filter the initial pattern to filter the set of packages. For example "com" shows * all packages starting with "com". The meta character '?' representing any character and * '*' representing any string are supported. Clients can pass an empty string if no filtering * is required. * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened * * @since 2.0 */ public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root, String filter) throws JavaModelException { ElementListSelectionDialog dialog= new ElementListSelectionDialog(parent, new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setElements(root.getChildren()); dialog.setFilter(filter); return dialog; } /** * Creates a selection dialog that lists all packages under the given package * fragment root. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected package (of type * <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param root the package fragment root * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createPackageDialog(Shell parent, IPackageFragmentRoot root) throws JavaModelException { return createPackageDialog(parent, root, ""); //$NON-NLS-1$ } /** * Creates a selection dialog that lists all types in the given scope. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected type(s) (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param scope the scope that limits which types are included * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_CLASSES</code>, * <code>CONSIDER_INTERFACES</code>, or their bitwise OR * (equivalent to <code>CONSIDER_TYPES</code>) * @param multipleSelection <code>true</code> if multiple selection is allowed * @param filter the initial pattern to filter the set of types. For example "Abstract" shows * all types starting with "abstract". The meta character '?' representing any character and * '*' representing any string are supported. Clients can pass an empty string if no filtering * is required. * @exception JavaModelException if the selection dialog could not be opened * * @since 2.0 */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) throws JavaModelException { int elementKinds= 0; if (style == IJavaElementSearchConstants.CONSIDER_TYPES) { elementKinds= IJavaSearchConstants.TYPE; } else if (style == IJavaElementSearchConstants.CONSIDER_INTERFACES) { elementKinds= IJavaSearchConstants.INTERFACE; } else if (style == IJavaElementSearchConstants.CONSIDER_CLASSES) { elementKinds= IJavaSearchConstants.CLASS; } else { Assert.isTrue(false, "illegal style"); //$NON-NLS-1$ } if (multipleSelection) { MultiTypeSelectionDialog dialog= new MultiTypeSelectionDialog(parent, context, elementKinds, scope); dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$ dialog.setFilter(filter); return dialog; } else { TypeSelectionDialog dialog= new TypeSelectionDialog(parent, context, elementKinds, scope); dialog.setMessage(JavaUIMessages.getString("JavaUI.defaultDialogMessage")); //$NON-NLS-1$ dialog.setFilter(filter); return dialog; } } /** * Creates a selection dialog that lists all types in the given scope. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected type(s) (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param scope the scope that limits which types are included * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_CLASSES</code>, * <code>CONSIDER_INTERFACES</code>, or their bitwise OR * (equivalent to <code>CONSIDER_TYPES</code>) * @param multipleSelection <code>true</code> if multiple selection is allowed * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) throws JavaModelException { return createTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$ } /** * Creates a selection dialog that lists all types in the given scope containing * a standard <code>main</code> method. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected type(s) (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param scope the scope that limits which types are included * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, * <code>CONSIDER_EXTERNAL_JARS</code>, or their bitwise OR, or <code>0</code> * @param multipleSelection <code>true</code> if multiple selection is allowed * @param filter the initial pattern to filter the set of types containg a main method. For * example "App" shows all types starting with "app". The meta character '?' representing * any character and '*' representing any string are supported. Clients can pass an empty * string if no filtering is required. * @return a new selection dialog * * @since 2.0 */ public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection, String filter) { if (multipleSelection) { MultiMainTypeSelectionDialog dialog= new MultiMainTypeSelectionDialog(parent, context, scope, style); dialog.setFilter(filter); return dialog; } else { MainTypeSelectionDialog dialog= new MainTypeSelectionDialog(parent, context, scope, style); dialog.setFilter(filter); return dialog; } } /** * Creates a selection dialog that lists all types in the given scope containing * a standard <code>main</code> method. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected type(s) (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param scope the scope that limits which types are included * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_BINARIES</code>, * <code>CONSIDER_EXTERNAL_JARS</code>, or their bitwise OR, or <code>0</code> * @param multipleSelection <code>true</code> if multiple selection is allowed * @return a new selection dialog */ public static SelectionDialog createMainTypeDialog(Shell parent, IRunnableContext context, IJavaSearchScope scope, int style, boolean multipleSelection) { return createMainTypeDialog(parent, context, scope, style, multipleSelection, "");//$NON-NLS-1$ } /** * Creates a selection dialog that lists all types in the given project. * The caller is responsible for opening the dialog with <code>Window.open</code>, * and subsequently extracting the selected type(s) (of type * <code>IType</code>) via <code>SelectionDialog.getResult</code>. * * @param parent the parent shell of the dialog to be created * @param context the runnable context used to show progress when the dialog * is being populated * @param project the Java project * @param style flags defining the style of the dialog; the only valid values are * <code>IJavaElementSearchConstants.CONSIDER_CLASSES</code>, * <code>CONSIDER_INTERFACES</code>, or their bitwise OR * (equivalent to <code>CONSIDER_TYPES</code>) * @param multipleSelection <code>true</code> if multiple selection is allowed * @return a new selection dialog * @exception JavaModelException if the selection dialog could not be opened */ public static SelectionDialog createTypeDialog(Shell parent, IRunnableContext context, IProject project, int style, boolean multipleSelection) throws JavaModelException { IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaProject[] { JavaCore.create(project) }); return createTypeDialog(parent, context, scope, style, multipleSelection); } /** * Opens a Java editor on the given Java element. The element can be a compilation unit * or class file. If there already is an open Java editor for the given element, it is returned. * * @param element the input element; either a compilation unit * (<code>ICompilationUnit</code>) or a class file (</code>IClassFile</code>) * @return the editor, or </code>null</code> if wrong element type or opening failed * @exception PartInitException if the editor could not be initialized * @exception JavaModelException if this element does not exist or if an * exception occurs while accessing its underlying resource */ public static IEditorPart openInEditor(IJavaElement element) throws JavaModelException, PartInitException { return EditorUtility.openInEditor(element); } /** * Reveals the source range of the given source reference element in the * given editor. No checking is done if the editor displays a compilation unit or * class file that contains the given source reference. The editor simply reveals * the source range denoted by the given source reference. * * @param part the editor displaying the compilation unit or class file * @param element the source reference element defining the source range to be revealed * * @deprecated use <code>revealInEditor(IEditorPart, IJavaElement)</code> instead */ public static void revealInEditor(IEditorPart part, ISourceReference element) { if (element instanceof IJavaElement) revealInEditor(part, (IJavaElement) element); } /** * Reveals the given java element in the given editor. If the element is not an instance * of <code>ISourceReference</code> this method result in a NOP. If it is a source * reference no checking is done if the editor displays a compilation unit or class file that * contains the source reference element. The editor simply reveals the source range * denoted by the given element. * * @param part the editor displaying a compilation unit or class file * @param element the element to be revealed * * @since 2.0 */ public static void revealInEditor(IEditorPart part, IJavaElement element) { EditorUtility.revealInEditor(part, element); } /** * Returns the working copy manager for the Java UI plug-in. * * @return the working copy manager for the Java UI plug-in */ public static IWorkingCopyManager getWorkingCopyManager() { return JavaPlugin.getDefault().getWorkingCopyManager(); } /** * Answers the shared working copies currently registered for the Java plug-in. * * @return the list of shared working copies this plug-in * * @see org.eclipse.jdt.core.JavaCore#getSharedWorkingCopies(org.eclipse.jdt.core.IBufferFactory) * @since 2.0 */ public static IWorkingCopy[] getSharedWorkingCopies() { return JavaCore.getSharedWorkingCopies(getBufferFactory()); } /** * Returns the BufferFactory for the Java UI plug-in. * * @return the BufferFactory for the Java UI plug-in * * @see org.eclipse.jdt.core.IBufferFactory * @since 2.0 */ public static IBufferFactory getBufferFactory() { CompilationUnitDocumentProvider provider= JavaPlugin.getDefault().getCompilationUnitDocumentProvider(); if (provider != null) return provider.getBufferFactory(); return null; } /** * Returns the DocumentProvider used for Java compilation units. * * @return the DocumentProvider for Java compilation units. * * @see IDocumentProvider * @since 2.0 */ public static IDocumentProvider getDocumentProvider() { return JavaPlugin.getDefault().getCompilationUnitDocumentProvider(); } /** * Sets the Javadoc location for an archive with the given path. * * @param archivePath the path of the library; this can be an workspace path * or an external path in case of an external library. * @param url The Javadoc location to set. This location should contain index.html and * a file 'package-list'. <code>null</code> clears the current documentation * location. * * @since 2.0 */ public static void setLibraryJavadocLocation(IPath archivePath, URL url) { JavaDocLocations.setLibraryJavadocLocation(archivePath, url); } /** * Returns the Javadoc location for an archive or <code>null</code> if no * location is available. * * @param archivePath the path of the library. This can be an workspace path * or an external path in case of an external library. * * @since 2.0 */ public static URL getLibraryJavadocLocation(IPath archivePath) { return JavaDocLocations.getLibraryJavadocLocation(archivePath); } /** * Sets the Javadoc location for a Java project. This location is used for * all types located in the project's source folders. * * @param project the project * @param url The Javadoc location to set. This location should contain index.html and * a file 'package-list'. <code>null</code> clears the current documentation * location. * * @since 2.1 */ public static void setProjectJavadocLocation(IJavaProject project, URL url) { JavaDocLocations.setProjectJavadocLocation(project, url); } /** * Returns the Javadoc location for a Java project or <code>null</code> if no * location is available. This location is used for all types located in the project's * source folders. * * @param project the project * * @since 2.1 */ public static URL getProjectJavadocLocation(IJavaProject project) { return JavaDocLocations.getProjectJavadocLocation(project); } /** * Returns the Javadoc base URL for an element. The base location contains the * index file. This location doesn't have to exist. Returns * <code>null</code> if no javadoc location has been attached to the * element's library or project. Example of a returned URL is <i>http://www. * junit. org/junit/javadoc</i>. * * @param The element for which the doc URL is requested. * * @since 2.0 */ public static URL getJavadocBaseLocation(IJavaElement element) throws JavaModelException { return JavaDocLocations.getJavadocBaseLocation(element); } /** * Returns the Javadoc URL for an element. Example of a returned URL is * <i>http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html</i>. * This returned location doesn't have to exist. Returns <code>null</code> * if no javadoc location has been attached to the element's library or * project. * * @param The element for which the doc URL is requested. * @param includeAnchor If set, the URL contains an anchor for member references: * <i>http://www.junit.org/junit/javadoc/junit/extensions/TestSetup.html#run(junit.framework.TestResult)</i>. Note * that this involves type resolving and is a more expensive call than without anchor. * * @since 2.0 */ public static URL getJavadocLocation(IJavaElement element, boolean includeAnchor) throws JavaModelException { return JavaDocLocations.getJavadocLocation(element, includeAnchor); } }
15,654
Bug 15654 Can't maximize Compare with Local History window
Build M5 When you select 'Compare with Local History' the dialog box which appears is resizable but not maximizable. If I can resize the window I ought to be able to maximize it, as well.
resolved fixed
c7ca379
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T23:26:15Z
2002-05-09T18:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/CompareDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.compare; import java.util.ResourceBundle; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.dialogs.*; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.compare.*; import org.eclipse.compare.structuremergeviewer.ICompareInput; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; class CompareDialog extends ResizableDialog { class ViewerSwitchingPane extends CompareViewerSwitchingPane { ViewerSwitchingPane(Composite parent, int style) { super(parent, style, false); } protected Viewer getViewer(Viewer oldViewer, Object input) { if (input instanceof ICompareInput) return CompareUI.findContentViewer(oldViewer, (ICompareInput)input, this, fCompareConfiguration); return null; } public void setImage(Image image) { // don't show icon } } private CompareViewerSwitchingPane fContentPane; private CompareConfiguration fCompareConfiguration; private ICompareInput fInput; CompareDialog(Shell parent, ResourceBundle bundle) { super(parent, bundle); fCompareConfiguration= new CompareConfiguration(); fCompareConfiguration.setLeftEditable(false); fCompareConfiguration.setRightEditable(false); } void compare(ICompareInput input) { fInput= input; fCompareConfiguration.setLeftLabel(fInput.getLeft().getName()); fCompareConfiguration.setLeftImage(fInput.getLeft().getImage()); fCompareConfiguration.setRightLabel(fInput.getRight().getName()); fCompareConfiguration.setRightImage(fInput.getRight().getImage()); if (fContentPane != null) fContentPane.setInput(fInput); open(); } /* (non Javadoc) * Creates SWT control tree. */ protected synchronized Control createDialogArea(Composite parent) { getShell().setText(JavaCompareUtilities.getString(fBundle, "title")); //$NON-NLS-1$ fContentPane= new ViewerSwitchingPane(parent, SWT.BORDER | SWT.FLAT); fContentPane.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_VERTICAL)); if (fInput != null) fContentPane.setInput(fInput); return fContentPane; } /* (non-Javadoc) * Method declared on Dialog. */ protected void createButtonsForButtonBar(Composite parent) { String buttonLabel= JavaCompareUtilities.getString(fBundle, "buttonLabel", IDialogConstants.OK_LABEL); //$NON-NLS-1$ createButton(parent, IDialogConstants.CANCEL_ID, buttonLabel, false); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.COMPARE_DIALOG); } }
15,654
Bug 15654 Can't maximize Compare with Local History window
Build M5 When you select 'Compare with Local History' the dialog box which appears is resizable but not maximizable. If I can resize the window I ought to be able to maximize it, as well.
resolved fixed
c7ca379
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-15T23:26:15Z
2002-05-09T18:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/compare/ResizableDialog.java
package org.eclipse.jdt.internal.ui.compare; import java.util.ResourceBundle; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.graphics.*; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.DialogSettings; import org.eclipse.compare.CompareUI; /** * Base class for resizable Dialogs with persistent window bounds. */ public abstract class ResizableDialog extends Dialog { // dialog store id constants private final static String DIALOG_BOUNDS_KEY= "ResizableDialogBounds"; //$NON-NLS-1$ private static final String X= "x"; //$NON-NLS-1$ private static final String Y= "y"; //$NON-NLS-1$ private static final String WIDTH= "width"; //$NON-NLS-1$ private static final String HEIGHT= "height"; //$NON-NLS-1$ protected ResourceBundle fBundle; private Rectangle fNewBounds; private IDialogSettings fSettings; public ResizableDialog(Shell parent, ResourceBundle bundle) { super(parent); setShellStyle(getShellStyle() | SWT.RESIZE); fBundle= bundle; fSettings= CompareUI.getPlugin().getDialogSettings(); } protected Point getInitialSize() { int width= 0; int height= 0; final Shell s= getShell(); if (s != null) { s.addControlListener( new ControlListener() { public void controlMoved(ControlEvent arg0) { fNewBounds= s.getBounds(); } public void controlResized(ControlEvent arg0) { fNewBounds= s.getBounds(); } } ); } IDialogSettings bounds= fSettings.getSection(DIALOG_BOUNDS_KEY); //$NON-NLS-1$ if (bounds == null) { if (fBundle != null) { width= JavaCompareUtilities.getInteger(fBundle, WIDTH, 0); height= JavaCompareUtilities.getInteger(fBundle, HEIGHT, 0); Shell shell= getParentShell(); if (shell != null) { Point parentSize= shell.getSize(); if (width <= 0) width= parentSize.x-300; if (height <= 0) height= parentSize.y-200; } } else { Shell shell= getParentShell(); if (shell != null) { Point parentSize= shell.getSize(); width= parentSize.x-100; height= parentSize.y-100; } } if (width < 700) width= 700; if (height < 500) height= 500; } else { try { width= bounds.getInt(WIDTH); } catch (NumberFormatException e) { width= 700; } try { height= bounds.getInt(HEIGHT); } catch (NumberFormatException e) { height= 500; } } return new Point(width, height); } protected Point getInitialLocation(Point initialSize) { Point loc= super.getInitialLocation(initialSize); IDialogSettings bounds= fSettings.getSection(DIALOG_BOUNDS_KEY); if (bounds != null) { try { loc.x= bounds.getInt(X); } catch (NumberFormatException e) { } try { loc.y= bounds.getInt(Y); } catch (NumberFormatException e) { } } return loc; } public boolean close() { boolean closed= super.close(); if (closed && fNewBounds != null) saveBounds(fNewBounds); return closed; } private void saveBounds(Rectangle bounds) { IDialogSettings dialogBounds= fSettings.getSection(DIALOG_BOUNDS_KEY); if (dialogBounds == null) { dialogBounds= new DialogSettings(DIALOG_BOUNDS_KEY); fSettings.addSection(dialogBounds); } dialogBounds.put(X, bounds.x); dialogBounds.put(Y, bounds.y); dialogBounds.put(WIDTH, bounds.width); dialogBounds.put(HEIGHT, bounds.height); } }
3,510
Bug 3510 Move Destination shows empty folders as packages (1G46Z2X)
The move destination shows empty folders as packages whereas the packages viewer doesn't. The UI should be consistent in this matter. Steps to reproduce: 1.) create a new source folder 2.) create a package a.b.c.d in the source folder 3.) Select move from context menu. The move destination dialog shows the following packages a a.b a.b.c a.b.c.d NOTES: EG (11/13/00 2:45:49 PM) no, you can move a package into an empty package. Veto if you disagree. EG (12/5/2000 5:04:11 PM) fixed the empty folder are now shown as folders and not packages MA (14.12.00 15:40:51) the destination dialog does not offer the project itself as a destination for the resource. you can however select the default package as destination, which results in having a file in the project i think the whole thing is still a bit too confusing. moved to inbox
verified fixed
3324ea5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T09:50:25Z
2001-10-11T03:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddDelegateMethodsAction.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * Martin Moebius * *****************************************************************************/ package org.eclipse.jdt.ui.actions; import java.lang.reflect.InvocationTargetException; import java.text.Collator; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeMap; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.JdtFlags; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.ActionUtil; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.ElementValidator; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableContext; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.help.WorkbenchHelp; /** * Creates delegate methods for a type's fields. Opens a dialog with a list of * fields for which delegate methods can be generated. User is able to check or * uncheck items before methods are generated. * <p> * Will open the parent compilation unit in a Java editor. The result is * unsaved, so the user can decide if the changes are acceptable. * <p> * The action is applicable to structured selections containing elements * of type <code>IField</code> or <code>IType</code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.1 */ public class AddDelegateMethodsAction extends SelectionDispatchAction { private static boolean fgReplaceFlag = false; private static boolean fgOverrideFinalsFlag = false; private static final String DIALOG_TITLE = ActionMessages.getString("AddDelegateMethodsAction.error.title"); //$NON-NLS-1$ private CompilationUnitEditor fEditor; /** * Creates a new <code>AddDelegateMethodsAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public AddDelegateMethodsAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("AddDelegateMethodsAction.label")); //$NON-NLS-1$ setDescription(ActionMessages.getString("AddDelegateMethodsAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("AddDelegateMethodsAction.tooltip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_DELEGATE_METHODS_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public AddDelegateMethodsAction(CompilationUnitEditor editor) { this(editor.getEditorSite()); fEditor = editor; setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null); } //---- Structured Viewer ----------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void selectionChanged(IStructuredSelection selection) { try { setEnabled(canEnable(selection)); } catch (JavaModelException e) { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 if (JavaModelUtil.filterNotPresentException(e)) JavaPlugin.log(e); setEnabled(false); } } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(IStructuredSelection selection) { try { IField[] selectedFields = getSelectedFields(selection); if (canEnableOn(selectedFields)) { run(selectedFields[0].getDeclaringType(), selectedFields, false); return; } Object firstElement = selection.getFirstElement(); if (firstElement instanceof IType) run((IType) firstElement, new IField[0], false); else if (firstElement instanceof ICompilationUnit) run(JavaElementUtil.getMainType((ICompilationUnit) firstElement), new IField[0], false); } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } } private boolean canEnable(IStructuredSelection selection) throws JavaModelException { if (canEnableOn(getSelectedFields(selection))) return true; if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) return canEnableOn((IType) selection.getFirstElement()); if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit)) return canEnableOn(JavaElementUtil.getMainType((ICompilationUnit) selection.getFirstElement())); return false; } private static boolean canEnableOn(IType type) throws JavaModelException { if (type == null || type.getCompilationUnit() == null) return false; return canEnableOn(type.getFields()); } private static boolean canEnableOn(IField[] fields) throws JavaModelException { if (fields == null) { return false; } int count = 0; for (int i = 0; i < fields.length; i++) { if (!hasPrimitiveType(fields[i])) { count++; } } return (count > 0); } /* * Returns fields in the selection or <code>null</code> if the selection is * empty or not valid. */ private IField[] getSelectedFields(IStructuredSelection selection) { List elements = selection.toList(); int nElements = elements.size(); if (nElements > 0) { IField[] res = new IField[nElements]; ICompilationUnit cu = null; for (int i = 0; i < nElements; i++) { Object curr = elements.get(i); if (curr instanceof IField) { IField fld = (IField) curr; if (i == 0) { // remember the cu of the first element cu = fld.getCompilationUnit(); if (cu == null) { return null; } } else if (!cu.equals(fld.getCompilationUnit())) { // all fields must be in the same CU return null; } try { if (fld.getDeclaringType().isInterface()) { // no delegates for fields in interfaces or fields with return null; } } catch (JavaModelException e) { JavaPlugin.log(e); return null; } res[i] = fld; } else { return null; } } return res; } return null; } private void run(IType type, IField[] preselected, boolean editor) throws CoreException { if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor)) return; if (!ActionUtil.isProcessable(getShell(), type)) return; showUI(type, preselected); } //---- Java Editior -------------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void selectionChanged(ITextSelection selection) { } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(ITextSelection selection) { try { IJavaElement input= SelectionConverter.getInput(fEditor); if (!ActionUtil.isProcessable(getShell(), input)) return; IJavaElement[] elements = SelectionConverter.codeResolve(fEditor); if (elements.length == 1 && (elements[0] instanceof IField)) { IField field = (IField) elements[0]; run(field.getDeclaringType(), new IField[] { field }, true); return; } IJavaElement element = SelectionConverter.getElementAtOffset(fEditor); if (element != null) { IType type = (IType) element.getAncestor(IJavaElement.TYPE); if (type != null) { if (type.getFields().length > 0) { run(type, new IField[0], true); return; } } } MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$ } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } } //---- Helpers ------------------------------------------------------------------- /**build ui */ private void showUI(IType type, IField[] preselected) { try { FieldContentProvider provider = new FieldContentProvider(type); Methods2FieldLabelProvider methodLabel = new Methods2FieldLabelProvider(); CheckedTreeSelectionDialog dialog = new CheckedTreeSelectionDialog(getShell(), methodLabel, provider); dialog.setValidator(new ISelectionStatusValidator() { public IStatus validate(Object[] selection) { StatusInfo state = new StatusInfo(); if (selection != null && selection.length > 0) { HashSet map = new HashSet(selection.length); int count = 0; for (int i = 0; i < selection.length; i++) { Object key = selection[i]; if (selection[i] instanceof Methods2Field) { count++; try { key = createSignatureKey(((Methods2Field) selection[i]).fMethod); } catch (JavaModelException e) { return new StatusInfo(StatusInfo.ERROR, e.toString()); } } if (!map.add(key)) { //$NON-NLS-1$ state = new StatusInfo(IStatus.ERROR, ActionMessages.getString("AddDelegateMethodsAction.duplicate_methods")); //$NON-NLS-1$ break; } else { String message; if (count == 1) { message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.one", String.valueOf(count)); //$NON-NLS-1$ } else { message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.more", String.valueOf(count)); //$NON-NLS-1$ } state = new StatusInfo(IStatus.INFO, message); } } } return state; } }); dialog.setSorter(new Methods2FieldSorter()); dialog.setInput(provider); dialog.setContainerMode(true); dialog.setMessage(ActionMessages.getString("AddDelegateMethodsAction.message")); //$NON-NLS-1$ dialog.setTitle(ActionMessages.getString("AddDelegateMethodsAction.title")); //$NON-NLS-1$ dialog.setExpandedElements(preselected); int result = dialog.open(); if (result == Window.OK) { Object[] o = dialog.getResult(); if (o == null) return; ArrayList methods = new ArrayList(o.length); for (int i = 0; i < o.length; i++) { if (o[i] instanceof Methods2Field) methods.add(o[i]); } IEditorPart part = EditorUtility.openInEditor(type); type = (IType) JavaModelUtil.toWorkingCopy(type); IMethod[] createdMethods = processResults(methods, type); if (createdMethods != null && createdMethods.length > 0) { EditorUtility.revealInEditor(part, createdMethods[0]); } } } catch (CoreException e) { ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } catch (InvocationTargetException e) { ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$ } } /**Runnable for the operation*/ private static class ResultRunner implements IWorkspaceRunnable { /**List with Methods2Field*/ List fList = null; /**Type to add methods to*/ IType fType = null; ArrayList fCreatedMethods; public ResultRunner(List resultList, IType type) { fList = resultList; fType = type; fCreatedMethods = new ArrayList(); } public IMethod[] getCreatedMethods() { return (IMethod[]) fCreatedMethods.toArray(new IMethod[fCreatedMethods.size()]); } public void run(IProgressMonitor monitor) throws CoreException { String message = ActionMessages.getFormattedString("AddDelegateMethodsAction.monitor.message", String.valueOf(fList.size())); //$NON-NLS-1$ monitor.beginTask(message, fList.size()); // the preferences CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(); boolean addComments = settings.createComments; // already existing methods IMethod[] existingMethods = fType.getMethods(); //the delemiter used String lineDelim = StubUtility.getLineDelimiterUsed(fType); // the indent used + 1 int indent = StubUtility.getIndentUsed(fType) + 1; // perhaps we have to add import statements final ImportsStructure imports = new ImportsStructure(fType.getCompilationUnit(), settings.importOrder, settings.importThreshold, true); for (int i = 0; i < fList.size(); i++) { //long time=System.currentTimeMillis(); //check for cancel each iteration if (monitor.isCanceled()) { if (i > 0) { imports.create(false, null); } return; } ITypeHierarchy typeHierarchy = fType.newSupertypeHierarchy(null); String content = null; Methods2Field wrapper = (Methods2Field) fList.get(i); IMethod curr = wrapper.fMethod; IField field = wrapper.fField; IMethod overwrittenMethod = JavaModelUtil.findMethodImplementationInHierarchy( typeHierarchy, fType, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); if (overwrittenMethod == null) { content = createStub(field, curr, addComments, overwrittenMethod, imports); } else { int flags = overwrittenMethod.getFlags(); if (Flags.isFinal(flags) || Flags.isPrivate(flags)) { // we could ask before overwriting final methods if (fgOverrideFinalsFlag) { System.out.println("method final"); //$NON-NLS-1$ System.out.println(overwrittenMethod); } } IMethod declaration = JavaModelUtil.findMethodDeclarationInHierarchy( typeHierarchy, fType, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); content = createStub(field, declaration, addComments, overwrittenMethod, imports); } IJavaElement sibling = null; IMethod existing = JavaModelUtil.findMethod( curr.getElementName(), curr.getParameterTypes(), curr.isConstructor(), existingMethods); if (existing != null) { // we could ask before replacing a method if (fgReplaceFlag) { System.out.println("method does already exists"); //$NON-NLS-1$ System.out.println(existing); sibling = StubUtility.findNextSibling(existing); existing.delete(false, null); } else { continue; } } else if (curr.isConstructor() && existingMethods.length > 0) { // add constructors at the beginning sibling = existingMethods[0]; } String formattedContent = StubUtility.codeFormat(content, indent, lineDelim) + lineDelim; IMethod created = fType.createMethod(formattedContent, sibling, true, null); fCreatedMethods.add(created); monitor.worked(1); //System.out.println(System.currentTimeMillis()-time +" for #"+i); } imports.create(false, null); } private String createStub( IField field, IMethod curr, boolean addComment, IMethod overridden, IImportsStructure imports) throws CoreException { String methodName = curr.getElementName(); String[] paramNames = curr.getParameterNames(); String returnTypSig = curr.getReturnType(); StringBuffer buf = new StringBuffer(); if (addComment) { String comment = StubUtility.getMethodComment( fType.getCompilationUnit(), fType.getElementName(), methodName, paramNames, curr.getExceptionTypes(), returnTypSig, overridden); if (comment != null) { buf.append(comment); } } String methodDeclaration = null; if (fType.isClass()) { StringBuffer body = new StringBuffer(); if (!Signature.SIG_VOID.equals(returnTypSig)) { body.append("return "); //$NON-NLS-1$ } if (JdtFlags.isStatic(curr)) { body.append(resolveTypeOfField(field).getElementName()); } else { body.append(field.getElementName()); } body.append('.').append(methodName).append('('); for (int i = 0; i < paramNames.length; i++) { body.append(paramNames[i]); if (i < paramNames.length - 1) body.append(','); } body.append(");"); //$NON-NLS-1$ methodDeclaration = body.toString(); } StubUtility.genMethodDeclaration(fType.getElementName(), curr, methodDeclaration, imports, buf); return buf.toString(); } } /**creates methods in class*/ private IMethod[] processResults(List list, IType type) throws InvocationTargetException { if (list.size() == 0) return null; ResultRunner resultRunner = new ResultRunner(list, type); IRunnableContext runnableContext = new ProgressMonitorDialog(getShell()); try { runnableContext.run(false, true, new WorkbenchRunnableAdapter(resultRunner)); } catch (InterruptedException e) { // cancel pressed return null; } return resultRunner.getCreatedMethods(); } /** The model (content provider) for the field-methods tree */ private static class FieldContentProvider implements ITreeContentProvider { private TreeMap fTreeMap = null; private HashMap fFieldMap = null; private HashMap fFilter = null; /** * Method FieldContentProvider. * @param type outer type to insert in (hide final methods in tree)) */ FieldContentProvider(IType type) throws JavaModelException { //hiding final methods fFilter = new HashMap(); //mapping name to methods fTreeMap = new TreeMap(); //mapping name to field fFieldMap = new HashMap(); buildModel(type); } private void buildModel(IType type) throws JavaModelException { IField[] fields = type.getFields(); //build map to filter against IMethod[] finMeths = resolveFinalMethods(type); for (int i = 0; i < finMeths.length; i++) { fFilter.put(createSignatureKey(finMeths[i]), finMeths[i]); } IMethod[] filter = type.getMethods(); for (int i = 0; i < filter.length; i++) { fFilter.put(createSignatureKey(filter[i]), filter[i]); } for (int i = 0; i < fields.length; i++) { IType fieldType = resolveTypeOfField(fields[i]); if (fieldType == null) continue; IMethod[] methods = resolveMethodsHierarchy(fieldType); ArrayList accessMethods = new ArrayList(); //show public methods; hide constructors + final methods for (int j = 0; j < methods.length; j++) { boolean publicField = Flags.isPublic(methods[j].getFlags()); boolean constructor = methods[j].isConstructor(); boolean finalExist = fFilter.get(createSignatureKey(methods[j])) != null; if (publicField && !constructor && !finalExist) accessMethods.add(new Methods2Field(methods[j], fields[i])); } Object[] m = accessMethods.toArray(); Methods2Field[] mf = new Methods2Field[m.length]; for (int j = 0; j < m.length; j++) { mf[j] = (Methods2Field) m[j]; } fTreeMap.put(fields[i].getElementName(), mf); fFieldMap.put(fields[i].getElementName(), fields[i]); } } public Object[] getChildren(Object parentElement) { if (parentElement instanceof IField) { return (Object[]) fTreeMap.get(((IField) parentElement).getElementName()); } return null; } public Object getParent(Object element) { return null; } public boolean hasChildren(Object element) { return element instanceof IField ? true : false; } public Object[] getElements(Object inputElement) { if ((inputElement != null) && (inputElement instanceof FieldContentProvider)) { Set set = fTreeMap.keySet(); Object[] o = set.toArray(); Object[] fields = new Object[o.length]; for (int i = 0; i < o.length; i++) { fields[i] = fFieldMap.get(o[i]); } return fields; } return null; } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } /**to map from dialog results to corresponding fields*/ private static class Methods2Field { public Methods2Field(IMethod method, IField field) { fMethod = method; fField = field; } /**method to wrap*/ IMethod fMethod = null; /**field where method is declared*/ IField fField = null; } /**just to wrap JavaElementLabelProvider using my Methods2Field*/ private static class Methods2FieldLabelProvider implements ILabelProvider { /**Delegate to forward calls*/ JavaElementLabelProvider fMethodLabel = null; public Methods2FieldLabelProvider() { fMethodLabel = new JavaElementLabelProvider(); fMethodLabel.turnOn(JavaElementLabelProvider.SHOW_TYPE); } public Image getImage(Object element) { if (element instanceof Methods2Field) { Methods2Field wrapper = (Methods2Field) element; return fMethodLabel.getImage(wrapper.fMethod); } else if (element instanceof IJavaElement) { return fMethodLabel.getImage(element); } return null; } public String getText(Object element) { if (element instanceof Methods2Field) { Methods2Field wrapper = (Methods2Field) element; return fMethodLabel.getText(wrapper.fMethod); } else if (element instanceof IJavaElement) { return fMethodLabel.getText(element); } return null; } public void addListener(ILabelProviderListener listener) { fMethodLabel.addListener(listener); } public void dispose() { fMethodLabel.dispose(); } public boolean isLabelProperty(Object element, String property) { return fMethodLabel.isLabelProperty(element, property); } public void removeListener(ILabelProviderListener listener) { fMethodLabel.removeListener(listener); } } /** and a delegate for the sorter*/ private static class Methods2FieldSorter extends ViewerSorter { JavaElementSorter fSorter = new JavaElementSorter(); public int category(Object element) { if (element instanceof Methods2Field) element = ((Methods2Field) element).fMethod; return fSorter.category(element); } public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof Methods2Field) e1 = ((Methods2Field) e1).fMethod; if (e2 instanceof Methods2Field) e2 = ((Methods2Field) e2).fMethod; return fSorter.compare(viewer, e1, e2); } public Collator getCollator() { return fSorter.getCollator(); } } /**return all methods of all super types, minus dups*/ private static IMethod[] resolveMethodsHierarchy(IType type) throws JavaModelException { HashMap map = new HashMap(); ITypeHierarchy hierarchy = type.newSupertypeHierarchy(null); IType[] types = hierarchy.getAllTypes(); for (int i = 0; i < types.length; i++) { IMethod[] methods = types[i].getMethods(); for (int j = 0; j < methods.length; j++) { map.put(createSignatureKey(methods[j]), methods[j]); } } ArrayList list = new ArrayList(); list.addAll(map.values()); IMethod[] methods = new IMethod[list.size()]; for (int i = 0; i < methods.length; i++) { methods[i] = (IMethod) list.get(i); } return methods; } /**returns a non null array of final methods of the type*/ private static IMethod[] resolveFinalMethods(IType type) throws JavaModelException { //Interfaces are java.lang.Objects if (type.isInterface()) { type = JavaModelUtil.findType(type.getJavaProject(), "java.lang.Object"); //$NON-NLS-1$ } IMethod[] methods = resolveMethodsHierarchy(type); ArrayList list = new ArrayList(methods.length); for (int i = 0; i < methods.length; i++) { boolean isFinal = Flags.isFinal(methods[i].getFlags()); if (isFinal) list.add(methods[i]); } IMethod[] finalMethods = new IMethod[list.size()]; for (int i = 0; i < finalMethods.length; i++) { finalMethods[i] = (IMethod) list.get(i); } return finalMethods; } /**creates a key used for hashmaps for a method signature (name+arguments(fqn))*/ private static String createSignatureKey(IMethod method) throws JavaModelException { StringBuffer buffer = new StringBuffer(); buffer.append(method.getElementName()); String[] args = method.getParameterTypes(); for (int i = 0; i < args.length; i++) { String signature; if (isUnresolved(args[i])) { int acount = Signature.getArrayCount(args[i]); if (acount > 0) { String arg = args[i]; int index = arg.lastIndexOf(Signature.C_ARRAY); arg = arg.substring(index + 1); signature = Signature.toString(arg); } else { signature = Signature.toString(args[i]); } String[][] fqn = method.getDeclaringType().resolveType(signature); if (fqn != null) { buffer.append(fqn[0][0]).append('.').append(fqn[0][1]); //TODO check for [][] for (int j = 0; j < acount; j++) { buffer.append("[]"); //$NON-NLS-1$ } } }else{ signature=Signature.toString(args[i]); buffer.append(signature); } } return buffer.toString(); } private static boolean isUnresolved(String signature) { boolean flag = false; char c=Signature.getElementType(signature).charAt(0); boolean primitive=(c!= Signature.C_RESOLVED && c != Signature.C_UNRESOLVED); if(primitive) return flag; int acount = Signature.getArrayCount(signature); if (acount > 0) { int index = signature.lastIndexOf(Signature.C_ARRAY); c = signature.charAt(index + 1); } else { c = signature.charAt(0); } switch (c) { case Signature.C_RESOLVED : flag=false; break; case Signature.C_UNRESOLVED : flag=true; break; default : throw new IllegalArgumentException(); } return flag; } private static boolean hasPrimitiveType(IField field) throws JavaModelException { String signature = field.getTypeSignature(); char first = Signature.getElementType(signature).charAt(0); return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); } /** * returns Type of field. * * if field is primitve null is returned. * if field is array java.lang.Object is returned. **/ private static IType resolveTypeOfField(IField field) throws JavaModelException { boolean isPrimitive = hasPrimitiveType(field); boolean isArray = Signature.getArrayCount(field.getTypeSignature()) > 0; if (!isPrimitive && !isArray) { String typeName = JavaModelUtil.getResolvedTypeName(field.getTypeSignature(), field.getDeclaringType()); //if the cu has errors its possible no type name is resolved IType type = typeName != null ? field.getJavaProject().findType(typeName) : null; return type; } else if (isArray) { return JavaModelUtil.findType(field.getJavaProject(), "java.lang.Object"); //$NON-NLS-1$ } return null; } }
31,865
Bug 31865 Package Explorer: Cannot search for references in workspace
Build 20030213 1. Create class X with method foo 2. In Package Explorer, select foo 3. Right click, select References in the pop up menu Observe: The sub-menu contains only working sets. The other entries (Workspace, Hierarchy, Working Set...) have disappeared.
resolved fixed
bade459
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T10:27:28Z
2003-02-14T13:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemTableViewer.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.viewsupport; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IResource; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.ui.IWorkingCopyProvider; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent; import org.eclipse.jdt.internal.ui.util.SelectionUtil; /** * Extends a TableViewer to allow more performance when showing error ticks. * A <code>ProblemItemMapper</code> is contained that maps all items in * the tree to underlying resource */ public class ProblemTableViewer extends TableViewer { protected ResourceToItemsMapper fResourceToItemsMapper; /** * Constructor for ProblemTableViewer. * @param parent */ public ProblemTableViewer(Composite parent) { super(parent); initMapper(); } /** * Constructor for ProblemTableViewer. * @param parent * @param style */ public ProblemTableViewer(Composite parent, int style) { super(parent, style); initMapper(); } /** * Constructor for ProblemTableViewer. * @param table */ public ProblemTableViewer(Table table) { super(table); initMapper(); } private void initMapper() { fResourceToItemsMapper= new ResourceToItemsMapper(this); } /* * @see StructuredViewer#mapElement(Object, Widget) */ protected void mapElement(Object element, Widget item) { super.mapElement(element, item); if (item instanceof Item) { fResourceToItemsMapper.addToMap(element, (Item) item); } } /* * @see StructuredViewer#unmapElement(Object, Widget) */ protected void unmapElement(Object element, Widget item) { if (item instanceof Item) { fResourceToItemsMapper.removeFromMap(element, (Item) item); } super.unmapElement(element, item); } /* * @see StructuredViewer#unmapAllElements() */ protected void unmapAllElements() { fResourceToItemsMapper.clearMap(); super.unmapAllElements(); } /* * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) */ protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { if (event instanceof ProblemsLabelChangedEvent) { ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; if (!e.isMarkerChange() && !isShowingWorkingCopies()) { return; } } Object[] changed= event.getElements(); if (changed != null && !fResourceToItemsMapper.isEmpty()) { ArrayList others= new ArrayList(changed.length); for (int i= 0; i < changed.length; i++) { Object curr= changed[i]; if (curr instanceof IResource) { fResourceToItemsMapper.resourceChanged((IResource) curr); } else { others.add(curr); } } if (others.isEmpty()) { return; } event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), others.toArray()); } super.handleLabelProviderChanged(event); } /** * @see StructuredViewer#handleInvalidSelection(ISelection, ISelection) */ protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { ISelection validNewSelection= getValidSelection(newSelection); if (isShowingWorkingCopies()) { // Convert to and from working copies if (invalidSelection instanceof IStructuredSelection) { IStructuredSelection structSel= (IStructuredSelection)invalidSelection; List elementsToSelect= new ArrayList(structSel.size()); Iterator iter= structSel.iterator(); while (iter.hasNext()) { Object element= iter.next(); if (element instanceof IJavaElement) { IJavaElement je= convertToValidElement((IJavaElement)element); if (je != null) elementsToSelect.add(je); } } if (!elementsToSelect.isEmpty()) { List alreadySelected= SelectionUtil.toList(validNewSelection); if (alreadySelected != null && !alreadySelected.isEmpty()) elementsToSelect.addAll(SelectionUtil.toList(validNewSelection)); validNewSelection= new StructuredSelection(elementsToSelect); } } } if (validNewSelection != newSelection) setSelection(validNewSelection); super.handleInvalidSelection(invalidSelection, validNewSelection); } /* * Returns a selection which does not contain non-existing * Java elements. If all elements are ok then the original * selection is returned unchanged. */ private ISelection getValidSelection(ISelection selection) { List selectedElements= SelectionUtil.toList(selection); if (selectedElements == null || selectedElements.isEmpty()) return selection; boolean selectionChanged= false; List validElementsToSelect= new ArrayList(selectedElements.size()); Iterator iter= selectedElements.iterator(); while (iter.hasNext()) { Object element= iter.next(); if (element instanceof IJavaElement) { IJavaElement je= (IJavaElement)element; if (je != null && je.exists()) validElementsToSelect.add(je); else selectionChanged= true; } else { validElementsToSelect.add(element); } } if (selectionChanged) return new StructuredSelection(validElementsToSelect); else return selection; } /** * Converts a working copy (element) to a cu (element) * or vice-versa. * * @return the converted Java element or <code>null</code> if the conversion fails */ private IJavaElement convertToValidElement(IJavaElement je) { ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT); IJavaElement convertedJE= null; if (cu == null) return null; if (cu.isWorkingCopy()) convertedJE= cu.getOriginal(je); else { IWorkingCopy wc= (IWorkingCopy)cu.findSharedWorkingCopy(JavaUI.getBufferFactory()); if (wc != null) { IJavaElement[] matches= wc.findElements(je); if (matches != null && matches.length > 0) convertedJE= matches[0]; } } if (convertedJE != null && convertedJE.exists()) return convertedJE; else return null; } /** * Answers whether this viewer shows working copies or not. * * @return <code>true</code> if this viewer shows working copies */ private boolean isShowingWorkingCopies() { Object contentProvider= getContentProvider(); return contentProvider instanceof IWorkingCopyProvider && ((IWorkingCopyProvider)contentProvider).providesWorkingCopies(); } }
31,865
Bug 31865 Package Explorer: Cannot search for references in workspace
Build 20030213 1. Create class X with method foo 2. In Package Explorer, select foo 3. Right click, select References in the pop up menu Observe: The sub-menu contains only working sets. The other entries (Workspace, Hierarchy, Working Set...) have disappeared.
resolved fixed
bade459
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T10:27:28Z
2003-02-14T13:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemTreeViewer.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.viewsupport; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IResource; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Tree; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.ui.IWorkingCopyProvider; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent; import org.eclipse.jdt.internal.ui.util.SelectionUtil; /** * Extends a TreeViewer to allow more performance when showing error ticks. * A <code>ProblemItemMapper</code> is contained that maps all items in * the tree to underlying resource */ public class ProblemTreeViewer extends TreeViewer { protected ResourceToItemsMapper fResourceToItemsMapper; /* * @see TreeViewer#TreeViewer(Composite) */ public ProblemTreeViewer(Composite parent) { super(parent); initMapper(); } /* * @see TreeViewer#TreeViewer(Composite, int) */ public ProblemTreeViewer(Composite parent, int style) { super(parent, style); initMapper(); } /* * @see TreeViewer#TreeViewer(Tree) */ public ProblemTreeViewer(Tree tree) { super(tree); initMapper(); } private void initMapper() { fResourceToItemsMapper= new ResourceToItemsMapper(this); } /* * @see StructuredViewer#mapElement(Object, Widget) */ protected void mapElement(Object element, Widget item) { super.mapElement(element, item); if (item instanceof Item) { fResourceToItemsMapper.addToMap(element, (Item) item); } } /* * @see StructuredViewer#unmapElement(Object, Widget) */ protected void unmapElement(Object element, Widget item) { if (item instanceof Item) { fResourceToItemsMapper.removeFromMap(element, (Item) item); } super.unmapElement(element, item); } /* * @see StructuredViewer#unmapAllElements() */ protected void unmapAllElements() { fResourceToItemsMapper.clearMap(); super.unmapAllElements(); } /* * @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent) */ protected void handleLabelProviderChanged(LabelProviderChangedEvent event) { if (event instanceof ProblemsLabelChangedEvent) { ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event; if (!e.isMarkerChange() && !isShowingWorkingCopies()) { return; } } Object[] changed= event.getElements(); if (changed != null && !fResourceToItemsMapper.isEmpty()) { ArrayList others= new ArrayList(); for (int i= 0; i < changed.length; i++) { Object curr= changed[i]; if (curr instanceof IResource) { fResourceToItemsMapper.resourceChanged((IResource) curr); } else { others.add(curr); } } if (others.isEmpty()) { return; } event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource(), others.toArray()); } super.handleLabelProviderChanged(event); } /** * @see StructuredViewer#handleInvalidSelection(ISelection, ISelection) */ protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { ISelection validNewSelection= getValidSelection(newSelection); if (isShowingWorkingCopies()) { // Convert to and from working copies if (invalidSelection instanceof IStructuredSelection) { IStructuredSelection structSel= (IStructuredSelection)invalidSelection; List elementsToSelect= new ArrayList(structSel.size()); Iterator iter= structSel.iterator(); while (iter.hasNext()) { Object element= iter.next(); if (element instanceof IJavaElement) { IJavaElement je= convertToValidElement((IJavaElement)element); if (je != null) elementsToSelect.add(je); } } if (!elementsToSelect.isEmpty()) { List alreadySelected= SelectionUtil.toList(validNewSelection); if (alreadySelected != null && !alreadySelected.isEmpty()) elementsToSelect.addAll(SelectionUtil.toList(validNewSelection)); validNewSelection= new StructuredSelection(elementsToSelect); } } } if (validNewSelection != newSelection) setSelection(validNewSelection); super.handleInvalidSelection(invalidSelection, validNewSelection); } /* * Returns a selection which does not contain non-existing * Java elements. If all elements are ok then the original * selection is returned unchanged. */ private ISelection getValidSelection(ISelection selection) { List selectedElements= SelectionUtil.toList(selection); if (selectedElements == null || selectedElements.isEmpty()) return selection; boolean selectionChanged= false; List validElementsToSelect= new ArrayList(selectedElements.size()); Iterator iter= selectedElements.iterator(); while (iter.hasNext()) { Object element= iter.next(); if (element instanceof IJavaElement) { IJavaElement je= (IJavaElement)element; if (je != null && je.exists()) validElementsToSelect.add(je); else selectionChanged= true; } else { validElementsToSelect.add(element); } } if (selectionChanged) return new StructuredSelection(validElementsToSelect); else return selection; } /** * Converts a working copy (element) to a cu (element) * or vice-versa. * * @return the converted Java element or <code>null</code> if the conversion fails */ private IJavaElement convertToValidElement(IJavaElement je) { ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT); IJavaElement convertedJE= null; if (cu == null) return null; if (cu.isWorkingCopy()) convertedJE= cu.getOriginal(je); else { IWorkingCopy wc= (IWorkingCopy)cu.findSharedWorkingCopy(JavaUI.getBufferFactory()); if (wc != null) { IJavaElement[] matches= wc.findElements(je); if (matches != null && matches.length > 0) convertedJE= matches[0]; } } if (convertedJE != null && convertedJE.exists()) return convertedJE; else return null; } /** * Answers whether this viewer shows working copies or not. * * @return <code>true</code> if this viewer shows working copies */ private boolean isShowingWorkingCopies() { Object contentProvider= getContentProvider(); return contentProvider instanceof IWorkingCopyProvider && ((IWorkingCopyProvider)contentProvider).providesWorkingCopies(); } }
31,905
Bug 31905 Package Explorer serious drawing problem
I have Windows 2000, JDK 1.4.0_01, Eclipse 2.1 M5 build. For no apparent reason, the package explorer seems to lose its mind for particular sections of the heirarchy. I am able to expand and collapse the tree and interact with it just fine. But certain sections become invisible and the only remedy is to restart eclipse. Please see the attached image. This has happend twice now, and I have no idea why.
resolved fixed
9c022ea
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T10:53:07Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/ProblemsLabelDecorator.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.IDecoration; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.ILabelProviderListener; import org.eclipse.jface.viewers.ILightweightLabelDecorator; import org.eclipse.jface.viewers.LabelProviderChangedEvent; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.MarkerAnnotation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.corext.refactoring.ListenerList; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.ImageImageDescriptor; /** * LabelDecorator that decorates an element's image with error and warning overlays that * represent the severity of markers attached to the element's underlying resource. To see * a problem decoration for a marker, the marker needs to be a subtype of <code>IMarker.PROBLEM</code>. * <p> * Note: Only images for elements in Java projects are currently updated on marker changes. * </p> * * @since 2.0 */ public class ProblemsLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator { /** * This is a special <code>LabelProviderChangedEvent</code> carring additional * information whether the event orgins from a maker change. * <p> * <code>ProblemsLabelChangedEvent</code>s are only generated by <code> * ProblemsLabelDecorator</code>s. * </p> */ public static class ProblemsLabelChangedEvent extends LabelProviderChangedEvent { private boolean fMarkerChange; /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public ProblemsLabelChangedEvent(IBaseLabelProvider source, IResource[] changedResource, boolean isMarkerChange) { super(source, changedResource); fMarkerChange= isMarkerChange; } /** * Returns whether this event origins from marker changes. If <code>false</code> an annotation * model change is the origin. In this case viewers not displaying working copies can ignore these * events. * * @return if this event origins from a marker change. */ public boolean isMarkerChange() { return fMarkerChange; } } private static final int ERRORTICK_WARNING= JavaElementImageDescriptor.WARNING; private static final int ERRORTICK_ERROR= JavaElementImageDescriptor.ERROR; private ImageDescriptorRegistry fRegistry; private boolean fUseNewRegistry= false; private IProblemChangedListener fProblemChangedListener; private ListenerList fListeners; /** * Creates a new <code>ProblemsLabelDecorator</code>. */ public ProblemsLabelDecorator() { this(null); fUseNewRegistry= true; } /* * Creates decorator with a shared image registry. * * @param registry The registry to use or <code>null</code> to use the Java plugin's * image registry. */ /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public ProblemsLabelDecorator(ImageDescriptorRegistry registry) { fRegistry= registry; fProblemChangedListener= null; } private ImageDescriptorRegistry getRegistry() { if (fRegistry == null) { fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : JavaPlugin.getImageDescriptorRegistry(); } return fRegistry; } /* (non-Javadoc) * @see ILabelDecorator#decorateText(String, Object) */ public String decorateText(String text, Object element) { return text; } /* (non-Javadoc) * @see ILabelDecorator#decorateImage(Image, Object) */ public Image decorateImage(Image image, Object obj) { int adornmentFlags= computeAdornmentFlags(obj); if (adornmentFlags != 0) { ImageDescriptor baseImage= new ImageImageDescriptor(image); Rectangle bounds= image.getBounds(); return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height))); } return image; } protected int computeAdornmentFlags(Object obj) { try { if (obj instanceof IJavaElement) { IJavaElement element= (IJavaElement) obj; int type= element.getElementType(); switch (type) { case IJavaElement.JAVA_PROJECT: case IJavaElement.PACKAGE_FRAGMENT_ROOT: return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_INFINITE, null); case IJavaElement.PACKAGE_FRAGMENT: case IJavaElement.CLASS_FILE: return getErrorTicksFromMarkers(element.getResource(), IResource.DEPTH_ONE, null); case IJavaElement.COMPILATION_UNIT: case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.IMPORT_CONTAINER: case IJavaElement.TYPE: case IJavaElement.INITIALIZER: case IJavaElement.METHOD: case IJavaElement.FIELD: ICompilationUnit cu= (ICompilationUnit) element.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { ISourceReference ref= (type == IJavaElement.COMPILATION_UNIT) ? null : (ISourceReference) element; // The assumption is that only source elements in compilation unit can have markers if (cu.isWorkingCopy()) { // working copy: look at annotation model return getErrorTicksFromWorkingCopy((ICompilationUnit) cu.getOriginalElement(), ref); } return getErrorTicksFromMarkers(cu.getResource(), IResource.DEPTH_ONE, ref); } break; default: } } else if (obj instanceof IResource) { return getErrorTicksFromMarkers((IResource) obj, IResource.DEPTH_INFINITE, null); } } catch (CoreException e) { if (e instanceof JavaModelException) { if (((JavaModelException) e).isDoesNotExist()) { return 0; } } JavaPlugin.log(e); } return 0; } private int getErrorTicksFromMarkers(IResource res, int depth, ISourceReference sourceElement) throws CoreException { if (res == null || !res.isAccessible()) { return 0; } int info= 0; IMarker[] markers= res.findMarkers(IMarker.PROBLEM, true, depth); if (markers != null) { for (int i= 0; i < markers.length && (info != ERRORTICK_ERROR); i++) { IMarker curr= markers[i]; if (sourceElement == null || isMarkerInRange(curr, sourceElement)) { int priority= curr.getAttribute(IMarker.SEVERITY, -1); if (priority == IMarker.SEVERITY_WARNING) { info= ERRORTICK_WARNING; } else if (priority == IMarker.SEVERITY_ERROR) { info= ERRORTICK_ERROR; } } } } return info; } private boolean isMarkerInRange(IMarker marker, ISourceReference sourceElement) throws CoreException { if (marker.isSubtypeOf(IMarker.TEXT)) { int pos= marker.getAttribute(IMarker.CHAR_START, -1); return isInside(pos, sourceElement); } return false; } private int getErrorTicksFromWorkingCopy(ICompilationUnit original, ISourceReference sourceElement) throws CoreException { int info= 0; FileEditorInput editorInput= new FileEditorInput((IFile) original.getResource()); IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(editorInput); if (model != null) { Iterator iter= model.getAnnotationIterator(); while ((info != ERRORTICK_ERROR) && iter.hasNext()) { Annotation curr= (Annotation) iter.next(); IMarker marker= isAnnotationInRange(model, curr, sourceElement); if (marker != null) { int priority= marker.getAttribute(IMarker.SEVERITY, -1); if (priority == IMarker.SEVERITY_WARNING) { info= ERRORTICK_WARNING; } else if (priority == IMarker.SEVERITY_ERROR) { info= ERRORTICK_ERROR; } } } } return info; } private IMarker isAnnotationInRange(IAnnotationModel model, Annotation annot, ISourceReference sourceElement) throws CoreException { if (annot instanceof MarkerAnnotation) { IMarker marker= ((MarkerAnnotation) annot).getMarker(); if (marker.exists() && marker.isSubtypeOf(IMarker.PROBLEM)) { Position pos= model.getPosition(annot); if (isInside(pos.getOffset(), sourceElement)) { return marker; } } } return null; } /** * Tests if a position is inside the source range of an element. * @param pos Position to be tested. * @param sourceElement Source element (must be a IJavaElement) * @return boolean Return <code>true</code> if position is located inside the source element. * @throws CoreException Exception thrown if element range could not be accessed. */ protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException { ISourceRange range= sourceElement.getSourceRange(); if (range != null) { int rangeOffset= range.getOffset(); return (rangeOffset <= pos && rangeOffset + range.getLength() > pos); } return false; } /* (non-Javadoc) * @see IBaseLabelProvider#dispose() */ public void dispose() { if (fProblemChangedListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener); fProblemChangedListener= null; } if (fRegistry != null && fUseNewRegistry) { fRegistry.dispose(); } } /* (non-Javadoc) * @see IBaseLabelProvider#isLabelProperty(Object, String) */ public boolean isLabelProperty(Object element, String property) { return true; } /* (non-Javadoc) * @see IBaseLabelProvider#addListener(ILabelProviderListener) */ public void addListener(ILabelProviderListener listener) { if (fListeners == null) { fListeners= new ListenerList(); } fListeners.add(listener); if (fProblemChangedListener == null) { fProblemChangedListener= new IProblemChangedListener() { public void problemsChanged(IResource[] changedResources, boolean isMarkerChange) { fireProblemsChanged(changedResources, isMarkerChange); } }; JavaPlugin.getDefault().getProblemMarkerManager().addListener(fProblemChangedListener); } } /* (non-Javadoc) * @see IBaseLabelProvider#removeListener(ILabelProviderListener) */ public void removeListener(ILabelProviderListener listener) { if (fListeners != null) { fListeners.remove(listener); if (fListeners.isEmpty() && fProblemChangedListener != null) { JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fProblemChangedListener); fProblemChangedListener= null; } } } private void fireProblemsChanged(IResource[] changedResources, boolean isMarkerChange) { if (fListeners != null && !fListeners.isEmpty()) { LabelProviderChangedEvent event= new ProblemsLabelChangedEvent(this, changedResources, isMarkerChange); Object[] listeners= fListeners.getListeners(); for (int i= 0; i < listeners.length; i++) { ((ILabelProviderListener) listeners[i]).labelProviderChanged(event); } } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration) */ public void decorate(Object element, IDecoration decoration) { int adornmentFlags= computeAdornmentFlags(element); if (adornmentFlags == ERRORTICK_ERROR) { decoration.addOverlay(JavaPluginImages.DESC_OVR_ERROR); } else if (adornmentFlags == ERRORTICK_WARNING) { decoration.addOverlay(JavaPluginImages.DESC_OVR_WARNING); } } }
31,292
Bug 31292 sort members: 2 dialogs if file read-only [code manipulation]
20030206 all other source actions show 1 error dialog if file is read-only this action shows 2
resolved fixed
f5dff4e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T13:12:05Z
2003-02-07T15:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/SortMembersAction.java
/******************************************************************************* * Copyright (c) 2003 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.codemanipulation.SortMembersOperation; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.ActionUtil; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.javaeditor.AnnotationType; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.util.ElementValidator; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Sorts the members of a compilation unit with the sort order as specified in * the Sort Order preference page. * <p> * The action will open the parent compilation unit in a Java editor. The result * is unsaved, so the user can decide if the changes are acceptable. * <p> * The action is applicable to structured selections containing a single * <code>ICompilationUnit</code> or top level <code>IType</code> in a * compilation unit. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.1 */ public class SortMembersAction extends SelectionDispatchAction { private CompilationUnitEditor fEditor; /** * Creates a new <code>SortMembersAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public SortMembersAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("SortMembersAction.label")); //$NON-NLS-1$ setDescription(ActionMessages.getString("SortMembersAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("SortMembersAction.tooltip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.SORT_MEMBERS_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public SortMembersAction(CompilationUnitEditor editor) { this(editor.getEditorSite()); fEditor= editor; setEnabled(checkEnabledEditor()); } private boolean checkEnabledEditor() { return fEditor != null && SelectionConverter.canOperateOn(fEditor); } //---- Structured Viewer ----------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void selectionChanged(IStructuredSelection selection) { boolean enabled= false; try { enabled= getSelectedCompilationUnit(selection) != null; } catch (JavaModelException e) { // http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253 if (JavaModelUtil.filterNotPresentException(e)) JavaPlugin.log(e); } setEnabled(enabled); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(IStructuredSelection selection) { Shell shell= getShell(); try { ICompilationUnit cu= getSelectedCompilationUnit(selection); if (cu == null || !ElementValidator.check(cu, getShell(), getDialogTitle(), false)) { return; } // open an editor and work on a working copy IEditorPart editor= EditorUtility.openInEditor(cu); if (editor != null) { run(shell, JavaModelUtil.toWorkingCopy(cu), editor); } } catch (CoreException e) { ExceptionHandler.handle(e, shell, getDialogTitle(), null); } } //---- Java Editior -------------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void selectionChanged(ITextSelection selection) { } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(ITextSelection selection) { Shell shell= getShell(); IJavaElement input= SelectionConverter.getInput(fEditor); if (input instanceof ICompilationUnit && ElementValidator.check(input, getShell(), getDialogTitle(), true)) run(shell, (ICompilationUnit) input, fEditor); else MessageDialog.openInformation(shell, getDialogTitle(), ActionMessages.getString("SortMembersAction.not_applicable")); //$NON-NLS-1$ } //---- Helpers ------------------------------------------------------------------- private boolean containsRelevantMarkers(IEditorPart editor) { IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); Iterator iterator= model.getAnnotationIterator(); while (iterator.hasNext()) { Object element= iterator.next(); if (element instanceof IJavaAnnotation) { IJavaAnnotation annot= (IJavaAnnotation) element; if (annot.isRelevant() && !annot.isTemporary()) { AnnotationType type= annot.getAnnotationType(); return (type == AnnotationType.BOOKMARK || type == AnnotationType.TASK || type == AnnotationType.UNKNOWN); } } } return false; } private void run(Shell shell, ICompilationUnit cu, IEditorPart editor) { if (!ActionUtil.isProcessable(getShell(), cu)) { return; } if (containsRelevantMarkers(editor)) { if (!MessageDialog.openConfirm(getShell(), getDialogTitle(), ActionMessages.getString("SortMembersAction.containsmarkers"))) { //$NON-NLS-1$ return; } } SortMembersOperation op= new SortMembersOperation(cu, null); try { BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext(); context.run(false, true, new WorkbenchRunnableAdapter(op)); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, shell, getDialogTitle(), null); } catch (InterruptedException e) { // Do nothing. Operation has been canceled by user. } } private ICompilationUnit getSelectedCompilationUnit(IStructuredSelection selection) throws JavaModelException { if (selection.size() == 1) { Object element= selection.getFirstElement(); if (element instanceof ICompilationUnit) { return (ICompilationUnit) element; } else if (element instanceof IType) { IType type= (IType) element; if (type.getParent() instanceof ICompilationUnit) { // only top level types return type.getCompilationUnit(); } } } return null; } private String getDialogTitle() { return ActionMessages.getString("SortMembersAction.error.title"); //$NON-NLS-1$ } }
31,970
Bug 31970 Go To Resource missing files
M5 build - org.eclipse.ui module in source, rest in binary - in Package Explorer, - Navigate / Go To / Resource... - type sync (looking for synced.gif under org.eclipse.ui\icons\full\clcl16) - no match - type *.gif - it's missing all of the gifs in this folder My Package Explorer filter settings are not set to filter out non-Java elements. These files show up in the Package Explorer, but not in Go To Resource.
resolved fixed
a496684
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T13:33:56Z
2003-02-17T05:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/GotoResourceAction.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.ui.dialogs.ResourceListSelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; public class GotoResourceAction extends Action { private PackageExplorerPart fPackageExplorer; private static class GotoResourceDialog extends ResourceListSelectionDialog { private IJavaModel fJavaModel; private Viewer fViewer; private ViewerFilter[] fFilters; public GotoResourceDialog(Shell parentShell, IContainer container, StructuredViewer viewer) { super(parentShell, container, IResource.FILE | IResource.FOLDER | IResource.PROJECT); fJavaModel= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); fViewer= viewer; fFilters= viewer.getFilters(); setTitle(PackagesMessages.getString("GotoResource.dialog.title")); //$NON-NLS-1$ WorkbenchHelp.setHelp(parentShell, IJavaHelpContextIds.GOTO_RESOURCE_DIALOG); } protected boolean select(IResource resource) { if (!fJavaModel.contains(resource)) return false; return isVisible(resource.getParent(), resource); } private boolean isVisible(Object parent, Object element) { for (int i= 0; i < fFilters.length; i++) { ViewerFilter filter= fFilters[i]; if (!filter.select(fViewer, parent, element)) return false; } return true; } } public GotoResourceAction(PackageExplorerPart explorer) { setText(PackagesMessages.getString("GotoResource.action.label")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GOTO_RESOURCE_ACTION); fPackageExplorer= explorer; } public void run() { TreeViewer viewer= fPackageExplorer.getViewer(); GotoResourceDialog dialog= new GotoResourceDialog(fPackageExplorer.getSite().getShell(), ResourcesPlugin.getWorkspace().getRoot(), viewer); dialog.open(); Object[] result = dialog.getResult(); if (result == null || result.length == 0 || !(result[0] instanceof IResource)) return; StructuredSelection selection= null; IJavaElement element = JavaCore.create((IResource)result[0]); if (element != null && element.exists()) selection= new StructuredSelection(element); else selection= new StructuredSelection(result[0]); viewer.setSelection(selection, true); } }
31,962
Bug 31962 Package Explorer context menu should not allow refresh on a closed project
null
verified fixed
a072d25
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T13:42:23Z
2003-02-16T01:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/RefreshAction.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.IWorkspaceRunnable; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Action for refreshing the workspace from the local file system for * the selected resources and all of their descendents. This action * also considers external Jars managed by the Java Model. * <p> * Action is applicable to selections containing resources and Java * elements down to compilation units. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class RefreshAction extends SelectionDispatchAction { /** * Creates a new <code>RefreshAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public RefreshAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("RefreshAction.label")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("RefreshAction.toolTip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.REFRESH_ACTION); } /* (non-Javadoc) * Method declared in SelectionDispatchAction */ protected void selectionChanged(IStructuredSelection selection) { setEnabled(checkEnabled(selection)); } private boolean checkEnabled(IStructuredSelection selection) { if (selection.isEmpty()) return true; for (Iterator iter= selection.iterator(); iter.hasNext();) { Object element= (Object) iter.next(); if (element instanceof IAdaptable) { IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class); if (resource == null) return false; } else { return false; } } return true; } /* (non-Javadoc) * Method declared in SelectionDispatchAction */ protected void run(IStructuredSelection selection) { final IResource[] resources= getResources(selection); IWorkspaceRunnable operation= new IWorkspaceRunnable() { public void run(IProgressMonitor monitor) throws CoreException { monitor.beginTask(ActionMessages.getString("RefreshAction.progressMessage"), resources.length * 2); //$NON-NLS-1$ monitor.subTask(""); //$NON-NLS-1$ List javaElements= new ArrayList(5); for (int r= 0; r < resources.length; r++) { IResource resource= resources[r]; if (resource.getType() == IResource.PROJECT) { checkLocationDeleted((IProject) resource); } else if (resource.getType() == IResource.ROOT) { IProject[] projects = ((IWorkspaceRoot)resource).getProjects(); for (int p = 0; p < projects.length; p++) { checkLocationDeleted(projects[p]); } } resource.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 1)); IJavaElement jElement= JavaCore.create(resource); if (jElement != null && jElement.exists()) javaElements.add(jElement); } IJavaModel model= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); model.refreshExternalArchives( (IJavaElement[]) javaElements.toArray(new IJavaElement[javaElements.size()]), new SubProgressMonitor(monitor, resources.length)); } }; try { new ProgressMonitorDialog(getShell()).run(true, true, new WorkbenchRunnableAdapter(operation)); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), ActionMessages.getString("RefreshAction.error.title"), //$NON-NLS-1$ ActionMessages.getString("RefreshAction.error.message")); //$NON-NLS-1$ } catch (InterruptedException e) { // canceled } } private IResource[] getResources(IStructuredSelection selection) { if (selection.isEmpty()) { return new IResource[] {ResourcesPlugin.getWorkspace().getRoot()}; } List result= new ArrayList(selection.size()); for (Iterator iter= selection.iterator(); iter.hasNext();) { Object element= (Object) iter.next(); if (element instanceof IAdaptable) { IResource resource= (IResource)((IAdaptable)element).getAdapter(IResource.class); if (resource != null) result.add(resource); } } for (Iterator iter= result.iterator(); iter.hasNext();) { IResource resource= (IResource) iter.next(); if (isDescendent(result, resource)) iter.remove(); } return (IResource[]) result.toArray(new IResource[result.size()]); } private boolean isDescendent(List candidates, IResource element) { IResource parent= element.getParent(); while (parent != null) { if (candidates.contains(parent)) return true; parent= parent.getParent(); } return false; } private void checkLocationDeleted(IProject project) throws CoreException { if (!project.exists()) return; File location = project.getLocation().toFile(); if (!location.exists()) { final String message = ActionMessages.getFormattedString( "RefreshAction.locationDeleted.message", //$NON-NLS-1$ new Object[] {project.getName(), location.getAbsolutePath()}); final boolean[] result= new boolean[1]; // Must prompt user in UI thread (we're in the operation thread here). getShell().getDisplay().syncExec(new Runnable() { public void run() { result[0]= MessageDialog.openQuestion(getShell(), ActionMessages.getString("RefreshAction.locationDeleted.title"), //$NON-NLS-1$ message); } }); if (result[0]) { project.delete(true, true, null); } } } }
31,554
Bug 31554 QuickFix Add catch clause to surrounding try in catch clause incorrect [code manipulation] [refactoring]
With the following code in the editor: try{ someMethod(); //throws SomeException }catch(SomeException e){ someOtherMethod(); //throws SomeException } You will get a QuickFix that suggests to add a catch clause to the surrounding try. There is no surrounding try. It will add another catch(SomeException e) to the try clause above! This catch clause is unreachable (which the editor notices). The exception is still uncaught (which the editor doesn't notice). Build: 2.1-M5
resolved fixed
1fa2575
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T13:44:04Z
2003-02-11T16:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Binding2JavaModel; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; public class ASTResolving { public static ITypeBinding normalizeTypeBinding(ITypeBinding binding) { if (binding != null && !binding.isNullType() && !"void".equals(binding.getName())) { //$NON-NLS-1$ if (binding.isAnonymous()) { ITypeBinding[] baseBindings= binding.getInterfaces(); if (baseBindings.length > 0) { return baseBindings[0]; } return binding.getSuperclass(); } return binding; } return null; } public static ITypeBinding guessBindingForReference(ASTNode node) { return normalizeTypeBinding(getPossibleReferenceBinding(node)); } private static ITypeBinding getPossibleReferenceBinding(ASTNode node) { ASTNode parent= node.getParent(); switch (parent.getNodeType()) { case ASTNode.ASSIGNMENT: Assignment assignment= (Assignment) parent; if (node.equals(assignment.getLeftHandSide())) { // field write access: xx= expression return assignment.getRightHandSide().resolveTypeBinding(); } // read access return assignment.getLeftHandSide().resolveTypeBinding(); case ASTNode.INFIX_EXPRESSION: InfixExpression infix= (InfixExpression) parent; if (node.equals(infix.getLeftOperand())) { // xx == expression return infix.getRightOperand().resolveTypeBinding(); } // expression == xx InfixExpression.Operator op= infix.getOperator(); if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED || op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) { return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } return infix.getLeftOperand().resolveTypeBinding(); case ASTNode.INSTANCEOF_EXPRESSION: InstanceofExpression instanceofExpression= (InstanceofExpression) parent; return instanceofExpression.getRightOperand().resolveBinding(); case ASTNode.VARIABLE_DECLARATION_FRAGMENT: VariableDeclarationFragment frag= (VariableDeclarationFragment) parent; if (frag.getInitializer().equals(node)) { ASTNode declaration= frag.getParent(); if (declaration instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)declaration).getType().resolveBinding(); } else if (declaration instanceof FieldDeclaration) { return ((FieldDeclaration)declaration).getType().resolveBinding(); } } break; case ASTNode.SUPER_METHOD_INVOCATION: SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent; IMethodBinding superMethodBinding= ASTNodes.getMethodBinding(superMethodInvocation.getName()); if (superMethodBinding != null) { return getParameterTypeBinding(node, superMethodInvocation.arguments(), superMethodBinding); } break; case ASTNode.METHOD_INVOCATION: MethodInvocation methodInvocation= (MethodInvocation) parent; IMethodBinding methodBinding= ASTNodes.getMethodBinding(methodInvocation.getName()); if (methodBinding != null) { return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding); } break; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: SuperConstructorInvocation superInvocation= (SuperConstructorInvocation) parent; IMethodBinding superBinding= superInvocation.resolveConstructorBinding(); if (superBinding != null) { return getParameterTypeBinding(node, superInvocation.arguments(), superBinding); } break; case ASTNode.CONSTRUCTOR_INVOCATION: ConstructorInvocation constrInvocation= (ConstructorInvocation) parent; IMethodBinding constrBinding= constrInvocation.resolveConstructorBinding(); if (constrBinding != null) { return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding); } break; case ASTNode.CLASS_INSTANCE_CREATION: ClassInstanceCreation creation= (ClassInstanceCreation) parent; IMethodBinding creationBinding= creation.resolveConstructorBinding(); if (creationBinding != null) { return getParameterTypeBinding(node, creation.arguments(), creationBinding); } break; case ASTNode.PARENTHESIZED_EXPRESSION: return guessBindingForReference(parent); case ASTNode.ARRAY_ACCESS: if (((ArrayAccess) parent).getIndex().equals(node)) { return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } break; case ASTNode.ARRAY_CREATION: if (((ArrayCreation) parent).dimensions().contains(node)) { return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } break; case ASTNode.ARRAY_INITIALIZER: ASTNode initializerParent= parent.getParent(); if (initializerParent instanceof ArrayCreation) { return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding(); } break; case ASTNode.CONDITIONAL_EXPRESSION: ConditionalExpression expression= (ConditionalExpression) parent; if (node.equals(expression.getExpression())) { return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$ } if (node.equals(expression.getElseExpression())) { return expression.getThenExpression().resolveTypeBinding(); } return expression.getElseExpression().resolveTypeBinding(); case ASTNode.POSTFIX_EXPRESSION: return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ case ASTNode.PREFIX_EXPRESSION: if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) { return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$ } return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ case ASTNode.IF_STATEMENT: case ASTNode.WHILE_STATEMENT: case ASTNode.DO_STATEMENT: if (node instanceof Expression) { return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$ } break; case ASTNode.SWITCH_STATEMENT: if (((SwitchStatement) parent).getExpression().equals(node)) { return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } break; case ASTNode.RETURN_STATEMENT: MethodDeclaration decl= findParentMethodDeclaration(parent); if (decl != null) { return decl.getReturnType().resolveBinding(); } break; case ASTNode.CAST_EXPRESSION: return ((CastExpression) parent).getType().resolveBinding(); case ASTNode.THROW_STATEMENT: case ASTNode.CATCH_CLAUSE: return parent.getAST().resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$ case ASTNode.FIELD_ACCESS: if (node.equals(((FieldAccess) parent).getName())) { return getPossibleReferenceBinding(parent); } break; case ASTNode.QUALIFIED_NAME: if (node.equals(((QualifiedName) parent).getName())) { return getPossibleReferenceBinding(parent); } break; } return null; } private static ITypeBinding getParameterTypeBinding(ASTNode node, List args, IMethodBinding binding) { ITypeBinding[] paramTypes= binding.getParameterTypes(); int index= args.indexOf(node); if (index >= 0 && index < paramTypes.length) { return paramTypes[index]; } return null; } public static ITypeBinding guessBindingForTypeReference(ASTNode node) { return normalizeTypeBinding(getPossibleTypeBinding(node)); } private static ITypeBinding getPossibleTypeBinding(ASTNode node) { ASTNode parent= node.getParent(); while (parent instanceof Type) { parent= parent.getParent(); } switch (parent.getNodeType()) { case ASTNode.VARIABLE_DECLARATION_STATEMENT: return guessVariableType(((VariableDeclarationStatement) parent).fragments()); case ASTNode.FIELD_DECLARATION: return guessVariableType(((FieldDeclaration) parent).fragments()); case ASTNode.VARIABLE_DECLARATION_EXPRESSION: return guessVariableType(((VariableDeclarationExpression) parent).fragments()); case ASTNode.SINGLE_VARIABLE_DECLARATION: SingleVariableDeclaration varDecl= (SingleVariableDeclaration) parent; if (varDecl.getInitializer() != null) { return varDecl.getInitializer().resolveTypeBinding(); } break; case ASTNode.ARRAY_CREATION: ArrayCreation creation= (ArrayCreation) parent; if (creation.getInitializer() != null) { return creation.getInitializer().resolveTypeBinding(); } return getPossibleReferenceBinding(parent); case ASTNode.TYPE_LITERAL: case ASTNode.CLASS_INSTANCE_CREATION: return getPossibleReferenceBinding(parent); } return null; } private static ITypeBinding guessVariableType(List fragments) { for (Iterator iter= fragments.iterator(); iter.hasNext();) { VariableDeclarationFragment frag= (VariableDeclarationFragment) iter.next(); if (frag.getInitializer() != null) { return frag.getInitializer().resolveTypeBinding(); } } return null; } public static MethodDeclaration findParentMethodDeclaration(ASTNode node) { while ((node != null) && (node.getNodeType() != ASTNode.METHOD_DECLARATION)) { node= node.getParent(); } return (MethodDeclaration) node; } public static BodyDeclaration findParentBodyDeclaration(ASTNode node) { while ((node != null) && (!(node instanceof BodyDeclaration))) { node= node.getParent(); } return (BodyDeclaration) node; } public static CompilationUnit findParentCompilationUnit(ASTNode node) { return (CompilationUnit) findAncestor(node, ASTNode.COMPILATION_UNIT); } /** * Returns either a TypeDeclaration or an AnonymousTypeDeclaration * @param node * @return CompilationUnit */ public static ASTNode findParentType(ASTNode node) { while ((node != null) && (node.getNodeType() != ASTNode.TYPE_DECLARATION) && (node.getNodeType() != ASTNode.ANONYMOUS_CLASS_DECLARATION)) { node= node.getParent(); } return node; } public static ASTNode findAncestor(ASTNode node, int nodeType) { while ((node != null) && (node.getNodeType() != nodeType)) { node= node.getParent(); } return node; } /** * Returns the type binding of the node's parent type declararation * @param node * @return CompilationUnit */ public static ITypeBinding getBindingOfParentType(ASTNode node) { while (node != null) { if (node instanceof TypeDeclaration) { return ((TypeDeclaration) node).resolveBinding(); } else if (node instanceof AnonymousClassDeclaration) { return ((AnonymousClassDeclaration) node).resolveBinding(); } node= node.getParent(); } return null; } public static Statement findParentStatement(ASTNode node) { while ((node != null) && (!(node instanceof Statement))) { node= node.getParent(); } return (Statement) node; } public static boolean isInStaticContext(ASTNode selectedNode) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { return Modifier.isStatic(((MethodDeclaration)decl).getModifiers()); } else if (decl instanceof Initializer) { return Modifier.isStatic(((Initializer)decl).getModifiers()); } else if (decl instanceof FieldDeclaration) { return Modifier.isStatic(((FieldDeclaration)decl).getModifiers()); } return false; } public static Type getTypeFromTypeBinding(AST ast, ITypeBinding binding) { if (binding.isArray()) { int dim= binding.getDimensions(); return ast.newArrayType(getTypeFromTypeBinding(ast, binding.getElementType()), dim); } else if (binding.isPrimitive()) { String name= binding.getName(); return ast.newPrimitiveType(PrimitiveType.toCode(name)); } else if (!binding.isNullType() && !binding.isAnonymous()) { return ast.newSimpleType(ast.newSimpleName(binding.getName())); } return null; } public static Expression getInitExpression(Type type, int extraDimensions) { if (extraDimensions == 0 && type.isPrimitiveType()) { PrimitiveType primitiveType= (PrimitiveType) type; if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) { return type.getAST().newBooleanLiteral(false); } else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) { return null; } else { return type.getAST().newNumberLiteral("0"); //$NON-NLS-1$ } } return type.getAST().newNullLiteral(); } public static Expression getInitExpression(AST ast, ITypeBinding type) { if (type.isPrimitive()) { String name= type.getName(); if ("boolean".equals(name)) { //$NON-NLS-1$ return ast.newBooleanLiteral(false); } else if ("void".equals(name)) { //$NON-NLS-1$ return null; } else { return ast.newNumberLiteral("0"); //$NON-NLS-1$ } } return ast.newNullLiteral(); } private static TypeDeclaration findTypeDeclaration(List decls, String name) { for (Iterator iter= decls.iterator(); iter.hasNext();) { ASTNode elem= (ASTNode) iter.next(); if (elem instanceof TypeDeclaration) { TypeDeclaration decl= (TypeDeclaration) elem; if (name.equals(decl.getName().getIdentifier())) { return decl; } } } return null; } public static TypeDeclaration findTypeDeclaration(CompilationUnit root, ITypeBinding binding) { ArrayList names= new ArrayList(5); while (binding != null) { names.add(binding.getName()); binding= binding.getDeclaringClass(); } List types= root.types(); for (int i= names.size() - 1; i >= 0; i--) { String name= (String) names.get(i); TypeDeclaration decl= findTypeDeclaration(types, name); if (decl == null || i == 0) { return decl; } types= decl.bodyDeclarations(); } return null; } public static String getFullName(Name name) { return ASTNodes.asString(name); } public static String getQualifier(Name name) { if (name.isQualifiedName()) { return getFullName(((QualifiedName) name).getQualifier()); } return ""; //$NON-NLS-1$ } public static String getSimpleName(Name name) { if (name.isQualifiedName()) { return ((QualifiedName) name).getName().getIdentifier(); } else { return ((SimpleName) name).getIdentifier(); } } public static ICompilationUnit findCompilationUnitForBinding(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding) throws JavaModelException { if (binding != null && binding.isFromSource() && astRoot.findDeclaringNode(binding) == null) { ICompilationUnit targetCU= Binding2JavaModel.findCompilationUnit(binding, cu.getJavaProject()); if (targetCU != null) { return JavaModelUtil.toWorkingCopy(targetCU); } return null; } return cu; } }
31,554
Bug 31554 QuickFix Add catch clause to surrounding try in catch clause incorrect [code manipulation] [refactoring]
With the following code in the editor: try{ someMethod(); //throws SomeException }catch(SomeException e){ someOtherMethod(); //throws SomeException } You will get a QuickFix that suggests to add a catch clause to the surrounding try. There is no surrounding try. It will add another catch(SomeException e) to the try clause above! This catch clause is unreachable (which the editor notices). The exception is still uncaught (which the editor doesn't notice). Build: 2.1-M5
resolved fixed
1fa2575
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T13:44:04Z
2003-02-11T16:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;[email protected]&gt; - Access to static proposal ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil; import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter; import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard; /** */ public class LocalCorrectionsSubProcessor { public static void addCastProposals(ICorrectionContext context, List proposals) throws CoreException { String[] args= context.getProblemArguments(); if (args.length != 2) { return; } ICompilationUnit cu= context.getCompilationUnit(); String castType= args[1]; CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (!(selectedNode instanceof Expression)) { return; } Expression nodeToCast= (Expression) selectedNode; int parentNodeType= selectedNode.getParent().getNodeType(); if (parentNodeType == ASTNode.ASSIGNMENT) { Assignment assign= (Assignment) selectedNode.getParent(); if (selectedNode.equals(assign.getLeftHandSide())) { nodeToCast= assign.getRightHandSide(); } } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent(); if (selectedNode.equals(frag.getName())) { nodeToCast= frag.getInitializer(); } } { ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent()); String label; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 1, image); //$NON-NLS-1$ String simpleCastType= proposal.addImport(castType); if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) { label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$ CastExpression expression= (CastExpression) nodeToCast; rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE)); } else { label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$ Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast); Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE); CastExpression castExpression= astRoot.getAST().newCastExpression(); castExpression.setExpression(expressionCopy); castExpression.setType(typeCopy); rewrite.markAsReplaced(nodeToCast, castExpression); } proposal.setDisplayName(label); proposal.ensureNoModifications(); proposals.add(proposal); } // change method return statement to actual type if (parentNodeType == ASTNode.RETURN_STATEMENT) { ITypeBinding binding= nodeToCast.resolveTypeBinding(); BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (binding != null && decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) decl; ASTRewrite rewrite= new ASTRewrite(methodDeclaration); Type newReturnType= ASTResolving.getTypeFromTypeBinding(astRoot.getAST(), binding); rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image); proposal.addImport(binding); proposal.ensureNoModifications(); proposals.add(proposal); } } if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent(); ASTNode parent= fragment.getParent(); Type type= null; if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent; if (stmt.fragments().size() == 1) { type= stmt.getType(); } } else if (parent instanceof FieldDeclaration) { FieldDeclaration decl= (FieldDeclaration) parent; if (decl.fragments().size() == 1) { type= decl.getType(); } } if (type != null) { ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String typeName= edit.addImport(args[0]); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast_var.description", typeName); //$NON-NLS-1$ ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, type.getStartPosition(), type.getLength(), typeName, 1); varProposal.getRootTextEdit().add(edit); proposals.add(varProposal); } } } public static void addUncaughtExceptionProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (selectedNode == null) { return; } while (selectedNode != null && !(selectedNode instanceof Statement)) { selectedNode= selectedNode.getParent(); } if (selectedNode == null) { return; } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); SurroundWithTryCatchRefactoring refactoring= new SurroundWithTryCatchRefactoring(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null); refactoring.setSaveChanges(false); if (refactoring.checkActivationBasics(astRoot, null).isOK()) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image); proposals.add(proposal); } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl == null) { return; } ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength())); if (uncaughtExceptions.length == 0) { return; } TryStatement surroundingTry= (TryStatement) ASTNodes.getParent(selectedNode, ASTNode.TRY_STATEMENT); if (surroundingTry != null) { ASTRewrite rewrite= new ASTRewrite(surroundingTry); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image); AST ast= astRoot.getAST(); List catchClauses= surroundingTry.catchClauses(); for (int i= 0; i < uncaughtExceptions.length; i++) { String imp= proposal.addImport(uncaughtExceptions[i]); Name name= ASTNodeFactory.newName(ast, imp); SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); var.setName(ast.newSimpleName("e")); //$NON-NLS-1$ var.setType(ast.newSimpleType(name)); CatchClause newClause= ast.newCatchClause(); newClause.setException(var); rewrite.markAsInserted(newClause); catchClauses.add(newClause); } proposal.ensureNoModifications(); proposals.add(proposal); } if (decl instanceof MethodDeclaration) { ASTRewrite rewrite= new ASTRewrite(astRoot); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); AST ast= astRoot.getAST(); MethodDeclaration methodDecl= (MethodDeclaration) decl; List exceptions= methodDecl.thrownExceptions(); for (int i= 0; i < uncaughtExceptions.length; i++) { String imp= proposal.addImport(uncaughtExceptions[i]); Name name= ASTNodeFactory.newName(ast, imp); rewrite.markAsInserted(name); exceptions.add(name); } for (int i= 0; i < exceptions.size(); i++) { Name elem= (Name) exceptions.get(i); if (canRemove(elem.resolveTypeBinding(), uncaughtExceptions)) { rewrite.markAsRemoved(elem); } } proposal.ensureNoModifications(); proposals.add(proposal); } } private static boolean canRemove(ITypeBinding curr, ITypeBinding[] addedExceptions) { while (curr != null) { for (int i= 0; i < addedExceptions.length; i++) { if (curr == addedExceptions[i]) { return true; } } curr= curr.getSuperclass(); } return false; } public static void addUnreachableCatchProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) { CatchClause clause= (CatchClause) selectedNode.getParent(); TryStatement tryStatement= (TryStatement) clause.getParent(); ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent()); if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) { rewrite.markAsRemoved(clause); } else { List statements= tryStatement.getBody().statements(); if (statements.size() > 0) { ASTNode placeholder= rewrite.createCopy((ASTNode) statements.get(0), (ASTNode) statements.get(statements.size() - 1)); rewrite.markAsReplaced(tryStatement, placeholder); } else { rewrite.markAsRemoved(tryStatement); } } String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); proposal.ensureNoModifications(); proposals.add(proposal); } } public static void addNLSProposals(ICorrectionContext context, List proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$ ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 0) { public void apply(IDocument document) { try { NLSRefactoring refactoring= new NLSRefactoring(cu, JavaPreferencesSettings.getCodeGenerationSettings()); ExternalizeWizard wizard= new ExternalizeWizard(refactoring); String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$ new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true); } catch (JavaModelException e) { JavaPlugin.log(e); } } }; proposals.add(proposal); TextEdit edit= NLSUtil.createNLSEdit(cu, context.getOffset()); if (edit != null) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE); CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image); nlsProposal.getRootTextEdit().add(edit); proposals.add(nlsProposal); } } /** * A static field or method is accessed using a non-static reference. E.g. * <pre> * File f = new File(); * f.pathSeparator; * </pre> * This correction changes <code>f</code> above to <code>File</code>. * * @param context * @param proposals */ public static void addInstanceAccessToStaticProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= context.getCoveredNode(); if (selectedNode == null) { return; } Expression qualifier= null; IBinding accessBinding= null; if (selectedNode instanceof QualifiedName) { QualifiedName name= (QualifiedName) selectedNode; qualifier= name.getQualifier(); accessBinding= name.resolveBinding(); } else if (selectedNode instanceof SimpleName) { ASTNode parent= selectedNode.getParent(); if (parent instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) parent; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); } } else if (selectedNode instanceof MethodInvocation) { MethodInvocation methodInvocation= (MethodInvocation) selectedNode; qualifier= methodInvocation.getExpression(); accessBinding= methodInvocation.getName().resolveBinding(); } else if (selectedNode instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) selectedNode; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); } ITypeBinding declaringTypeBinding= null; if (accessBinding != null) { if (accessBinding instanceof IMethodBinding) { declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass(); } else if (accessBinding instanceof IVariableBinding) { declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass(); } if (declaringTypeBinding != null) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(declaringTypeBinding.getName())); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 2, image); proposal.addImport(declaringTypeBinding); proposal.ensureNoModifications(); proposals.add(proposal); } } if (qualifier != null) { ITypeBinding instanceTypeBinding= ASTResolving.normalizeTypeBinding(qualifier.resolveTypeBinding()); if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); rewrite.markAsReplaced(qualifier, astRoot.getAST().newSimpleName(instanceTypeBinding.getName())); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 1, image); proposal.addImport(instanceTypeBinding); proposal.ensureNoModifications(); proposals.add(proposal); } } ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC); } public static void addUnimplementedMethodsProposals(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } ASTNode typeNode= null; if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) { typeNode= selectedNode.getParent(); } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; typeNode= creation.getAnonymousClassDeclaration(); } if (typeNode != null) { UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10); proposals.add(proposal); } if (typeNode instanceof TypeDeclaration) { TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode; ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration); proposals.add(proposal); } } public static void addUninitializedLocalVariableProposal(ICorrectionContext context, List proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= context.getCoveringNode(); if (!(selectedNode instanceof Name)) { return; } Name name= (Name) selectedNode; IBinding binding= name.resolveBinding(); if (!(binding instanceof IVariableBinding)) { return; } IVariableBinding varBinding= (IVariableBinding) binding; CompilationUnit astRoot= context.getASTRoot(); ASTNode node= astRoot.findDeclaringNode(binding); if (node instanceof VariableDeclarationFragment) { ASTRewrite rewrite= new ASTRewrite(node.getParent()); VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; if (fragment.getInitializer() != null) { return; } Expression expression= ASTResolving.getInitExpression(astRoot.getAST(), varBinding.getType()); if (expression == null) { return; } fragment.setInitializer(expression); rewrite.markAsInserted(expression); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); proposal.ensureNoModifications(); proposals.add(proposal); } } public static void addConstructorFromSuperclassProposal(ICorrectionContext context, List proposals) { ASTNode selectedNode= context.getCoveringNode(); if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) { return; } TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent(); ITypeBinding binding= typeDeclaration.resolveBinding(); if (binding == null || binding.getSuperclass() == null) { return; } ICompilationUnit cu= context.getCompilationUnit(); IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) { proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 2)); } } } public static void addUnusedMemberProposal(ICorrectionContext context, List proposals) throws CoreException { ASTNode selectedNode= context.getCoveringNode(); if (selectedNode == null) { return; } BodyDeclaration declaration= ASTResolving.findParentBodyDeclaration(selectedNode); if (declaration != null) { ASTNode nodeToRemove= declaration; if (declaration.getNodeType() == ASTNode.FIELD_DECLARATION) { List fragments= ((FieldDeclaration) declaration).fragments(); if (fragments.size() > 1) { for (int i= 0; i < fragments.size(); i++) { VariableDeclarationFragment node= (VariableDeclarationFragment) fragments.get(i); if (ASTNodes.isParent(selectedNode, node)) { nodeToRemove= node; break; } } } } ASTRewrite rewrite= new ASTRewrite(nodeToRemove.getParent()); rewrite.markAsRemoved(nodeToRemove); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removeunusedmember.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 6, image); proposal.ensureNoModifications(); proposals.add(proposal); } } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/FocusOnSelectionAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.util.SelectionUtil; /** * Refocuses the type hierarchy on the currently selection type. */ public class FocusOnSelectionAction extends Action { private TypeHierarchyViewPart fViewPart; private ISelectionProvider fSelectionProvider; private String fText; public FocusOnSelectionAction(TypeHierarchyViewPart part) { super(TypeHierarchyMessages.getString("FocusOnSelectionAction.label")); //$NON-NLS-1$ setDescription(TypeHierarchyMessages.getString("FocusOnSelectionAction.description")); //$NON-NLS-1$ setToolTipText(TypeHierarchyMessages.getString("FocusOnSelectionAction.tooltip")); //$NON-NLS-1$ fViewPart= part; fText= TypeHierarchyMessages.getString("FocusOnSelectionAction.label"); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FOCUS_ON_SELECTION_ACTION); } private ISelection getSelection() { ISelectionProvider provider= fViewPart.getSite().getSelectionProvider(); if (provider != null) { return provider.getSelection(); } return null; } /* * @see Action#run */ public void run() { Object element= SelectionUtil.getSingleElement(getSelection()); if (element instanceof IType) { fViewPart.setInputElement((IType)element); } } public boolean canActionBeAdded() { Object element= SelectionUtil.getSingleElement(getSelection()); if (element instanceof IType) { setText(TypeHierarchyMessages.getFormattedString("FocusOnSelectionAction.label", ((IType)element).getElementName())); //$NON-NLS-1$ return true; } return false; } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/FocusOnTypeAction.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; /** * Refocuses the type hierarchy on a type selection from a all types dialog. */ public class FocusOnTypeAction extends Action { private TypeHierarchyViewPart fViewPart; private ISelectionProvider fSelectionProvider; public FocusOnTypeAction(TypeHierarchyViewPart part) { super(TypeHierarchyMessages.getString("FocusOnTypeAction.label")); //$NON-NLS-1$ setDescription(TypeHierarchyMessages.getString("FocusOnTypeAction.description")); //$NON-NLS-1$ setToolTipText(TypeHierarchyMessages.getString("FocusOnTypeAction.tooltip")); //$NON-NLS-1$ fViewPart= part; WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FOCUS_ON_TYPE_ACTION); } /* * @see Action#run */ public void run() { Shell parent= fViewPart.getSite().getShell(); TypeSelectionDialog dialog= new TypeSelectionDialog(parent, new ProgressMonitorDialog(parent), IJavaSearchConstants.TYPE, SearchEngine.createWorkspaceScope()); dialog.setTitle(TypeHierarchyMessages.getString("FocusOnTypeAction.dialog.title")); //$NON-NLS-1$ dialog.setMessage(TypeHierarchyMessages.getString("FocusOnTypeAction.dialog.message")); //$NON-NLS-1$ if (dialog.open() != IDialogConstants.OK_ID) { return; } Object[] types= dialog.getResult(); if (types != null && types.length > 0) { IType type= (IType)types[0]; fViewPart.setInputElement(type); } } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/MethodsViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.Table; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.ui.actions.OpenAction; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.util.SelectionUtil; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; /** * Method viewer shows a list of methods of a input type. * Offers filter actions. * No dependency to the type hierarchy view */ public class MethodsViewer extends ProblemTableViewer { private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$ private static final String TAG_SORTBYDEFININGTYPE= "sortbydefiningtype"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$ private static final int LABEL_BASEFLAGS= AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS; private HierarchyLabelProvider fLabelProvider; private MemberFilterActionGroup fMemberFilterActionGroup; private OpenAction fOpen; private ShowInheritedMembersAction fShowInheritedMembersAction; private SortByDefiningTypeAction fSortByDefiningTypeAction; public MethodsViewer(Composite parent, final TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { super(new Table(parent, SWT.MULTI)); fLabelProvider= new HierarchyLabelProvider(lifeCycle); setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, true, false)); setContentProvider(new MethodsContentProvider(lifeCycle)); HierarchyViewerSorter sorter= new HierarchyViewerSorter(lifeCycle); sorter.setSortByDefiningType(false); setSorter(sorter); fOpen= new OpenAction(part.getSite()); addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fOpen.run(); } }); fMemberFilterActionGroup= new MemberFilterActionGroup(this, "HierarchyMethodView"); //$NON-NLS-1$ fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false); fSortByDefiningTypeAction= new SortByDefiningTypeAction(this, false); showInheritedMethodsNoRedraw(false); sortByDefiningTypeNoRedraw(false); JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); } private void showInheritedMethodsNoRedraw(boolean on) { MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider(); cprovider.showInheritedMethods(on); fShowInheritedMembersAction.setChecked(on); if (on) { fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaElementLabels.ALL_POST_QUALIFIED); } else { fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & ~JavaElementLabels.ALL_POST_QUALIFIED); } if (on) { sortByDefiningTypeNoRedraw(false); } fSortByDefiningTypeAction.setEnabled(!on); } /** * Show inherited methods */ public void showInheritedMethods(boolean on) { if (on == isShowInheritedMethods()) { return; } try { getTable().setRedraw(false); showInheritedMethodsNoRedraw(on); refresh(); } finally { getTable().setRedraw(true); } } private void sortByDefiningTypeNoRedraw(boolean on) { fSortByDefiningTypeAction.setChecked(on); fLabelProvider.setShowDefiningType(on); ((HierarchyViewerSorter) getSorter()).setSortByDefiningType(on); } /** * Show the name of the defining type */ public void sortByDefiningType(boolean on) { if (on == isShowDefiningTypes()) { return; } try { getTable().setRedraw(false); sortByDefiningTypeNoRedraw(on); refresh(); } finally { getTable().setRedraw(true); } } /* * @see Viewer#inputChanged(Object, Object) */ protected void inputChanged(Object input, Object oldInput) { super.inputChanged(input, oldInput); } /** * Returns <code>true</code> if inherited methods are shown. */ public boolean isShowInheritedMethods() { return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods(); } /** * Returns <code>true</code> if defining types are shown. */ public boolean isShowDefiningTypes() { return fLabelProvider.isShowDefiningType(); } /** * Saves the state of the filter actions */ public void saveState(IMemento memento) { fMemberFilterActionGroup.saveState(memento); memento.putString(TAG_SHOWINHERITED, String.valueOf(isShowInheritedMethods())); memento.putString(TAG_SORTBYDEFININGTYPE, String.valueOf(isShowDefiningTypes())); ScrollBar bar= getTable().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putString(TAG_VERTICAL_SCROLL, String.valueOf(position)); } /** * Restores the state of the filter actions */ public void restoreState(IMemento memento) { fMemberFilterActionGroup.restoreState(memento); getControl().setRedraw(false); refresh(); getControl().setRedraw(true); boolean showInherited= Boolean.valueOf(memento.getString(TAG_SHOWINHERITED)).booleanValue(); showInheritedMethods(showInherited); boolean showDefiningTypes= Boolean.valueOf(memento.getString(TAG_SORTBYDEFININGTYPE)).booleanValue(); sortByDefiningType(showDefiningTypes); ScrollBar bar= getTable().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } } /** * Attaches a contextmenu listener to the table */ public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) { MenuManager menuMgr= new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(menuListener); Menu menu= menuMgr.createContextMenu(getTable()); getTable().setMenu(menu); viewSite.registerContextMenu(popupId, menuMgr, this); } /** * Fills up the context menu with items for the method viewer * Should be called by the creator of the context menu */ public void contributeToContextMenu(IMenuManager menu) { } /** * Fills up the tool bar with items for the method viewer * Should be called by the creator of the tool bar */ public void contributeToToolBar(ToolBarManager tbm) { tbm.add(fShowInheritedMembersAction); tbm.add(fSortByDefiningTypeAction); tbm.add(new Separator()); fMemberFilterActionGroup.contributeToToolBar(tbm); } public void dispose() { if (fMemberFilterActionGroup != null) { fMemberFilterActionGroup.dispose(); fMemberFilterActionGroup= null; } } /* * @see StructuredViewer#handleInvalidSelection(ISelection, ISelection) */ protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) { // on change of input, try to keep selected methods stable by selecting a method with the same // signature: See #5466 List oldSelections= SelectionUtil.toList(invalidSelection); List newSelections= SelectionUtil.toList(newSelection); if (!oldSelections.isEmpty()) { ArrayList newSelectionElements= new ArrayList(newSelections); try { Object[] currElements= getFilteredChildren(getInput()); for (int i= 0; i < oldSelections.size(); i++) { Object curr= oldSelections.get(i); if (curr instanceof IMethod && !newSelections.contains(curr)) { IMethod method= (IMethod) curr; if (method.exists()) { IMethod similar= findSimilarMethod(method, currElements); if (similar != null) { newSelectionElements.add(similar); } } } } if (!newSelectionElements.isEmpty()) { newSelection= new StructuredSelection(newSelectionElements); } else if (currElements.length > 0) { newSelection= new StructuredSelection(currElements[0]); } } catch (JavaModelException e) { JavaPlugin.log(e); } } setSelection(newSelection); updateSelection(newSelection); } private IMethod findSimilarMethod(IMethod meth, Object[] elements) throws JavaModelException { String name= meth.getElementName(); String[] paramTypes= meth.getParameterTypes(); boolean isConstructor= meth.isConstructor(); for (int i= 0; i < elements.length; i++) { Object curr= elements[i]; if (curr instanceof IMethod && JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, (IMethod) curr)) { return (IMethod) curr; } } return null; } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/SubTypeHierarchyViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; /** * A viewer including the content provider for the subtype hierarchy. * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle * on construction (shared type hierarchy) */ public class SubTypeHierarchyViewer extends TypeHierarchyViewer { public SubTypeHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { super(parent, new SubTypeHierarchyContentProvider(lifeCycle), lifeCycle, part); } /* * @see TypeHierarchyViewer#getTitle */ public String getTitle() { if (isMethodFiltering()) { return TypeHierarchyMessages.getString("SubTypeHierarchyViewer.filtered.title"); //$NON-NLS-1$ } else { return TypeHierarchyMessages.getString("SubTypeHierarchyViewer.title"); //$NON-NLS-1$ } } /* * @see TypeHierarchyViewer#updateContent */ public void updateContent() { getTree().setRedraw(false); refresh(); int expandLevel= 2; if (isMethodFiltering()) { expandLevel++; } expandToLevel(expandLevel); getTree().setRedraw(true); } /** * Content provider for the subtype hierarchy */ private static class SubTypeHierarchyContentProvider extends TypeHierarchyContentProvider { public SubTypeHierarchyContentProvider(TypeHierarchyLifeCycle lifeCycle) { super(lifeCycle); } protected final IType[] getTypesInHierarchy(IType type) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { return hierarchy.getSubtypes(type); } return new IType[0]; } protected IType getParentType(IType type) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { return hierarchy.getSuperclass(type); // dont handle interfaces } return null; } } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/SuperTypeHierarchyViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; /** * A viewer including the content provider for the supertype hierarchy. * Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle * on construction (shared type hierarchy) */ public class SuperTypeHierarchyViewer extends TypeHierarchyViewer { public SuperTypeHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { super(parent, new SuperTypeHierarchyContentProvider(lifeCycle), lifeCycle, part); } /* * @see TypeHierarchyViewer#getTitle */ public String getTitle() { if (isMethodFiltering()) { return TypeHierarchyMessages.getString("SuperTypeHierarchyViewer.filtered.title"); //$NON-NLS-1$ } else { return TypeHierarchyMessages.getString("SuperTypeHierarchyViewer.title"); //$NON-NLS-1$ } } /* * @see TypeHierarchyViewer#updateContent */ public void updateContent() { getTree().setRedraw(false); refresh(); expandAll(); getTree().setRedraw(true); } /* * Content provider for the supertype hierarchy */ private static class SuperTypeHierarchyContentProvider extends TypeHierarchyContentProvider { public SuperTypeHierarchyContentProvider(TypeHierarchyLifeCycle lifeCycle) { super(lifeCycle); } protected final IType[] getTypesInHierarchy(IType type) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { return hierarchy.getSupertypes(type); } return new IType[0]; } protected IType getParentType(IType type) { // cant handle return null; } } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.widgets.Composite; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; /** * 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() { getTree().setRedraw(false); refresh(); TraditionalHierarchyContentProvider contentProvider= (TraditionalHierarchyContentProvider) getContentProvider(); int expandLevel= contentProvider.getExpandLevel(); if (isMethodFiltering()) { expandLevel++; } expandToLevel(expandLevel); getTree().setRedraw(true); } /** * Content provider for the 'traditional' type hierarchy. */ private 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) { // opened on a region return hierarchy.getRootClasses(); } 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 ("java.lang.Object".equals(JavaModelUtil.getFullyQualifiedName(roots[i]))) { //$NON-NLS-1$ return new Object[] { roots[i] }; } } return roots; // a problem with the hierarchy } } } return NO_ELEMENTS; } /* * @see TypeHierarchyContentProvider.getTypesInHierarchy */ protected final IType[] getTypesInHierarchy(IType type) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { return hierarchy.getSubtypes(type); } return new IType[0]; } protected IType getParentType(IType type) { ITypeHierarchy hierarchy= getHierarchy(); if (hierarchy != null) { return hierarchy.getSuperclass(type); // dont handle interfaces } return null; } } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; 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.RefactorActionGroup; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectAllAction; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of input elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IDialogSettings fDialogSettings; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private IPropertyChangeListener fPropertyChangeListener; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private IPartListener2 fPartListener; private int fCurrentOrientation; private boolean fIsVisible; private boolean fNeedRefresh; private boolean fIsEnableMemberFilter; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private MethodsViewer fMethodsViewer; private SashForm fTypeMethodsSplitter; private PageBook fViewerbook; private PageBook fPagebook; private Label fNoHierarchyShownLabel; private Label fEmptyTypesViewer; private ViewForm fTypeViewerViewForm; private ViewForm fMethodViewerViewForm; private CLabel fMethodViewerPaneLabel; private JavaUILabelProvider fPaneLabelProvider; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private EnableMemberFilterAction fEnableMemberFilterAction; private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; private SelectAllAction fSelectAllAction; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fHierarchyLifeCycle.setReconciled(isReconciled); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); fIsEnableMemberFilter= false; fInputHistory= new ArrayList(); fAllViewers= null; fViewActions= new ToggleViewAction[] { new ToggleViewAction(this, VIEW_ID_TYPE), new ToggleViewAction(this, VIEW_ID_SUPER), new ToggleViewAction(this, VIEW_ID_SUB) }; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fHistoryDropDownAction= new HistoryDropDownAction(this); fHistoryDropDownAction.setEnabled(false); fToggleOrientationActions= new ToggleOrientationAction[] { new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) }; fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener2() { public void partVisible(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part == TypeHierarchyViewPart.this) { visibilityChanged(true); } } public void partHidden(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part == TypeHierarchyViewPart.this) { visibilityChanged(false); } } public void partActivated(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partInputChanged(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part instanceof IEditorPart) editorActivated((IEditorPart) part); }; public void partBroughtToTop(IWorkbenchPartReference ref) {} public void partClosed(IWorkbenchPartReference ref) {} public void partDeactivated(IWorkbenchPartReference ref) {} public void partOpened(IWorkbenchPartReference ref) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * Method doPropertyChange. * @param event */ protected void doPropertyChange(PropertyChangeEvent event) { if (fMethodsViewer != null) { if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) { fMethodsViewer.refresh(); } } } /** * Adds the entry if new. Inserted at the beginning of the history entries list. */ private void addHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { fInputHistory.remove(entry); } fInputHistory.add(0, entry); fHistoryDropDownAction.setEnabled(true); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty()); } /** * Goes to the selected entry, without updating the order of history entries. */ public void gotoHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { updateInput(entry); } } /** * Gets all history entries. */ public IJavaElement[] getHistoryEntries() { if (fInputHistory.size() > 0) { updateHistoryEntries(); } return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]); } /** * Sets the history entries */ public void setHistoryEntries(IJavaElement[] elems) { fInputHistory.clear(); for (int i= 0; i < elems.length; i++) { fInputHistory.add(elems[i]); } updateHistoryEntries(); } /** * Selects an member in the methods list or in the current hierarchy. */ public void selectMember(IMember member) { if (member.getElementType() != IJavaElement.TYPE) { // methods are working copies if (fHierarchyLifeCycle.isReconciled()) { member= JavaModelUtil.toWorkingCopy(member); } Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { methodControl.setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } else { Control viewerControl= getCurrentViewer().getControl(); if (viewerControl != null && !viewerControl.isDisposed()) { viewerControl.setFocus(); } // types are originals member= JavaModelUtil.toOriginal(member); if (!member.equals(fSelectedType)) { getCurrentViewer().setSelection(new StructuredSelection(member), true); } } } /** * @deprecated */ public IType getInput() { if (fInputElement instanceof IType) { return (IType) fInputElement; } return null; } /** * Sets the input to a new type * @deprecated */ public void setInput(IType type) { setInputElement(type); } /** * Returns the input element of the type hierarchy. * Can be of type <code>IType</code> or <code>IPackageFragment</code> */ public IJavaElement getInputElement() { return fInputElement; } /** * Sets the input to a new element. */ public void setInputElement(IJavaElement element) { if (element != null) { if (element instanceof IMember) { if (element.getElementType() != IJavaElement.TYPE) { element= ((IMember) element).getDeclaringType(); } ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(element); if (!element.exists()) { MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return; } } } else { int kind= element.getElementType(); if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) { element= null; JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$ } } } if (element != null && !element.equals(fInputElement)) { addHistoryEntry(element); } updateInput(element); } /** * Changes the input to a new type */ private void updateInput(IJavaElement inputElement) { IJavaElement prevInput= fInputElement; // Make sure the UI got repainted before we execute a long running // operation. This can be removed if we refresh the hierarchy in a // separate thread. // Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881 processOutstandingEvents(); fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); fPagebook.showPage(fTypeMethodsSplitter); } } private void processOutstandingEvents() { Display display= getDisplay(); if (display != null && !display.isDisposed()) display.update(); } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); fMethodsViewer.dispose(); if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } getSite().getPage().removePartListener(fPartListener); if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { IPageLayout.ID_RES_NAV, JavaUI.ID_PACKAGES }; } }; } return super.getAdapter(key); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW); fAllViewers= new TypeHierarchyViewer[3]; fAllViewers[VIEW_ID_SUPER]= superTypesViewer; fAllViewers[VIEW_ID_SUB]= subTypesViewer; fAllViewers[VIEW_ID_TYPE]= vajViewer; int currViewerIndex; try { currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); if (currViewerIndex < 0 || currViewerIndex > 2) { currViewerIndex= VIEW_ID_TYPE; } } catch (NumberFormatException e) { currViewerIndex= VIEW_ID_TYPE; } fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setInput(fAllViewers[i]); } // force the update fCurrentViewerIndex= -1; setView(currViewerIndex); return fViewerbook; } private KeyListener createKeyListener() { return new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F5) { updateHierarchyViewer(); return; } else if (event.character == SWT.DEL){ if (fCCPActionGroup.getDeleteAction().isEnabled()) fCCPActionGroup.getDeleteAction().run(); return; } } viewPartKeyShortcuts(event); } }; } private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) { typesViewer.getControl().setVisible(false); typesViewer.getControl().addKeyListener(keyListener); typesViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillTypesViewerContextMenu(typesViewer, menu); } }, cotextHelpId, getSite()); typesViewer.addSelectionChangedListener(fSelectionChangedListener); typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames()); } private Control createMethodViewerControl(Composite parent) { fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this); fMethodsViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillMethodsViewerContextMenu(menu); } }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); fMethodsViewer.addSelectionChangedListener(fSelectionChangedListener); Control control= fMethodsViewer.getTable(); control.addKeyListener(createKeyListener()); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK; for (int i= 0; i < fAllViewers.length; i++) { addDragAdapters(fAllViewers[i], ops, transfers); addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers); } addDragAdapters(fMethodsViewer, ops, transfers); //dnd on empty hierarchy DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT); dropTarget.setTransfer(transfers); dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0])); } private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){ TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new TypeHierarchyTransferDropAdapter(this, viewer) }; viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners)); } private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers){ Control control= viewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(viewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ MenuManager menu= new MenuManager(); menu.add(fFocusOnTypeAction); fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); fPagebook.showPage(fNoHierarchyShownLabel); int orientation; try { orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); if (orientation < 0 || orientation > 2) { orientation= VIEW_ORIENTATION_VERTICAL; } } catch (NumberFormatException e) { orientation= VIEW_ORIENTATION_VERTICAL; } // force the update fCurrentOrientation= -1; // will fill the main tool bar setOrientation(orientation); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fToggleOrientationActions.length; i++) { viewMenu.add(fToggleOrientationActions[i]); } viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); viewMenu.add(fShowQualifiedTypeNamesAction); // fill the method viewer toolbar ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar); lowertbmanager.add(fEnableMemberFilterAction); lowertbmanager.add(new Separator()); fMethodsViewer.contributeToToolBar(lowertbmanager); lowertbmanager.update(true); // selection provider int nHierarchyViewers= fAllViewers.length; Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1]; for (int i= 0; i < nHierarchyViewers; i++) { trackedViewers[i]= fAllViewers[i]; } trackedViewers[nHierarchyViewers]= fMethodsViewer; fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager)); getSite().setSelectionProvider(fSelectionProviderMediator); getSite().getPage().addPartListener(fPartListener); IJavaElement input= determineInputElement(); if (fMemento != null) { restoreState(fMemento, input); } else if (input != null) { setInputElement(input); } else { setViewerVisibility(false); } WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); fActionGroups= new CompositeActionGroup(new ActionGroup[] { new NewWizardsActionGroup(this.getSite()), new OpenEditorActionGroup(this), new OpenViewActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); fActionGroups.fillActionBars(actionBars); fSelectAllAction= new SelectAllAction(fMethodsViewer); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction); initDragAndDrop(); } /** * called from ToggleOrientationAction. * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL */ public void setOrientation(int orientation) { if (fCurrentOrientation != orientation) { boolean methodViewerNeedsUpdate= false; if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { if (orientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(false); enableMemberFilter(false); updateMethodViewer(null); } else { if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(true); methodViewerNeedsUpdate= true; } boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); } updateMainToolbar(orientation); fTypeMethodsSplitter.layout(); } for (int i= 0; i < fToggleOrientationActions.length; i++) { fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation()); } fCurrentOrientation= orientation; if (methodViewerNeedsUpdate) { updateMethodViewer(fSelectedType); } fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation); } } private void updateMainToolbar(int orientation) { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager tbmanager= actionBars.getToolBarManager(); if (orientation == VIEW_ORIENTATION_HORIZONTAL) { clearMainToolBar(tbmanager); ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); fillMainToolBar(new ToolBarManager(typeViewerToolBar)); fTypeViewerViewForm.setTopLeft(typeViewerToolBar); } else { fTypeViewerViewForm.setTopLeft(null); fillMainToolBar(tbmanager); } } private void fillMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.add(fHistoryDropDownAction); for (int i= 0; i < fViewActions.length; i++) { tbmanager.add(fViewActions[i]); } tbmanager.update(false); } private void clearMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.update(false); } /** * Creates the context menu for the hierarchy viewers */ private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { JavaPlugin.createStandardGroups(menu); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS)); // viewer entries viewer.contributeToContextMenu(menu); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction); menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction); fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Creates the context menu for the method viewer */ private void fillMethodsViewerContextMenu(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries fMethodsViewer.contributeToContextMenu(menu); if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction); } fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Toggles between the empty viewer page and the hierarchy */ private void setViewerVisibility(boolean showHierarchy) { if (showHierarchy) { fViewerbook.showPage(getCurrentViewer().getControl()); } else { fViewerbook.showPage(fEmptyTypesViewer); } } /** * Sets the member filter. <code>null</code> disables member filtering. */ private void setMemberFilter(IMember[] memberFilter) { Assert.isNotNull(fAllViewers); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setMemberFilter(memberFilter); } } private IType getSelectableType(IJavaElement elem) { if (elem.getElementType() != IJavaElement.TYPE) { return null; //(IType) getCurrentViewer().getTreeRootType(); } else { return (IType) elem; } } private void internalSelectType(IMember elem, boolean reveal) { TypeHierarchyViewer viewer= getCurrentViewer(); viewer.removeSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); viewer.addSelectionChangedListener(fSelectionChangedListener); } /** * When the input changed or the hierarchy pane becomes visible, * <code>updateHierarchyViewer<code> brings up the correct view and refreshes * the current tree */ private void updateHierarchyViewer() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) { setViewerVisibility(true); } } else { fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ setViewerVisibility(false); } } } private void updateMethodViewer(final IType input) { if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input == fMethodsViewer.getInput()) { if (input != null) { Runnable runnable= new Runnable() { public void run() { fMethodsViewer.refresh(); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); } } else { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } Runnable runnable= new Runnable() { public void run() { fMethodsViewer.setInput(input); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); } } } protected void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(true); } else { typeSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(false); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); updateHierarchyViewer(); updateTitle(); internalSelectType(fSelectedType, true); } if (nSelected == 1) { revealElementInEditor(selected.get(0), fMethodsViewer); } } } private void typeSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (nSelected != 0) { List types= new ArrayList(nSelected); for (int i= nSelected-1; i >= 0; i--) { Object elem= selected.get(i); if (elem instanceof IType && !types.contains(elem)) { types.add(elem); } } if (types.size() == 1) { fSelectedType= (IType) types.get(0); updateMethodViewer(fSelectedType); } else if (types.size() == 0) { // method selected, no change } if (nSelected == 1) { revealElementInEditor(selected.get(0), getCurrentViewer()); } } else { fSelectedType= null; updateMethodViewer(null); } } } private void revealElementInEditor(Object elem, Viewer originViewer) { // only allow revealing when the type hierarchy is the active pagae // no revealing after selection events due to model changes if (getSite().getPage().getActivePart() != this) { return; } if (fSelectionProviderMediator.getViewerInFocus() != originViewer) { return; } IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); if (editorPart != null && (elem instanceof IJavaElement)) { getSite().getPage().removePartListener(fPartListener); getSite().getPage().bringToTop(editorPart); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } } private Display getDisplay() { if (fPagebook != null && !fPagebook.isDisposed()) { return fPagebook.getDisplay(); } return null; } private boolean isChildVisible(Composite pb, Control child) { Control[] children= pb.getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] == child && children[i].isVisible()) return true; } return false; } private void updateTitle() { String viewerTitle= getCurrentViewer().getTitle(); String tooltip; String title; if (fInputElement != null) { String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) }; title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ } else { title= viewerTitle; tooltip= viewerTitle; } setTitle(title); setTitleToolTip(tooltip); } private void updateToolbarButtons() { boolean isType= fInputElement instanceof IType; for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; if (action.getViewerIndex() == VIEW_ID_TYPE) { action.setEnabled(fInputElement != null); } else { action.setEnabled(isType); } } } /** * Sets the current view (see view id) * called from ToggleViewAction. Must be called after creation of the viewpart. */ public void setView(int viewerIndex) { Assert.isNotNull(fAllViewers); if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { fCurrentViewerIndex= viewerIndex; updateHierarchyViewer(); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement), false); currSelection= getCurrentViewer().getSelection(); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); getCurrentViewer().getTree().setFocus(); } for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); } } /** * Gets the curret active view index. */ public int getViewIndex() { return fCurrentViewerIndex; } private TypeHierarchyViewer getCurrentViewer() { return fAllViewers[fCurrentViewerIndex]; } /** * called from EnableMemberFilterAction. * Must be called after creation of the viewpart. */ public void enableMemberFilter(boolean on) { if (on != fIsEnableMemberFilter) { fIsEnableMemberFilter= on; if (!on) { IType methodViewerInput= (IType) fMethodsViewer.getInput(); setMemberFilter(null); updateHierarchyViewer(); updateTitle(); if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { // avoid that the method view changes content by selecting the previous input internalSelectType(methodViewerInput, true); } else if (fSelectedType != null) { // choose a input that exists internalSelectType(fSelectedType, true); updateMethodViewer(fSelectedType); } } else { methodSelectionChanged(fMethodsViewer.getSelection()); } } fEnableMemberFilterAction.setChecked(on); } /** * called from ShowQualifiedTypeNamesAction. Must be called after creation * of the viewpart. */ public void showQualifiedTypeNames(boolean on) { if (fAllViewers == null) { return; } for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setQualifiedTypeName(on); } } private boolean isShowQualifiedTypeNames() { return fShowQualifiedTypeNamesAction.isChecked(); } /** * Called from ITypeHierarchyLifeCycleListener. * Can be called from any thread */ protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { if (!fIsVisible) { fNeedRefresh= true; } Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { if (fPagebook != null && !fPagebook.isDisposed()) { doTypeHierarchyChangedOnViewers(changedTypes); } } }); } } protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fMethodsViewer.refresh(); updateHierarchyViewer(); } else { // elements in hierarchy modified fMethodsViewer.refresh(); if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { IJavaElement elem= (IJavaElement) input; if (elem instanceof IMember) { return elem; } else { int kind= elem.getElementType(); if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) { return elem; } } } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { String handleIndentifier= fInputElement.getHandleIdentifier(); if (fInputElement instanceof IType) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) { // for startup performance reasons do not try to recover huge hierarchies handleIndentifier= null; } } memento.putString(TAG_INPUT, handleIndentifier); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (input != null && !input.exists()) { input= null; } } setInputElement(input); Integer viewerIndex= memento.getInteger(TAG_VIEW); if (viewerIndex != null) { setView(viewerIndex.intValue()); } Integer orientation= memento.getInteger(TAG_ORIENTATION); if (orientation != null) { setOrientation(orientation.intValue()); } Integer ratio= memento.getInteger(TAG_RATIO); if (ratio != null) { fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); } ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } //String selectionId= memento.getString(TAG_SELECTION); // do not restore type hierarchy contents // if (selectionId != null) { // IJavaElement elem= JavaCore.create(selectionId); // if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { // internalSelectType((IMember)elem, false); // } // } fMethodsViewer.restoreState(memento); } /** * view part becomes visible */ protected void visibilityChanged(boolean isVisible) { fIsVisible= isVisible; if (isVisible && fNeedRefresh) { doTypeHierarchyChanged(fHierarchyLifeCycle, null); } fNeedRefresh= false; } /** * Link selection to active editor. */ protected void editorActivated(IEditorPart editor) { if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR)) { return; } if (fInputElement == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); try { TypeHierarchyViewer currentViewer= getCurrentViewer(); if (elem instanceof IClassFile) { IType type= ((IClassFile)elem).getType(); if (currentViewer.isElementShown(type)) { internalSelectType(type, true); updateMethodViewer(type); } } else if (elem instanceof ICompilationUnit) { IType[] allTypes= ((ICompilationUnit)elem).getAllTypes(); for (int i= 0; i < allTypes.length; i++) { if (currentViewer.isElementShown(allTypes[i])) { internalSelectType(allTypes[i], true); updateMethodViewer(allTypes[i]); return; } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return fInputElement; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( null, getSite().getSelectionProvider().getSelection()); } }; } }
31,897
Bug 31897 Hierarchy View expands all treeitems on save
I have a hierarchy perspective open rooted on a package. Whenever I save a CU in the package, the entire hierarchy view Tree is expanded.
resolved fixed
ad9614d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:19:54Z
2003-02-14T19:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewer.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Tree; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; import org.eclipse.jdt.ui.actions.OpenAction; public abstract class TypeHierarchyViewer extends ProblemTreeViewer { private OpenAction fOpen; private HierarchyLabelProvider fLabelProvider; public TypeHierarchyViewer(Composite parent, IContentProvider contentProvider, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) { super(new Tree(parent, SWT.SINGLE)); fLabelProvider= new HierarchyLabelProvider(lifeCycle); setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, true, false)); setContentProvider(contentProvider); setSorter(new HierarchyViewerSorter(lifeCycle)); fOpen= new OpenAction(part.getSite()); addOpenListener(new IOpenListener() { public void open(OpenEvent event) { fOpen.run(); } }); JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); } public void setQualifiedTypeName(boolean on) { if (on) { fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaElementLabels.T_POST_QUALIFIED); } else { fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & ~JavaElementLabels.T_POST_QUALIFIED); } refresh(); } /** * Attaches a contextmenu listener to the tree */ public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) { MenuManager menuMgr= new MenuManager(); menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(menuListener); Menu menu= menuMgr.createContextMenu(getTree()); getTree().setMenu(menu); viewSite.registerContextMenu(popupId, menuMgr, this); } /** * Fills up the context menu with items for the hierarchy viewer * Should be called by the creator of the context menu */ public void contributeToContextMenu(IMenuManager menu) { } /** * Set the member filter */ public void setMemberFilter(IMember[] memberFilter) { TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); if (contentProvider != null) { contentProvider.setMemberFilter(memberFilter); } } /** * Returns if method filtering is enabled. */ public boolean isMethodFiltering() { TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); if (contentProvider != null) { return contentProvider.getMemberFilter() != null; } return false; } /** * Returns true if the hierarchy contains elements. Returns one of them * With member filtering it is possible that no elements are visible */ public Object containsElements() { TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); if (contentProvider != null) { Object[] elements= contentProvider.getElements(null); if (elements.length > 0) { return elements[0]; } } return null; } /** * Returns true if the hierarchy contains elements. Returns one of them * With member filtering it is possible that no elements are visible */ public IType getTreeRootType() { TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider(); if (contentProvider != null) { Object[] elements= contentProvider.getElements(null); if (elements.length > 0 && elements[0] instanceof IType) { return (IType) elements[0]; } } return null; } /** * Returns true if the hierarchy contains element the element. */ public boolean isElementShown(Object element) { return findItem(element) != null; } /** * Updates the content of this viewer: refresh and expanding the tree in the way wanted. */ public abstract void updateContent(); /** * Returns the title for the current view */ public abstract String getTitle(); /* * @see StructuredViewer#setContentProvider * Content provider must be of type TypeHierarchyContentProvider */ public void setContentProvider(IContentProvider cp) { Assert.isTrue(cp instanceof TypeHierarchyContentProvider); super.setContentProvider(cp); } protected TypeHierarchyContentProvider getHierarchyContentProvider() { return (TypeHierarchyContentProvider)getContentProvider(); } }
32,010
Bug 32010 renaming a java project wipes out linked sourcefolders
20030214 as a consequence of core making SHALLOW not default. arrrgh! have a fix - entered the report so that it's verified
resolved fixed
84dde43
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:36:13Z
2003-02-17T13:53:20Z
org.eclipse.jdt.ui/core
32,010
Bug 32010 renaming a java project wipes out linked sourcefolders
20030214 as a consequence of core making SHALLOW not default. arrrgh! have a fix - entered the report so that it's verified
resolved fixed
84dde43
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:36:13Z
2003-02-17T13:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/RenameJavaProjectChange.java
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
org.eclipse.jdt.ui/core
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameMethodInInterfaceRefactoring.java
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
org.eclipse.jdt.ui/core
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameMethodRefactoring.java
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
org.eclipse.jdt.ui/core
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenamePrivateMethodRefactoring.java
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
org.eclipse.jdt.ui/core
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameStaticMethodRefactoring.java
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
org.eclipse.jdt.ui/core
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameVirtualMethodRefactoring.java
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
org.eclipse.jdt.ui/ui
18,944
Bug 18944 Renaming a type causes unwanted reveal in Resource Navigator [refactoring]
Build F1. Choose "Refactor > Rename Element" while a type is selected and rename it. Resource Navigator reveals the source file for the type (workbench preference to link navigator selection to active editor is not selected).
resolved fixed
a385cad
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:44:04Z
2002-06-03T21:33:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringSupport.java
13,921
Bug 13921 Desire per-project property settings for Ant integration
We have an Ant implementation which stores most properties in an external .properties file. However, there is still a need to pass one or two properties to Ant using the Ant wizard and -DPROPERTY=.... Our build files are set up in such a way that property values are unlikely to change between any two build files in a given project. Thus it would be a nice feature if Eclipse allowed a user to set default property values for a PROJECT, which would then be in force for any build.xml file which is part of that PROJECT. And as long as I'm asking for favors, an ideal implementation would still allow the user to use the Ant wizard to override any of these default values for any particular build.xml file, as desired.
resolved wontfix
1be2414
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T15:51:55Z
2002-04-16T18:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/JavaCorrectionAssistant.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.Iterator; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultInformationControl; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControl; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.source.Annotation; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.jface.util.Assert; import org.eclipse.ui.IEditorPart; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.IColorManager; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation; import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator; import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; public class JavaCorrectionAssistant extends ContentAssistant { private ITextViewer fViewer; private IEditorPart fEditor; private Position fPosition; /** * Constructor for CorrectionAssistant. */ public JavaCorrectionAssistant(IEditorPart editor) { super(); Assert.isNotNull(editor); fEditor= editor; JavaCorrectionProcessor processor= new JavaCorrectionProcessor(editor); setContentAssistProcessor(processor, IDocument.DEFAULT_CONTENT_TYPE); setContentAssistProcessor(processor, JavaPartitionScanner.JAVA_STRING); enableAutoActivation(false); enableAutoInsert(false); setContextInformationPopupOrientation(CONTEXT_INFO_ABOVE); setInformationControlCreator(getInformationControlCreator()); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); IColorManager manager= textTools.getColorManager(); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); Color c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager); setProposalSelectorForeground(c); c= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager); setProposalSelectorBackground(c); } private IInformationControlCreator getInformationControlCreator() { return new IInformationControlCreator() { public IInformationControl createInformationControl(Shell parent) { return new DefaultInformationControl(parent, new HTMLTextPresenter()); } }; } private static Color getColor(IPreferenceStore store, String key, IColorManager manager) { RGB rgb= PreferenceConverter.getColor(store, key); return manager.getColor(rgb); } public void install(ITextViewer textViewer) { super.install(textViewer); fViewer= textViewer; } /** * Show completions at caret position. If current * position does not contain quick fixes look for * next quick fix on same line by moving from left * to right and restarting at end of line if the * beginning of the line is reached. * * @see org.eclipse.jface.text.contentassist.IContentAssistant#showPossibleCompletions() */ public String showPossibleCompletions() { if (fViewer == null) // Let superclass deal with this return super.showPossibleCompletions(); Point selectedRange= fViewer.getSelectedRange(); int initalOffset= selectedRange.x; int invocationOffset; int invocationLength; if (areMultipleLinesSelected()) { try { IDocument document= fViewer.getDocument(); IRegion start= document.getLineInformationOfOffset(initalOffset); invocationOffset= start.getOffset(); IRegion end= document.getLineInformationOfOffset(initalOffset + selectedRange.y); if (end.getOffset() == initalOffset + selectedRange.y) { int line= document.getLineOfOffset(end.getOffset()); end= fViewer.getDocument().getLineInformation(line - 1); } invocationLength= end.getOffset() + end.getLength() - invocationOffset; } catch (BadLocationException ex) { invocationOffset= initalOffset; invocationLength= 0; } } else { invocationOffset= computeOffsetWithCorrection(initalOffset); invocationLength= 0; } if (invocationOffset != -1) { storePosition(); fViewer.setSelectedRange(invocationOffset, invocationLength); fViewer.revealRange(invocationOffset, invocationLength); } else { fPosition= null; } String errorMsg= super.showPossibleCompletions(); return errorMsg; } /** * Find offset which contains corrections. * Search on same line by moving from left * to right and restarting at end of line if the * beginning of the line is reached. * * @return an offset where corrections are available or -1 if none */ private int computeOffsetWithCorrection(int initalOffset) { if (fViewer == null || fViewer.getDocument() == null) return -1; IRegion lineInfo= null; try { lineInfo= fViewer.getDocument().getLineInformationOfOffset(initalOffset); } catch (BadLocationException ex) { return -1; } int startOffset= lineInfo.getOffset(); int endOffset= startOffset + lineInfo.getLength(); int result= computeOffsetWithCorrection(startOffset, endOffset, initalOffset); if (result > 0) return result; else return -1; } /** * @return the best matching offset with corrections or -1 if nothing is found */ private int computeOffsetWithCorrection(int startOffset, int endOffset, int initialOffset) { IAnnotationModel model= JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput()); int invocationOffset= -1; int offsetOfFirstProblem= Integer.MAX_VALUE; Iterator iter= new JavaAnnotationIterator(model, true); while (iter.hasNext()) { IJavaAnnotation annot= (IJavaAnnotation)iter.next(); Position pos= model.getPosition((Annotation)annot); if (isIncluded(pos, startOffset, endOffset)) { if (JavaCorrectionProcessor.hasCorrections(annot)) { offsetOfFirstProblem= Math.min(offsetOfFirstProblem, pos.getOffset()); invocationOffset= computeBestOffset(invocationOffset, pos, initialOffset); if (initialOffset == invocationOffset) return initialOffset; } } } if (initialOffset < offsetOfFirstProblem && offsetOfFirstProblem != Integer.MAX_VALUE) return offsetOfFirstProblem; else return invocationOffset; } private boolean isIncluded(Position pos, int lineStart, int lineEnd) { return (pos != null) && (pos.getOffset() >= lineStart && (pos.getOffset() + pos.getLength() <= lineEnd)); } /** * Computes and returns the invocation offset given a new * position, the initial offset and the best invocation offset * found so far. * <p> * The closest offset to the left of the initial offset is the * best. If there is no offset on the left, the closest on the * right is the best.</p> */ private int computeBestOffset(int invocationOffset, Position pos, int initalOffset) { int newOffset= pos.offset; if (newOffset <= initalOffset && initalOffset <= newOffset + pos.length) return initalOffset; if (invocationOffset < 0) return newOffset; if (newOffset <= initalOffset && invocationOffset >= initalOffset) return newOffset; if (newOffset <= initalOffset && invocationOffset < initalOffset) return Math.max(invocationOffset, newOffset); if (invocationOffset <= initalOffset) return invocationOffset; return Math.max(invocationOffset, newOffset); } /* * @see org.eclipse.jface.text.contentassist.ContentAssistant#possibleCompletionsClosed() */ protected void possibleCompletionsClosed() { super.possibleCompletionsClosed(); restorePosition(); } /** * Returns <code>true</code> if one line is completely selected or if multiple lines are selected. * Being completely selected means that all characters except the new line characters are * selected. * * @return <code>true</code> if one or multiple lines are selected * @since 2.1 */ private boolean areMultipleLinesSelected() { Point s= fViewer.getSelectedRange(); if (s.y == 0) return false; try { IDocument document= fViewer.getDocument(); int startLine= document.getLineOfOffset(s.x); int endLine= document.getLineOfOffset(s.x + s.y); IRegion line= document.getLineInformation(startLine); return startLine != endLine || (s.x == line.getOffset() && s.y == line.getLength()); } catch (BadLocationException x) { return false; } } private void storePosition() { int initalOffset= fViewer.getSelectedRange().x; int length= fViewer.getSelectedRange().y; fPosition= new Position(initalOffset, length); } private void restorePosition() { if (fPosition != null && !fPosition.isDeleted()) { fViewer.setSelectedRange(fPosition.offset, fPosition.length); fViewer.revealRange(fPosition.offset, fPosition.length); } fPosition= null; } }
29,909
Bug 29909 Incorrect indentation after newline
I have my preferences set as follows: Java | Editor | Displayed tab width: 8 Java | Code formatter | Insert tabs for indentation: No Java | Code formatter | Number of spaces representing an indentation level: 4 When I have the following code: class ContainerSelection extends Selection { } and I position the caret after the { and press Enter, Eclipse inserts a new line and 8 spaces. It should only insert 4.
resolved fixed
5f2a46d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:06:37Z
2003-01-21T17:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
/********************************************************************** Copyright (c) 2000, 2002 IBM Corp. and others. All rights reserved. This program and the accompanying materials are made available under the terms of the Common Public License v1.0 which accompanies this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.html Contributors: IBM Corporation - Initial implementation **********************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import java.util.Iterator; import java.util.NoSuchElementException; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentPartitioner; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner; /** * Auto indent strategy sensitive to brackets. */ public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy { private final static String COMMENT= "//"; //$NON-NLS-1$ private int fTabWidth= -1; private Boolean fUseSpaces= null; public JavaAutoIndentStrategy() { } // evaluate the line with the opening bracket that matches the closing bracket on the given line protected int findMatchingOpenBracket(IDocument d, int line, int end, int closingBracketIncrease) throws BadLocationException { int start= d.getLineOffset(line); int brackcount= getBracketCount(d, start, end, false) - closingBracketIncrease; // sum up the brackets counts of each line (closing brackets count negative, // opening positive) until we find a line the brings the count to zero while (brackcount < 0) { line--; if (line < 0) { return -1; } start= d.getLineOffset(line); end= start + d.getLineLength(line) - 1; brackcount += getBracketCount(d, start, end, false); } return line; } private int getBracketCount(IDocument d, int start, int end, boolean ignoreCloseBrackets) throws BadLocationException { int bracketcount= 0; while (start < end) { char curr= d.getChar(start); start++; switch (curr) { case '/' : if (start < end) { char next= d.getChar(start); if (next == '*') { // a comment starts, advance to the comment end start= getCommentEnd(d, start + 1, end); } else if (next == '/') { // '//'-comment: nothing to do anymore on this line start= end; } } break; case '*' : if (start < end) { char next= d.getChar(start); if (next == '/') { // we have been in a comment: forget what we read before bracketcount= 0; start++; } } break; case '{' : bracketcount++; ignoreCloseBrackets= false; break; case '}' : if (!ignoreCloseBrackets) { bracketcount--; } break; case '"' : case '\'' : start= getStringEnd(d, start, end, curr); break; default : } } return bracketcount; } // ----------- bracket counting ------------------------------------------------------ private int getCommentEnd(IDocument d, int pos, int end) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '*') { if (pos < end && d.getChar(pos) == '/') { return pos + 1; } } } return end; } protected String getIndentOfLine(IDocument d, int line) throws BadLocationException { if (line > -1) { int start= d.getLineOffset(line); int end= start + d.getLineLength(line) - 1; int whiteend= findEndOfWhiteSpace(d, start, end); return d.get(start, whiteend - start); } else { return ""; //$NON-NLS-1$ } } private int getStringEnd(IDocument d, int pos, int end, char ch) throws BadLocationException { while (pos < end) { char curr= d.getChar(pos); pos++; if (curr == '\\') { // ignore escaped characters pos++; } else if (curr == ch) { return pos; } } return end; } protected void smartInsertAfterBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); int start= d.getLineOffset(line); int whiteend= findEndOfWhiteSpace(d, start, c.offset); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset= start; c.text= replaceText.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } } protected void smartIndentAfterNewLine(IDocument d, DocumentCommand c) { int docLength= d.getLength(); if (c.offset == -1 || docLength == 0) return; try { int p= (c.offset == docLength ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); StringBuffer buf= new StringBuffer(c.text); if (c.offset < docLength && d.getChar(c.offset) == '}') { int indLine= findMatchingOpenBracket(d, line, c.offset, 0); if (indLine == -1) { indLine= line; } buf.append(getIndentOfLine(d, indLine)); } else { int start= d.getLineOffset(line); // if line just ended a javadoc comment, take the indent from the comment's begin line IDocumentPartitioner partitioner= d.getDocumentPartitioner(); if (partitioner != null) { ITypedRegion region= partitioner.getPartition(start); if (JavaPartitionScanner.JAVA_DOC.equals(region.getType())) start= d.getLineInformationOfOffset(region.getOffset()).getOffset(); } int whiteend= findEndOfWhiteSpace(d, start, c.offset); buf.append(d.get(start, whiteend - start)); if (getBracketCount(d, start, c.offset, true) > 0) { buf.append(createIndent(1, useSpaces())); } } c.text= buf.toString(); } catch (BadLocationException e) { JavaPlugin.log(e); } } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } private static boolean startsWithClosingBrace(String string) { final int length= string.length(); int i= 0; while (i != length && Character.isWhitespace(string.charAt(i))) ++i; if (i == length) return false; return string.charAt(i) == '}'; } protected void smartPaste(IDocument document, DocumentCommand command) { String lineDelimiter= getLineDelimiter(document); try { String pastedText= command.text; Assert.isNotNull(pastedText); Assert.isTrue(pastedText.length() > 1); // extend selection begin if only whitespaces int selectionStart= command.offset; IRegion region= document.getLineInformationOfOffset(selectionStart); String notSelected= document.get(region.getOffset(), selectionStart - region.getOffset()); String selected= document.get(selectionStart, region.getOffset() + region.getLength() - selectionStart); if (notSelected.trim().length() == 0 && selected.trim().length() != 0) { pastedText= notSelected + pastedText; command.length += notSelected.length(); command.offset= region.getOffset(); } // choose smaller indent of block and preceeding non-empty line String blockIndent= getBlockIndent(document, command); String insideBlockIndent= blockIndent == null ? "" : blockIndent + createIndent(1, useSpaces()); //$NON-NLS-1$ // add one indent level int insideBlockIndentSize= calculateDisplayedWidth(insideBlockIndent, getTabWidth()); int previousIndentSize= getIndentSize(document, command); int newIndentSize= insideBlockIndentSize < previousIndentSize ? insideBlockIndentSize : previousIndentSize; // indent is different if block starts with '}' if (startsWithClosingBrace(pastedText)) { int outsideBlockIndentSize= blockIndent == null ? 0 : calculateDisplayedWidth(blockIndent, getTabWidth()); newIndentSize = outsideBlockIndentSize; } // check selection int offset= command.offset; int line= document.getLineOfOffset(offset); int lineOffset= document.getLineOffset(line); String prefix= document.get(lineOffset, offset - lineOffset); boolean formatFirstLine= prefix.trim().length() == 0; String formattedParagraph= format(pastedText, newIndentSize, lineDelimiter, formatFirstLine); // paste if (formatFirstLine) { int end= command.offset + command.length; command.offset= lineOffset; command.length= end - command.offset; } command.text= formattedParagraph; } catch (BadLocationException e) { JavaPlugin.log(e); } } private static String getIndentOfLine(String line) { int i= 0; for (; i < line.length(); i++) { if (! Character.isWhitespace(line.charAt(i))) break; } return line.substring(0, i); } /** * Returns the indent of the first non empty line. * A line is considered empty if it only consists of whitespaces or if it * begins with a single line comment followed by whitespaces only. */ private static int getIndentSizeOfFirstLine(String paragraph, boolean includeFirstLine, int tabWidth) { for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { final String line= (String) iterator.next(); if (!includeFirstLine) { includeFirstLine= true; continue; } String indent= null; if (line.startsWith(COMMENT)) { String commentedLine= line.substring(2); // line is empty if (commentedLine.trim().length() == 0) continue; indent= COMMENT + getIndentOfLine(commentedLine); } else { // line is empty if (line.trim().length() == 0) continue; indent= getIndentOfLine(line); } return calculateDisplayedWidth(indent, tabWidth); } return 0; } /** * Returns the minimal indent size of all non empty lines; */ private static int getMinimalIndentSize(String paragraph, boolean includeFirstLine, int tabWidth) { int minIndentSize= Integer.MAX_VALUE; for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { final String line= (String) iterator.next(); if (!includeFirstLine) { includeFirstLine= true; continue; } String indent= null; if (line.startsWith(COMMENT)) { String commentedLine= line.substring(2); // line is empty if (commentedLine.trim().length() == 0) continue; indent= COMMENT + getIndentOfLine(commentedLine); } else { // line is empty if (line.trim().length() == 0) continue; indent=getIndentOfLine(line); } final int indentSize= calculateDisplayedWidth(indent, tabWidth); if (indentSize < minIndentSize) minIndentSize= indentSize; } return minIndentSize == Integer.MAX_VALUE ? 0 : minIndentSize; } /** * Returns the displayed width of a string, taking in account the displayed tab width. * The result can be compared against the print margin. */ private static int calculateDisplayedWidth(String string, int tabWidth) { int column= 0; for (int i= 0; i < string.length(); i++) if ('\t' == string.charAt(i)) column += tabWidth - (column % tabWidth); else column++; return column; } private static boolean isLineEmpty(IDocument document, int line) throws BadLocationException { IRegion region= document.getLineInformation(line); String string= document.get(region.getOffset(), region.getLength()); return string.trim().length() == 0; } private int getIndentSize(IDocument document, DocumentCommand command) { StringBuffer buffer= new StringBuffer(); int docLength= document.getLength(); if (command.offset == -1 || docLength == 0) return 0; try { int p= (command.offset == docLength ? command.offset - 1 : command.offset); int line= document.getLineOfOffset(p); IRegion region= document.getLineInformation(line); String string= document.get(region.getOffset(), command.offset - region.getOffset()); if (line != 0 && string.trim().length() == 0) --line; while (line != 0 && isLineEmpty(document, line)) --line; int start= document.getLineOffset(line); // if line is at end of a javadoc comment, take the indent from the comment's begin line IDocumentPartitioner partitioner= document.getDocumentPartitioner(); if (partitioner != null) { ITypedRegion typedRegion= partitioner.getPartition(start); if (JavaPartitionScanner.JAVA_DOC.equals(typedRegion.getType())) start= document.getLineInformationOfOffset(typedRegion.getOffset()).getOffset(); else if (JavaPartitionScanner.JAVA_SINGLE_LINE_COMMENT.equals(typedRegion.getType())) { buffer.append(COMMENT); start += 2; } } int whiteend= findEndOfWhiteSpace(document, start, command.offset); buffer.append(document.get(start, whiteend - start)); if (getBracketCount(document, start, command.offset, true) > 0) { buffer.append(createIndent(1, useSpaces())); } } catch (BadLocationException e) { JavaPlugin.log(e); } return calculateDisplayedWidth(buffer.toString(), getTabWidth()); } private String getBlockIndent(IDocument d, DocumentCommand c) { if (c.offset < 0 || d.getLength() == 0) return null; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); // evaluate the line with the opening bracket that matches out closing bracket int indLine= findMatchingOpenBracket(d, line, c.offset, 1); if (indLine != -1) // take the indent of the found line return getIndentOfLine(d, indLine); } catch (BadLocationException e) { JavaPlugin.log(e); } return null; } private static final class LineIterator implements Iterator { /** The document to iterator over. */ private final IDocument fDocument; /** The line index. */ private int fLineIndex; /** * Creates a line iterator. */ public LineIterator(String string) { fDocument= new Document(string); } /* * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return fLineIndex != fDocument.getNumberOfLines(); } /* * @see java.util.Iterator#next() */ public Object next() { try { IRegion region= fDocument.getLineInformation(fLineIndex++); return fDocument.get(region.getOffset(), region.getLength()); } catch (BadLocationException e) { JavaPlugin.log(e); throw new NoSuchElementException(); } } /* * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } } private static String createIndent(int level, boolean useSpaces) { StringBuffer buffer= new StringBuffer(); if (useSpaces) { int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); int width= level * tabWidth; for (int i= 0; i != width; ++i) buffer.append(' '); } else { for (int i= 0; i != level; ++i) buffer.append('\t'); } return buffer.toString(); } /** * Extends the string to match displayed width. * String is either the empty string or "//" and should not contain whites. */ private static String changePrefix(String string, int displayedWidth, boolean useSpaces, int tabWidth) { // assumption: string contains no whitspaces final StringBuffer buffer= new StringBuffer(string); int column= calculateDisplayedWidth(buffer.toString(), tabWidth); if (column > displayedWidth) return string; if (useSpaces) { while (column != displayedWidth) { buffer.append(' '); ++column; } } else { while (column != displayedWidth) { if (column + tabWidth - (column % tabWidth) <= displayedWidth) { buffer.append('\t'); column += tabWidth - (column % tabWidth); } else { buffer.append(' '); ++column; } } } return buffer.toString(); } /** * Formats a paragraph such that the first non-empty line of the paragraph * will have an indent of size newIndentSize. */ private String format(String paragraph, int newIndentSize, String lineDelimiter, boolean indentFirstLine) { final int tabWidth= getTabWidth(); final int firstLineIndentSize= getIndentSizeOfFirstLine(paragraph, indentFirstLine, tabWidth); final int minIndentSize= getMinimalIndentSize(paragraph, indentFirstLine, tabWidth); if (newIndentSize < firstLineIndentSize - minIndentSize) newIndentSize= firstLineIndentSize - minIndentSize; final StringBuffer buffer= new StringBuffer(); for (final Iterator iterator= new LineIterator(paragraph); iterator.hasNext();) { String line= (String) iterator.next(); if (indentFirstLine) { String lineIndent= null; if (line.startsWith(COMMENT)) lineIndent= COMMENT + getIndentOfLine(line.substring(2)); else lineIndent= getIndentOfLine(line); String lineContent= line.substring(lineIndent.length()); if (lineContent.length() == 0) { // line was empty; insert as is buffer.append(line); } else { int indentSize= calculateDisplayedWidth(lineIndent, tabWidth); int deltaSize= newIndentSize - firstLineIndentSize; lineIndent= changePrefix(lineIndent.trim(), indentSize + deltaSize, useSpaces(), tabWidth); buffer.append(lineIndent); buffer.append(lineContent); } } else { indentFirstLine= true; buffer.append(line); } if (iterator.hasNext()) buffer.append(lineDelimiter); } return buffer.toString(); } private boolean equalsDelimiter(IDocument d, String txt) { String[] delimiters= d.getLegalLineDelimiters(); for (int i= 0; i < delimiters.length; i++) { if (txt.equals(delimiters[i])) return true; } return false; } private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) { if (command.text.charAt(0) == '}') smartInsertAfterBracket(document, command); } /* * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument d, DocumentCommand c) { if (c.length == 0 && c.text != null && equalsDelimiter(d, c.text)) smartIndentAfterNewLine(d, c); else if (c.text.length() == 1) smartIndentAfterBlockDelimiter(d, c); else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE)) smartPaste(d, c); clearCachedValues(); } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } private boolean useSpaces() { if (fUseSpaces == null) fUseSpaces= new Boolean(JavaCore.SPACE.equals(JavaCore.getOptions().get(JavaCore.FORMATTER_TAB_CHAR))); return fUseSpaces.booleanValue(); } private int getTabWidth() { if (fTabWidth == -1) fTabWidth= JavaPlugin.getDefault().getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH); return fTabWidth; } private void clearCachedValues() { fTabWidth= -1; fUseSpaces= null; } }
27,636
Bug 27636 Organize Import ordering differs for different VMs
Build 20021203 OrganizeImportTest.testBaseGroups1 failed because the import ordering was different. If fixed the test by looking at the VM version and then do different asserts. However this is just a workaround to make the tests run again. The import order must not depend on the VM version. Please remove the VM version check in the test when this PR is fixed.
verified fixed
b2a1cfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:08:27Z
2002-12-04T11:06:40Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/AddImportTest.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui.tests.core; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; import org.eclipse.jdt.internal.corext.util.TypeInfo; public class AddImportTest extends TestCase { private static final Class THIS= AddImportTest.class; private IJavaProject fJProject1; public AddImportTest(String name) { super(name); } public static Test suite() { if (true) { return new TestSuite(THIS); } else { TestSuite suite= new TestSuite(); suite.addTest(new AddImportTest("testAddImports_bug25113")); return suite; } } protected void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null); } protected void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); } private IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) { return new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { assertTrue(name + "-query-nchoices1", choices.length == openChoices.length); assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length); if (nEntries != null) { for (int i= 0; i < nEntries.length; i++) { assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]); } } TypeInfo[] res= new TypeInfo[openChoices.length]; for (int i= 0; i < openChoices.length; i++) { TypeInfo[] selection= openChoices[i]; assertNotNull(name + "-query-setset" + i, selection); assertTrue(name + "-query-setlen" + i, selection.length > 0); TypeInfo found= null; for (int k= 0; k < selection.length; k++) { if (selection[k].getFullyQualifiedName().equals(choices[i])) { found= selection[k]; } } assertNotNull(name + "-query-notfound" + i, found); res[i]= found; } return res; } }; } private void assertImports(ICompilationUnit cu, String[] imports) throws Exception { IImportDeclaration[] desc= cu.getImports(); assertTrue(cu.getElementName() + "-count", desc.length == imports.length); for (int i= 0; i < imports.length; i++) { assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]); } } private static final int printRange= 6; public static void assertEqualString(String str1, String str2) { int len1= Math.min(str1.length(), str2.length()); int diffPos= -1; for (int i= 0; i < len1; i++) { if (str1.charAt(i) != str2.charAt(i)) { diffPos= i; break; } } if (diffPos == -1 && str1.length() != str2.length()) { diffPos= len1; } if (diffPos != -1) { int diffAhead= Math.max(0, diffPos - printRange); int diffAfter= Math.min(str1.length(), diffPos + printRange); String diffStr= str1.substring(diffAhead, diffPos) + '^' + str1.substring(diffPos, diffAfter); assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + str2, false); } } public void testAddImports1() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.util.Map;\n"); buf.append("\n"); buf.append("import pack.List;\n"); buf.append("import pack.List2;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "com", "pack" }; ImportsStructure imports= new ImportsStructure(cu, order, 2, true); imports.addImport("java.net.Socket"); imports.addImport("p.A"); imports.addImport("com.something.Foo"); imports.create(true, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.net.Socket;\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.util.Map;\n"); buf.append("\n"); buf.append("import com.something.Foo;\n"); buf.append("\n"); buf.append("import p.A;\n"); buf.append("\n"); buf.append("import pack.List;\n"); buf.append("import pack.List2;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testAddImports2() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "java.util", "com", "pack" }; ImportsStructure imports= new ImportsStructure(cu, order, 2, true); imports.addImport("java.x.Socket"); imports.create(true, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.x.Socket;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testAddImports_bug23078() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import p.A.*;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { }; ImportsStructure imports= new ImportsStructure(cu, order, 2, true); imports.addImport("p.Inner"); imports.create(true, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import p.Inner;\n"); buf.append("import p.A.*;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testAddImports_bug25113() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.awt.Panel;\n"); buf.append("\n"); buf.append("import java.math.BigInteger;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java.awt", "java" }; ImportsStructure imports= new ImportsStructure(cu, order, 99, true); imports.addImport("java.applet.Applet"); imports.create(true, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.awt.Panel;\n"); buf.append("\n"); buf.append("import java.applet.Applet;\n"); buf.append("import java.math.BigInteger;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } }
27,636
Bug 27636 Organize Import ordering differs for different VMs
Build 20021203 OrganizeImportTest.testBaseGroups1 failed because the import ordering was different. If fixed the test by looking at the VM version and then do different asserts. However this is just a workaround to make the tests run again. The import order must not depend on the VM version. Please remove the VM version check in the test when this PR is fixed.
verified fixed
b2a1cfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:08:27Z
2002-12-04T11:06:40Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/ImportOrganizeTest.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.ui.tests.core; import java.io.File; import java.util.zip.ZipFile; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.JavaTestPlugin; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation; import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery; import org.eclipse.jdt.internal.corext.util.TypeInfo; public class ImportOrganizeTest extends CoreTests { private static final Class THIS= ImportOrganizeTest.class; private IJavaProject fJProject1; public ImportOrganizeTest(String name) { super(name); } public static Test suite() { if (false) { return new TestSuite(THIS); } else { TestSuite suite= new TestSuite(); suite.addTest(new ImportOrganizeTest("testImportStructureOnNonExistingCU")); return suite; } } protected void setUp() throws Exception { fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null); } protected void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); } private IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) { return new IChooseImportQuery() { public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) { assertTrue(name + "-query-nchoices1", choices.length == openChoices.length); assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length); if (nEntries != null) { for (int i= 0; i < nEntries.length; i++) { assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]); } } TypeInfo[] res= new TypeInfo[openChoices.length]; for (int i= 0; i < openChoices.length; i++) { TypeInfo[] selection= openChoices[i]; assertNotNull(name + "-query-setset" + i, selection); assertTrue(name + "-query-setlen" + i, selection.length > 0); TypeInfo found= null; for (int k= 0; k < selection.length; k++) { if (selection[k].getFullyQualifiedName().equals(choices[i])) { found= selection[k]; } } assertNotNull(name + "-query-notfound" + i, found); res[i]= found; } return res; } }; } private void assertImports(ICompilationUnit cu, String[] imports) throws Exception { IImportDeclaration[] desc= cu.getImports(); assertTrue(cu.getElementName() + "-count", desc.length == imports.length); for (int i= 0; i < imports.length; i++) { assertEquals(cu.getElementName() + "-cmpentries" + i, desc[i].getElementName(), imports[i]); } } public void test1() throws Exception { File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC); assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists()); ZipFile zipfile= new ZipFile(junitSrcArchive); JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile); ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java")); assertNotNull("BaseTestRunner.java", cu); IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent(); IPackageFragment pack= root.createPackageFragment("mytest", true, null); ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java"); colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 }); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); assertImports(cu, new String[] { "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream", "java.io.IOException", "java.io.InputStream", "java.io.PrintWriter", "java.io.StringReader", "java.io.StringWriter", "java.lang.reflect.InvocationTargetException", "java.lang.reflect.Method", "java.text.NumberFormat", "java.util.Properties", "junit.framework.Test", "junit.framework.TestListener", "junit.framework.TestSuite" }); } public void test1WithOrder() throws Exception { File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC); assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists()); ZipFile zipfile= new ZipFile(junitSrcArchive); JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile); ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/BaseTestRunner.java")); assertNotNull("BaseTestRunner.java", cu); IPackageFragmentRoot root= (IPackageFragmentRoot)cu.getParent().getParent(); IPackageFragment pack= root.createPackageFragment("mytest", true, null); ICompilationUnit colidingCU= pack.getCompilationUnit("TestListener.java"); colidingCU.createType("public abstract class TestListener {\n}\n", null, true, null); String[] order= new String[] { "junit", "java.text", "java.io", "java" }; IChooseImportQuery query= createQuery("BaseTestRunner", new String[] { "junit.framework.TestListener" }, new int[] { 2 }); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); assertImports(cu, new String[] { "junit.framework.Test", "junit.framework.TestListener", "junit.framework.TestSuite", "java.text.NumberFormat", "java.io.BufferedReader", "java.io.File", "java.io.FileInputStream", "java.io.IOException", "java.io.InputStream", "java.io.PrintWriter", "java.io.StringReader", "java.io.StringWriter", "java.lang.reflect.InvocationTargetException", "java.lang.reflect.Method", "java.util.Properties" }); } public void test2() throws Exception { File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC); assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists()); ZipFile zipfile= new ZipFile(junitSrcArchive); JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile); ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/LoadingTestCollector.java")); assertNotNull("LoadingTestCollector.java", cu); String[] order= new String[0]; IChooseImportQuery query= createQuery("LoadingTestCollector", new String[] { }, new int[] { }); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); assertImports(cu, new String[] { "java.lang.reflect.Constructor", "java.lang.reflect.Method", "java.lang.reflect.Modifier", "junit.framework.Test" }); } public void test3() throws Exception { File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC); assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists()); ZipFile zipfile= new ZipFile(junitSrcArchive); JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile); ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/runner/TestCaseClassLoader.java")); assertNotNull("TestCaseClassLoader.java", cu); String[] order= new String[0]; IChooseImportQuery query= createQuery("TestCaseClassLoader", new String[] { }, new int[] { }); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 3, false, true, true, query); op.run(null); assertImports(cu, new String[] { "java.io.*", "java.net.URL", "java.util.*", "java.util.zip.ZipEntry", "java.util.zip.ZipFile", }); } public void test4() throws Exception { File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC); assertTrue("junit src not found", junitSrcArchive != null && junitSrcArchive.exists()); ZipFile zipfile= new ZipFile(junitSrcArchive); JavaProjectHelper.addSourceContainerWithImport(fJProject1, "src", zipfile); ICompilationUnit cu= (ICompilationUnit) fJProject1.findElement(new Path("junit/textui/TestRunner.java")); assertNotNull("TestRunner.java", cu); String[] order= new String[0]; IChooseImportQuery query= createQuery("TestRunner", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); assertImports(cu, new String[] { "java.io.PrintStream", "java.util.Enumeration", "junit.framework.AssertionFailedError", "junit.framework.Test", "junit.framework.TestFailure", "junit.framework.TestResult", "junit.framework.TestSuite", "junit.runner.BaseTestRunner", "junit.runner.StandardTestSuiteLoader", "junit.runner.TestSuiteLoader", "junit.runner.Version" }); } public void testVariousTypeReferences() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack= sourceFolder.createPackageFragment("test", false, null); for (int ch= 'A'; ch < 'M'; ch++) { String name= String.valueOf((char) ch); ICompilationUnit cu= pack.getCompilationUnit(name + ".java"); String content= "public class " + name + " {}"; cu.createType(content, null, false, null); } for (int ch= 'A'; ch < 'M'; ch++) { String name= "I" + String.valueOf((char) ch); ICompilationUnit cu= pack.getCompilationUnit(name + ".java"); String content= "public interface " + name + " {}"; cu.createType(content, null, false, null); } StringBuffer buf= new StringBuffer(); buf.append("public class ImportTest extends A implements IA, IB {\n"); buf.append(" private B fB;\n"); buf.append(" private Object fObj= new C();\n"); buf.append(" public IB foo(IC c, ID d) throws IOException {\n"); buf.append(" Object local= (D) fObj;\n"); buf.append(" if (local instanceof E) {};\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); pack= sourceFolder.createPackageFragment("other", false, null); ICompilationUnit cu= pack.getCompilationUnit("ImportTest.java"); cu.createType(buf.toString(), null, false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("ImportTest", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); assertImports(cu, new String[] { "java.io.IOException", "test.A", "test.B", "test.C", "test.D", "test.E", "test.IA", "test.IB", "test.IC", "test.ID", }); } public void testInnerClassVisibility() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" protected static class C1 {\n"); buf.append(" public static class C2 {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("C.java", buf.toString(), false, null); IPackageFragment pack2= sourceFolder.createPackageFragment("test2", false, null); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import test2.A.A1;\n"); buf.append("import test2.A.A1.A2;\n"); buf.append("import test2.A.A1.A2.A3;\n"); buf.append("import test2.A.B1;\n"); buf.append("import test2.A.B1.B2;\n"); buf.append("import test1.C;\n"); buf.append("import test1.C.C1.C2;\n"); buf.append("public class A {\n"); buf.append(" public static class A1 {\n"); buf.append(" public static class A2 {\n"); buf.append(" public static class A3 {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append(" public static class B1 {\n"); buf.append(" public static class B2 {\n"); buf.append(" }\n"); buf.append(" public static class B3 {\n"); buf.append(" public static class B4 extends C {\n"); buf.append(" B4 b4;\n"); buf.append(" B3 b3;\n"); buf.append(" B2 b2;\n"); buf.append(" B1 b1;\n"); buf.append(" A1 a1;\n"); buf.append(" A2 a2;\n"); buf.append(" A3 a3;\n"); buf.append(" C1 c1;\n"); buf.append(" C2 c2;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu2= pack2.createCompilationUnit("A.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("A", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu2, order, 99, false, true, true, query); op.run(null); assertImports(cu2, new String[] { "test1.C", "test1.C.C1.C2", "test2.A.A1.A2", "test2.A.A1.A2.A3" }); } public void testClearImports() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Vector;\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testNewImports() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testReplaceImports() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testClearImportsNoPackage() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.getPackageFragment(""); StringBuffer buf= new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("public class C {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("public class C {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testNewImportsNoPackage() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.getPackageFragment(""); StringBuffer buf= new StringBuffer(); buf.append("public class C extends Vector {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testReplaceImportsNoPackage() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.getPackageFragment(""); StringBuffer buf= new StringBuffer(); buf.append("import java.util.Set;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C extends Vector {\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testCommentAfterImport() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\r\n"); buf.append("\r\n"); buf.append("import x;\r\n"); buf.append("import java.util.Vector; // comment\r\n"); buf.append("\r\n"); buf.append("public class C {\r\n"); buf.append(" Vector v;\r\n"); buf.append("}\r\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[0]; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\r\n"); buf.append("\r\n"); buf.append("import java.util.Vector;\r\n"); buf.append("\r\n"); buf.append("public class C {\r\n"); buf.append(" Vector v;\r\n"); buf.append("}\r\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testImportToStar() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class List {\n"); buf.append("}\n"); pack2.createCompilationUnit("List.java", buf.toString(), false, null); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.util.Map;\n"); buf.append("\n"); buf.append("import pack.List;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List v4;\n"); buf.append(" String v5;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "pack" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.*;\n"); buf.append("\n"); buf.append("import pack.List;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List v4;\n"); buf.append(" String v5;\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testImportToStarWithExplicit() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("pack", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class List {\n"); buf.append("}\n"); pack2.createCompilationUnit("List.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class List2 {\n"); buf.append("}\n"); pack2.createCompilationUnit("List2.java", buf.toString(), false, null); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.util.Map;\n"); buf.append("\n"); buf.append("import pack.List;\n"); buf.append("import pack.List2;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List v4;\n"); buf.append(" List2 v5;\n"); buf.append(" String v6;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "pack" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.*;\n"); buf.append("\n"); buf.append("import pack.*;\n"); buf.append("import pack.List;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List v4;\n"); buf.append(" List2 v5;\n"); buf.append(" String v6;\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testImportFromDefault() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null); StringBuffer buf= new StringBuffer(); buf.append("public class List1 {\n"); buf.append("}\n"); pack2.createCompilationUnit("List1.java", buf.toString(), false, null); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.util.Map;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List1 v4;\n"); buf.append(" String v5;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "pack" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import List1;\n"); buf.append("\n"); buf.append("import java.util.*;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List1 v4;\n"); buf.append(" String v5;\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testImportFromDefaultWithStar() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("", false, null); StringBuffer buf= new StringBuffer(); buf.append("public class List1 {\n"); buf.append("}\n"); pack2.createCompilationUnit("List1.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("public class List2 {\n"); buf.append("}\n"); pack2.createCompilationUnit("List2.java", buf.toString(), false, null); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Set;\n"); buf.append("import java.util.Vector;\n"); buf.append("import java.util.Map;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List1 v4;\n"); buf.append(" List2 v5;\n"); buf.append(" String v6;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "pack" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 2, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import List1;\n"); buf.append("import List2;\n"); buf.append("\n"); buf.append("import java.util.*;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" Vector v;\n"); buf.append(" Set v2;\n"); buf.append(" Map v3;\n"); buf.append(" List1 v4;\n"); buf.append(" List2 v5;\n"); buf.append(" String v6;\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testImportOfMemberFromLocal() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" public void foo() {\n"); buf.append(" class Local {\n"); buf.append(" class LocalMember {\n"); buf.append(" }\n"); buf.append(" LocalMember x;\n"); buf.append(" Vector v;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "pack" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.Vector;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" public void foo() {\n"); buf.append(" class Local {\n"); buf.append(" class LocalMember {\n"); buf.append(" }\n"); buf.append(" LocalMember x;\n"); buf.append(" Vector v;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testGroups1() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack0;\n"); buf.append("public class List1 {\n"); buf.append("}\n"); pack2.createCompilationUnit("List1.java", buf.toString(), false, null); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" File f;\n"); buf.append(" IOException f1;\n"); buf.append(" RandomAccessFile f2;\n"); buf.append(" ArrayList f3;\n"); buf.append(" List1 f4;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java.io", "java.util" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.io.File;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.io.RandomAccessFile;\n"); buf.append("\n"); buf.append("import java.util.ArrayList;\n"); buf.append("\n"); buf.append("import pack0.List1;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" File f;\n"); buf.append(" IOException f1;\n"); buf.append(" RandomAccessFile f2;\n"); buf.append(" ArrayList f3;\n"); buf.append(" List1 f4;\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testBaseGroups1() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack0;\n"); buf.append("public class List1 {\n"); buf.append("}\n"); pack2.createCompilationUnit("List1.java", buf.toString(), false, null); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("public class C {\n"); buf.append(" File f;\n"); buf.append(" IOException f1;\n"); buf.append(" RandomAccessFile f2;\n"); buf.append(" ArrayList f3;\n"); buf.append(" List1 f4;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); String[] order= new String[] { "java", "java.io" }; IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.ArrayList;\n"); buf.append("\n"); String vm= System.getProperty("java.version"); if (vm != null && vm.startsWith("1.4")) { buf.append("import java.io.File;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.io.RandomAccessFile;\n"); buf.append("\n"); buf.append("import pack0.List1;\n"); } else { buf.append("import pack0.List1;\n"); buf.append("\n"); buf.append("import java.io.File;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.io.RandomAccessFile;\n"); } buf.append("\n"); buf.append("public class C {\n"); buf.append(" File f;\n"); buf.append(" IOException f1;\n"); buf.append(" RandomAccessFile f2;\n"); buf.append(" ArrayList f3;\n"); buf.append(" List1 f4;\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void testVisibility_bug26746() throws Exception { IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); IPackageFragment pack2= sourceFolder.createPackageFragment("pack0", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack0;\n"); buf.append("public interface MyInterface {\n"); buf.append(" public interface MyInnerInterface {\n"); buf.append(" }\n"); buf.append("}\n"); pack2.createCompilationUnit("MyInterface.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package pack0;\n"); buf.append("\n"); buf.append("import pack0.MyInterface.MyInnerInterface;\n"); buf.append("public class MyClass implements MyInterface {\n"); buf.append(" public MyInnerInterface myMethod() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack2.createCompilationUnit("MyClass.java", buf.toString(), false, null); String[] order= new String[] {}; IChooseImportQuery query= createQuery("MyClass", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack0;\n"); buf.append("\n"); buf.append("public class MyClass implements MyInterface {\n"); buf.append(" public MyInnerInterface myMethod() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); } public void test5() throws Exception { String[] types= new String[] { "org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader", "org.eclipse.core.resources.IContainer", "org.eclipse.core.runtime.IPath", "org.eclipse.core.runtime.CoreException", "org.eclipse.core.resources.IResource", "org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer" }; String[] order= new String[] { "org.eclipse.jdt", "org.eclipse" }; IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); for (int i= 0; i < types.length; i++) { String pack= Signature.getQualifier(types[i]); String name= Signature.getSimpleName(types[i]); IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null); StringBuffer buf= new StringBuffer(); buf.append("package "); buf.append(pack); buf.append(";\n"); buf.append("public class "); buf.append(name); buf.append(" {\n"); buf.append("}\n"); pack2.createCompilationUnit(name + ".java", buf.toString(), false, null); } StringBuffer body= new StringBuffer(); body.append("public class C {\n"); for (int i= 0; i < types.length; i++) { String name= Signature.getSimpleName(types[i]); body.append(name); body.append(" a"); body.append(i); body.append(";\n"); } body.append("}\n"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append(body.toString()); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, 99, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;\n"); buf.append("import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;\n"); buf.append("\n"); buf.append("import org.eclipse.core.resources.IContainer;\n"); buf.append("import org.eclipse.core.resources.IResource;\n"); buf.append("import org.eclipse.core.runtime.CoreException;\n"); buf.append("import org.eclipse.core.runtime.IPath;\n"); buf.append("\n"); buf.append(body.toString()); assertEqualString(cu.getSource(), buf.toString()); } public void test_bug25773() throws Exception { String[] types= new String[] { "java.util.Vector", "java.util.Map", "java.util.Set", "org.eclipse.gef.X1", "org.eclipse.gef.X2", "org.eclipse.gef.X3", "org.eclipse.core.runtime.IAdaptable", "org.eclipse.draw2d.IFigure", "org.eclipse.draw2d.LayoutManager", "org.eclipse.draw2d.geometry.Point", "org.eclipse.draw2d.geometry.Rectangle", "org.eclipse.swt.accessibility.ACC", "org.eclipse.swt.accessibility.AccessibleControlEvent" }; String[] order= new String[] { "java", "org.eclipse", "org.eclipse.gef", "org.eclipse.draw2d", "org.eclipse.gef.examples" }; int threshold= 3; IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); for (int i= 0; i < types.length; i++) { String pack= Signature.getQualifier(types[i]); if (!pack.startsWith("java.")) { String name= Signature.getSimpleName(types[i]); IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null); StringBuffer buf= new StringBuffer(); buf.append("package "); buf.append(pack); buf.append(";\n"); buf.append("public class "); buf.append(name); buf.append(" {\n"); buf.append("}\n"); pack2.createCompilationUnit(name + ".java", buf.toString(), false, null); } } StringBuffer body= new StringBuffer(); body.append("public class C {\n"); for (int i= 0; i < types.length; i++) { String name= Signature.getSimpleName(types[i]); body.append(name); body.append(" a"); body.append(i); body.append(";\n"); } body.append("}\n"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append(body.toString()); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, threshold, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import java.util.*;\n"); buf.append("\n"); buf.append("import org.eclipse.core.runtime.IAdaptable;\n"); buf.append("import org.eclipse.swt.accessibility.ACC;\n"); buf.append("import org.eclipse.swt.accessibility.AccessibleControlEvent;\n"); buf.append("\n"); buf.append("import org.eclipse.gef.*;\n"); buf.append("\n"); buf.append("import org.eclipse.draw2d.IFigure;\n"); buf.append("import org.eclipse.draw2d.LayoutManager;\n"); buf.append("import org.eclipse.draw2d.geometry.Point;\n"); buf.append("import org.eclipse.draw2d.geometry.Rectangle;\n"); buf.append("\n"); buf.append(body.toString()); assertEqualString(cu.getSource(), buf.toString()); } public void test_bug25113() throws Exception { String[] types= new String[] { "com.mycompany.Class1", "com.foreigncompany.Class2", "com.foreigncompany.Class3", "com.mycompany.Class4", "com.misc.Class5" }; String[] order= new String[] { "com", "com.foreigncompany", "com.mycompany" }; int threshold= 99; IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); for (int i= 0; i < types.length; i++) { String pack= Signature.getQualifier(types[i]); if (!pack.startsWith("java.")) { String name= Signature.getSimpleName(types[i]); IPackageFragment pack2= sourceFolder.createPackageFragment(pack, false, null); StringBuffer buf= new StringBuffer(); buf.append("package "); buf.append(pack); buf.append(";\n"); buf.append("public class "); buf.append(name); buf.append(" {\n"); buf.append("}\n"); pack2.createCompilationUnit(name + ".java", buf.toString(), false, null); } } StringBuffer body= new StringBuffer(); body.append("public class C {\n"); for (int i= 0; i < types.length; i++) { String name= Signature.getSimpleName(types[i]); body.append(name); body.append(" a"); body.append(i); body.append(";\n"); } body.append("}\n"); IPackageFragment pack1= sourceFolder.createPackageFragment("pack1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append(body.toString()); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); IChooseImportQuery query= createQuery("C", new String[] {}, new int[] {}); OrganizeImportsOperation op= new OrganizeImportsOperation(cu, order, threshold, false, true, true, query); op.run(null); buf= new StringBuffer(); buf.append("package pack1;\n"); buf.append("\n"); buf.append("import com.misc.Class5;\n"); buf.append("\n"); buf.append("import com.foreigncompany.Class2;\n"); buf.append("import com.foreigncompany.Class3;\n"); buf.append("\n"); buf.append("import com.mycompany.Class1;\n"); buf.append("import com.mycompany.Class4;\n"); buf.append("\n"); buf.append(body.toString()); assertEqualString(cu.getSource(), buf.toString()); } public void testImportStructureOnNonExistingCU() throws Exception { IJavaProject project1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); IPackageFragmentRoot sourceFolder= JavaProjectHelper.addSourceContainer(project1, "src"); IPackageFragment pack1= sourceFolder.createPackageFragment("test1", false, null); ICompilationUnit unit= pack1.getCompilationUnit("A.java"); ICompilationUnit wc= (ICompilationUnit) unit.getWorkingCopy(null, JavaUI.getBufferFactory(), null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public Object foo() {\n"); buf.append(" }\n"); buf.append("}\n"); wc.getBuffer().setContents(buf.toString()); String[] order= new String[] { "com", "com.foreigncompany", "com.mycompany" }; int threshold= 99; ImportsStructure importsStructure= new ImportsStructure(wc, order, threshold, true); importsStructure.addImport("java.util.HashMap"); importsStructure.create(false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.util.HashMap;\n"); buf.append("\n"); buf.append("public class A {\n"); buf.append(" public Object foo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualStringIgnoreDelim(wc.getSource(), buf.toString()); } }
27,636
Bug 27636 Organize Import ordering differs for different VMs
Build 20021203 OrganizeImportTest.testBaseGroups1 failed because the import ordering was different. If fixed the test by looking at the VM version and then do different asserts. However this is just a workaround to make the tests run again. The import order must not depend on the VM version. Please remove the VM version check in the test when this PR is fixed.
verified fixed
b2a1cfb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-02-17T17:08:27Z
2002-12-04T11:06:40Z
org.eclipse.jdt.ui/core