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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test958.java
|
package duplicates_in;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test958 {
private Object fO;
public void method0() {
/*[*/Object o2= fO;/*]*/
fO= o2;
}
public void method1() {
Object o= fO;
fO= o;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test959.java
|
package duplicates_in;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test959 {
public void foo() {
int x= 10;
int y= /*[*/x/*]*/;
x= 20;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test960.java
|
package duplicates_in;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test960 {
private Object fO;
public void foo() {
/*[*/fO= new Object();/*]*/
}
public void bar() {
foo();
fO= new Object();
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test961.java
|
package duplicates_in;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test961 {
private Object fO;
public void foo(Object o) {
/*[*/fO= o;/*]*/
}
public void bar(Object x) {
foo(x);
fO= x;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test962.java
|
package duplicates_in;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test962 {
private Object object;
public A_test962() {
this.object = new Object();
System.out.println(/*[*/this.object/*]*/);
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test963.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_in/A_test964.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test957.java
|
package duplicates_out;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test957 {
public void f() {
int i = 17;
int k = 1;
i = extracted(i);
k = extracted(k);
System.out.println(i);
System.out.println(k);
}
protected int extracted(int i) {
/*[*/i++;/*]*/
return i;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test958.java
|
package duplicates_out;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test958 {
private Object fO;
public void method0() {
Object o2 = extracted();
fO= o2;
}
protected Object extracted() {
/*[*/Object o2= fO;/*]*/
return o2;
}
public void method1() {
Object o = extracted();
fO= o;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test959.java
|
package duplicates_out;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test959 {
public void foo() {
int x= 10;
int y= extracted(x);
x= 20;
}
protected int extracted(int x) {
return /*[*/x/*]*/;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test960.java
|
package duplicates_out;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test960 {
private Object fO;
public void foo() {
extracted();
}
protected void extracted() {
/*[*/fO= new Object();/*]*/
}
public void bar() {
foo();
extracted();
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test961.java
|
package duplicates_out;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test961 {
private Object fO;
public void foo(Object o) {
extracted(o);
}
protected void extracted(Object o) {
/*[*/fO= o;/*]*/
}
public void bar(Object x) {
foo(x);
extracted(x);
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test962.java
|
package duplicates_out;
// don't extract second occurence of
// 2 since it is in a inner class
public class A_test962 {
private Object object;
public A_test962() {
this.object = new Object();
System.out.println(extracted());
}
protected Object extracted() {
return /*[*/this.object/*]*/;
}
}
|
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test963.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/duplicates_out/A_test964.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui.tests.refactoring/test
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui/core
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui/core
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/InlineMethodRefactoring.java
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
org.eclipse.jdt.ui/core
| |
53,851
|
Bug 53851 extract method in anonymous class introduces error [refactoring]
|
Test case: public class Bug { void test () { new Object () { public void yes () { System.out.println ("hello world"); } }; System.out.println ("hello world"); } } Three (possibly related) problems: 1. Select the first print statement (whole line). Refactor:Extract Method..., enter some name and press OK, leaving "replace 1 duplicate code fragment" checked. The method is created inside the anonymous class but called from outside. 2. Select the second print statement (whole line). Refactor:Extract Method... The duplicate code fragment is not recognized. 3. Select only "println" in either print statement. Refactor:Extract Method..., enter some name and press OK. You get a strange error message: "Cannot determine expression's return type. Using void instead." Pressing Continue produces meaningless code.
|
resolved fixed
|
974ed09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:06:14Z
| 2004-03-05T15:20:00Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SnippetFinder.java
| |
58,509
|
Bug 58509 [spell checking] ConcurrentModif.Exception in spelling plugin
|
20040407 Got this printed in the console (not .log!) java.util.ConcurrentModificationException at java.lang.Throwable.<init>(Throwable.java) at java.util.HashMap$HashIterator.nextEntry(HashMap.java) at java.util.HashMap$KeyIterator.next(HashMap.java) at org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker. fireEvent(DefaultSpellChecker.java) at org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker. execute(DefaultSpellChecker.java) at org.eclipse.jdt.internal.ui.text.spelling.SpellReconcileStrategy.reco ncile(SpellReconcileStrategy.java) at org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy.reconc ile(CompositeReconcilingStrategy.java) at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.rec oncile(JavaCompositeReconcilingStrategy.java) at org.eclipse.jface.text.reconciler.MonoReconciler.process (MonoReconcil er.java) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread .run(AbstractReconciler.java)
|
resolved fixed
|
d818204
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:09:14Z
| 2004-04-14T16:26:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/engine/DefaultSpellChecker.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.spelling.engine;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.jface.preference.IPreferenceStore;
/**
* Default spell checker for standard text.
*
* @since 3.0
*/
public class DefaultSpellChecker implements ISpellChecker {
/** Array of url prefixes */
public static final String[] URL_PREFIXES= new String[] { "http://", "https://", "www.", "ftp://", "ftps://", "news://", "mailto://" }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$
/**
* Does this word contain digits?
*
* @param word
* The word to check
* @return <code>true</code> iff this word contains digits, <code>false></code>
* otherwise
*/
protected static boolean isDigits(final String word) {
for (int index= 0; index < word.length(); index++) {
if (Character.isDigit(word.charAt(index)))
return true;
}
return false;
}
/**
* Does this word contain mixed-case letters?
*
* @param word
* The word to check
* @param sentence
* <code>true</code> iff the specified word starts a new
* sentence, <code>false</code> otherwise
* @return <code>true</code> iff the contains mixed-case letters, <code>false</code>
* otherwise
*/
protected static boolean isMixedCase(final String word, final boolean sentence) {
final int length= word.length();
boolean upper= Character.isUpperCase(word.charAt(0));
if (sentence && upper && (length > 1))
upper= Character.isUpperCase(word.charAt(1));
if (upper) {
for (int index= length - 1; index > 0; index--) {
if (Character.isLowerCase(word.charAt(index)))
return true;
}
} else {
for (int index= length - 1; index > 0; index--) {
if (Character.isUpperCase(word.charAt(index)))
return true;
}
}
return false;
}
/**
* Does this word contain upper-case letters only?
*
* @param word
* The word to check
* @return <code>true</code> iff this word only contains upper-case
* letters, <code>false</code> otherwise
*/
protected static boolean isUpperCase(final String word) {
for (int index= word.length() - 1; index >= 0; index--) {
if (Character.isLowerCase(word.charAt(index)))
return false;
}
return true;
}
/**
* Does this word look like an URL?
*
* @param word
* The word to check
* @return <code>true</code> iff this word looks like an URL, <code>false</code>
* otherwise
*/
protected static boolean isUrl(final String word) {
for (int index= 0; index < URL_PREFIXES.length; index++) {
if (word.startsWith(URL_PREFIXES[index]))
return true;
}
return false;
}
/** The dictionaries to use for spell-checking */
private final Set fDictionaries= new HashSet();
/** The words to be ignored */
private final Set fIgnored= new HashSet();
/** The spell event listeners */
private final Set fListeners= new HashSet();
/** The preference store */
private final IPreferenceStore fPreferences;
/**
* Creates a new default spell-checker.
*
* @param store
* The preference store for this spell-checker
*/
public DefaultSpellChecker(final IPreferenceStore store) {
fPreferences= store;
}
/*
* @see org.eclipse.spelling.done.ISpellChecker#addDictionary(org.eclipse.spelling.done.ISpellDictionary)
*/
public final void addDictionary(final ISpellDictionary dictionary) {
fDictionaries.add(dictionary);
}
/*
* @see org.eclipse.spelling.done.ISpellChecker#addListener(org.eclipse.spelling.done.ISpellEventListener)
*/
public final void addListener(final ISpellEventListener listener) {
fListeners.add(listener);
}
/*
* @see org.eclipse.jdt.ui.text.spelling.engine.ISpellChecker#acceptsWords()
*/
public boolean acceptsWords() {
ISpellDictionary dictionary= null;
for (final Iterator iterator= fDictionaries.iterator(); iterator.hasNext();) {
dictionary= (ISpellDictionary)iterator.next();
if (dictionary.acceptsWords())
return true;
}
return false;
}
/*
* @see org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellChecker#addWord(java.lang.String)
*/
public void addWord(final String word) {
final String addable= word.toLowerCase();
fIgnored.add(addable);
ISpellDictionary dictionary= null;
for (final Iterator iterator= fDictionaries.iterator(); iterator.hasNext();) {
dictionary= (ISpellDictionary)iterator.next();
dictionary.addWord(addable);
}
}
/*
* @see org.eclipse.jdt.ui.text.spelling.engine.ISpellChecker#checkWord(java.lang.String)
*/
public final void checkWord(final String word) {
fIgnored.remove(word.toLowerCase());
}
/*
* @see org.eclipse.spelling.done.ISpellChecker#execute(org.eclipse.spelling.ISpellCheckTokenizer)
*/
public void execute(final ISpellCheckIterator iterator) {
final boolean ignoreDigits= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_DIGITS);
final boolean ignoreMixed= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_MIXED);
final boolean ignoreSentence= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_SENTENCE);
final boolean ignoreUpper= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_UPPER);
final boolean ignoreURLS= fPreferences.getBoolean(ISpellCheckPreferenceKeys.SPELLING_IGNORE_URLS);
String word= null;
boolean starts= false;
while (iterator.hasNext()) {
word= (String)iterator.next();
if (word != null) {
if (!fIgnored.contains(word)) {
starts= iterator.startsSentence();
if (!isCorrect(word)) {
boolean isMixed= isMixedCase(word, true);
boolean isUpper= isUpperCase(word);
boolean isDigits= isDigits(word);
boolean isURL= isUrl(word);
if ( !ignoreMixed && isMixed || !ignoreUpper && isUpper || !ignoreDigits && isDigits || !ignoreURLS && isURL || !(isMixed || isUpper || isDigits || isURL))
fireEvent(new SpellEvent(this, word, iterator.getBegin(), iterator.getEnd(), starts, false));
} else {
if (!ignoreSentence && starts && Character.isLowerCase(word.charAt(0)))
fireEvent(new SpellEvent(this, word, iterator.getBegin(), iterator.getEnd(), true, true));
}
}
}
}
}
/**
* Fires the specified event.
*
* @param event
* Event to fire
*/
protected final void fireEvent(final ISpellEvent event) {
ISpellEventListener listener= null;
for (final Iterator iterator= fListeners.iterator(); iterator.hasNext();) {
listener= (ISpellEventListener)iterator.next();
listener.handle(event);
}
}
/*
* @see org.eclipse.spelling.done.ISpellChecker#getProposals(java.lang.String,boolean)
*/
public Set getProposals(final String word, final boolean sentence) {
ISpellDictionary dictionary= null;
final HashSet proposals= new HashSet();
for (final Iterator iterator= fDictionaries.iterator(); iterator.hasNext();) {
dictionary= (ISpellDictionary)iterator.next();
proposals.addAll(dictionary.getProposals(word, sentence));
}
return proposals;
}
/*
* @see org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellChecker#ignoreWord(java.lang.String)
*/
public final void ignoreWord(final String word) {
fIgnored.add(word.toLowerCase());
}
/*
* @see org.eclipse.jdt.internal.ui.text.spelling.engine.ISpellChecker#isCorrect(java.lang.String)
*/
public final boolean isCorrect(final String word) {
if (fIgnored.contains(word.toLowerCase()))
return true;
ISpellDictionary dictionary= null;
for (final Iterator iterator= fDictionaries.iterator(); iterator.hasNext();) {
dictionary= (ISpellDictionary)iterator.next();
if (dictionary.isCorrect(word))
return true;
}
return false;
}
/*
* @see org.eclipse.spelling.done.ISpellChecker#removeDictionary(org.eclipse.spelling.done.ISpellDictionary)
*/
public final void removeDictionary(final ISpellDictionary dictionary) {
fDictionaries.remove(dictionary);
}
/*
* @see org.eclipse.spelling.done.ISpellChecker#removeListener(org.eclipse.spelling.done.ISpellEventListener)
*/
public final void removeListener(final ISpellEventListener listener) {
fListeners.remove(listener);
}
}
|
58,509
|
Bug 58509 [spell checking] ConcurrentModif.Exception in spelling plugin
|
20040407 Got this printed in the console (not .log!) java.util.ConcurrentModificationException at java.lang.Throwable.<init>(Throwable.java) at java.util.HashMap$HashIterator.nextEntry(HashMap.java) at java.util.HashMap$KeyIterator.next(HashMap.java) at org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker. fireEvent(DefaultSpellChecker.java) at org.eclipse.jdt.internal.ui.text.spelling.engine.DefaultSpellChecker. execute(DefaultSpellChecker.java) at org.eclipse.jdt.internal.ui.text.spelling.SpellReconcileStrategy.reco ncile(SpellReconcileStrategy.java) at org.eclipse.jface.text.reconciler.CompositeReconcilingStrategy.reconc ile(CompositeReconcilingStrategy.java) at org.eclipse.jdt.internal.ui.text.JavaCompositeReconcilingStrategy.rec oncile(JavaCompositeReconcilingStrategy.java) at org.eclipse.jface.text.reconciler.MonoReconciler.process (MonoReconcil er.java) at org.eclipse.jface.text.reconciler.AbstractReconciler$BackgroundThread .run(AbstractReconciler.java)
|
resolved fixed
|
d818204
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T14:09:14Z
| 2004-04-14T16:26:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/spelling/engine/ISpellChecker.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.spelling.engine;
import java.util.Set;
/**
* Interface for spell-checkers.
*
* @since 3.0
*/
public interface ISpellChecker {
/**
* Adds a dictionary to the list of active dictionaries.
*
* @param dictionary
* The dictionary to add
*/
public void addDictionary(ISpellDictionary dictionary);
/**
* Adds a spell event listener to the active listeners.
*
* @param listener
* The listener to add
*/
public void addListener(ISpellEventListener listener);
/**
* Returns whether this spell checker accepts word additions.
*
* @return <code>true</code> if word additions are accepted, <code>false</code> otherwise
*/
public boolean acceptsWords();
/**
* Adds the specified word to the set of correct words.
*
* @param word
* The word to add to the set of correct words
*/
public void addWord(String word);
/**
* Checks the specified word until calling <code>ignoreWord(String)</code>.
*
* @param word
* The word to check
*/
public void checkWord(String word);
/**
* Checks the spelling with the spell-check iterator.
*
* @param iterator
* The iterator to use for spell-checking
*/
public void execute(ISpellCheckIterator iterator);
/**
* Returns the ranked proposals for a word.
*
* @param word
* The word to retrieve the proposals for
* @param sentence
* <code>true</code> iff the proposals should start a
* sentence, <code>false</code> otherwise
* @return Set of ranked proposals for the word
*/
public Set getProposals(String word, boolean sentence);
/**
* Ignores the specified word until calling <code>checkWord(String)</code>.
*
* @param word
* The word to ignore
*/
public void ignoreWord(String word);
/**
* Is the specified word correctly spelled?
*
* @param word
* The word to check its spelling
* @return <code>true</code> iff the word is correctly spelled, <code>false</code>
* otherwise
*/
public boolean isCorrect(String word);
/**
* Remove a dictionary from the list of active dictionaries.
*
* @param dictionary
* The dictionary to remove
*/
public void removeDictionary(ISpellDictionary dictionary);
/**
* Removes a spell event listener from the active listeners.
*
* @param listener
* The listener to remove
*/
public void removeListener(ISpellEventListener listener);
}
|
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/expression_in/TestConditionalExpression.java
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/expression_out/TestConditionalExpression.java
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
org.eclipse.jdt.ui.tests.refactoring/test
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
org.eclipse.jdt.ui/core
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
org.eclipse.jdt.ui/core
| |
38,464
|
Bug 38464 inline method: compile error after
|
20030604 int i(Object s, int k){ return k == 3? s.hashCode():3; } void f(int p){ int u= i(null, p); } inline i you get int u= p == 3? null.hashCode():3; which does not compile
|
resolved fixed
|
1f88a99
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:21:21Z
| 2003-06-05T10:46:40Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/SourceProvider.java
| |
57,706
|
Bug 57706 [navigation] expecting an override indicator for overrides in anonymous classes
|
Currently no override indicator is shown when I override/implement a method in an anonymous class. Given that we show override indicators for normal overrides it is confusing to not see the override indicator in this case.
|
resolved fixed
|
4e390aa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T15:27:14Z
| 2004-04-07T09:26:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/OverrideIndicatorManager.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.ui.PartInitException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
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.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener;
/**
* Manages the override and overwrite indicators for
* the given Java element and annotation model.
*
* @since 3.0
*/
class OverrideIndicatorManager implements IJavaReconcilingListener {
/**
* Overwrite and override indicator annotation.
*
* @since 3.0
*/
class OverrideIndicator extends Annotation {
private boolean fIsOverwriteIndicator;
private String fAstNodeKey;
/**
* Creates a new override annotation.
*
* @param isOverwriteIndicator <code>true</code> if this annotation is
* an overwrite indicator, <code>false</code> otherwise
* @param text the text associated with this annotation
* @param key the method binding key
* @since 3.0
*/
OverrideIndicator(boolean isOverwriteIndicator, String text, String key) {
super(ANNOTATION_TYPE, false, text);
fIsOverwriteIndicator= isOverwriteIndicator;
fAstNodeKey= key;
}
/**
* Tells whether this is an overwrite or an override indicator.
*
* @return <code>true</code> if this is an overwrite indicator
*/
public boolean isOverwriteIndicator() {
return fIsOverwriteIndicator;
}
/**
* Opens and reveals the defining method.
*/
public void open() {
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(fJavaElement, true, null);
ASTNode node= null;
if (ast != null)
node= ast.findDeclaringNode(fAstNodeKey);
if (node instanceof MethodDeclaration) {
try {
IMethodBinding methodBinding= ((MethodDeclaration)node).resolveBinding();
IType type= getType(methodBinding);
if (type != null) {
ITypeHierarchy th= SuperTypeHierarchyCache.getTypeHierarchy(type);
IType[] superTypes= th.getAllSupertypes(type);
IMethodBinding definingMethodBinding= Bindings.findMethodDefininition(methodBinding);
IType definingType= null;
if (definingMethodBinding != null)
definingType= findType(superTypes, definingMethodBinding.getDeclaringClass().getQualifiedName());
if (definingType != null) {
IMethod definingMethod= Bindings.findMethod(definingMethodBinding, definingType);
if (definingMethod != null) {
OpenActionUtil.open(definingMethod, true);
return;
}
}
}
} catch (JavaModelException ex) {
JavaPlugin.log(ex.getStatus());
} catch (PartInitException ex) {
JavaPlugin.log(ex.getStatus());
}
}
String title= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.title"); //$NON-NLS-1$
String message= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.message"); //$NON-NLS-1$
MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
private IType getType(IMethodBinding methodBinding) throws JavaModelException {
if (methodBinding == null)
return null;
int type= fJavaElement.getElementType();
IType[] types= null;
if (type == IJavaElement.COMPILATION_UNIT)
types= ((ICompilationUnit)fJavaElement).getAllTypes();
else if (type == IJavaElement.CLASS_FILE)
types= new IType[] { ((IClassFile)fJavaElement).getType() };
return findType(types, methodBinding.getDeclaringClass().getQualifiedName());
}
private IType findType(IType[] types, String fullyQualifiedName) throws JavaModelException {
if (types == null)
return null;
for (int i= 0; i < types.length; i++) {
IType type= types[i];
if (JavaModelUtil.getFullyQualifiedName(type).equals(fullyQualifiedName))
return type;
}
return null;
}
}
static final String ANNOTATION_TYPE= "org.eclipse.jdt.ui.overrideIndicator"; //$NON-NLS-1$
private IAnnotationModel fAnnotationModel;
private Object fAnnotationModelLockObject;
private Annotation[] fOverrideAnnotations;
private IJavaElement fJavaElement;
public OverrideIndicatorManager(IAnnotationModel annotationModel, IJavaElement javaElement, CompilationUnit ast) {
Assert.isNotNull(annotationModel);
Assert.isNotNull(javaElement);
fJavaElement= javaElement;
fAnnotationModel=annotationModel;
fAnnotationModelLockObject= getLockObject(fAnnotationModel);
updateAnnotations(ast, new NullProgressMonitor());
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the override and implements annotations based
* on the given AST.
*
* @param ast the compilation unit AST
* @param progressMonitor the progress monitor
* @since 3.0
*/
protected void updateAnnotations(CompilationUnit ast, IProgressMonitor progressMonitor) {
if (ast == null || progressMonitor.isCanceled())
return;
final Map annotationMap= new HashMap(50);
ast.accept(new ASTVisitor(false) {
/*
* @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodDeclaration)
*/
public boolean visit(MethodDeclaration node) {
IMethodBinding binding= node.resolveBinding();
if (binding != null) {
IMethodBinding definingMethod= Bindings.findMethodDefininition(binding);
if (definingMethod != null) {
ITypeBinding definingType= definingMethod.getDeclaringClass();
String qualifiedMethodName= definingType.getQualifiedName() + "." + binding.getName(); //$NON-NLS-1$
boolean isOverwriteIndicator= definingType.isInterface();
String text;
if (isOverwriteIndicator)
text= JavaEditorMessages.getFormattedString("OverrideIndicatorManager.implements", qualifiedMethodName); //$NON-NLS-1$
else
text= JavaEditorMessages.getFormattedString("OverrideIndicatorManager.overrides", qualifiedMethodName); //$NON-NLS-1$
SimpleName name= node.getName();
Position position= new Position(name.getStartPosition(), name.getLength());
annotationMap.put(
new OverrideIndicator(isOverwriteIndicator, text, binding.getKey()), //$NON-NLS-1$
position);
}
}
return false;
}
});
if (progressMonitor.isCanceled())
return;
synchronized (fAnnotationModelLockObject) {
if (fAnnotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, annotationMap);
} else {
removeAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
fAnnotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOverrideAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
}
/**
* Removes all override indicators from this manager's annotation model.
*/
void removeAnnotations() {
if (fOverrideAnnotations == null)
return;
synchronized (fAnnotationModelLockObject) {
if (fAnnotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, null);
} else {
for (int i= 0, length= fOverrideAnnotations.length; i < length; i++)
fAnnotationModel.removeAnnotation(fOverrideAnnotations[i]);
}
fOverrideAnnotations= null;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
*/
public synchronized void aboutToBeReconciled() {
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor)
*/
public synchronized void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) {
updateAnnotations(ast, progressMonitor);
}
}
|
46,942
|
Bug 46942 Change method signature: Edit dialog: Flaws in input validation [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, press edit. 1. Change the parameter name to an existing parameter name. Dialog does not complain. You will get the conflict message after pressing 'ok' 2. Clear the return type field. The error message is '' is not a valid return type. Should be like: 'The return type can not be empty.'
|
resolved fixed
|
1f82fa5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:12:26Z
| 2003-11-19T11:06:40Z
|
org.eclipse.jdt.ui/core
| |
46,942
|
Bug 46942 Change method signature: Edit dialog: Flaws in input validation [refactoring]
|
20031119 In the 'Refactoring > Change Method Signature' dialog, press edit. 1. Change the parameter name to an existing parameter name. Dialog does not complain. You will get the conflict message after pressing 'ok' 2. Clear the return type field. The error message is '' is not a valid return type. Should be like: 'The return type can not be empty.'
|
resolved fixed
|
1f82fa5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:12:26Z
| 2003-11-19T11:06:40Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/PullUp/testFail29/in/A.java
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
org.eclipse.jdt.ui.tests.refactoring/test
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
cases/org/eclipse/jdt/ui/tests/refactoring/PullUpTests.java
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
org.eclipse.jdt.ui/core
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MemberCheckUtil.java
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
org.eclipse.jdt.ui/core
| |
44,283
|
Bug 44283 pull up doesn't detect duplicate (overriden) methods [refactoring]
|
---------------------------- public class A { public void stop() { } } class B extends A { public void stop() //<-- pull up this method { System.out.println("pulled up!"); } } -------------------------------------- if you pull up B.stop() you get two stop methods in A
|
resolved fixed
|
58f4499
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-14T19:37:21Z
| 2003-10-07T09:46:40Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoring.java
| |
61,841
|
Bug 61841 SWTError: Cannot set data in clipboard
|
I200405111600 I've seen this before so it's not new in this build. I selected 3 or 4 lines and pressed Control-X (cut) and got a dialog that said "A SWT error has occurred. You are recommended to exit the workbench". The same thing happens if I press Control-C (copy). The text does get into the clipboard but is sometimes not cut from the original source file (Java code). (Note: I saw bugzilla entries with similar but not quite the same traceback so this may or may not be a dup.) Windows XP SP1, JDK1.4.2_04. Error May 11, 2004 21:56:41.728 Cannot set data in clipboard org.eclipse.swt.SWTError: Cannot set data in clipboard at org.eclipse.swt.dnd.DND.error(DND.java:225) at org.eclipse.swt.dnd.DND.error(DND.java:181) at org.eclipse.swt.dnd.Clipboard.setContents(Clipboard.java:289) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doCutCopyWithIm portsOperation(ClipboardOperationAction.java:301) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOpera tion(ClipboardOperationAction.java:245) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run (ClipboardOperationAction.java:223) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run (ClipboardOperationAction.java:221) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand (WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press (WorkbenchKeyboard.java:886) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent (WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings (WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2 (WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent (WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:712) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:795) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:820) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:805) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1724) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1720) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3048) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2951) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3291) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1466) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2388) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706)
|
resolved fixed
|
d0d3fbb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-15T21:55:04Z
| 2004-05-12T02:46:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/ClipboardOperationAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.ByteArrayTransfer;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.RTFTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.dnd.TransferData;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.IRewriteTarget;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportReferencesCollector;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
/**
* Action for cut/copy and paste with support for adding imports on paste.
*/
public final class ClipboardOperationAction extends TextEditorAction {
public static class ClipboardData {
private String fOriginHandle;
private String[] fImports;
public ClipboardData(IJavaElement origin, String[] imports) {
fImports= imports;
fOriginHandle= origin.getHandleIdentifier();
}
public ClipboardData(byte[] bytes) throws IOException {
DataInputStream dataIn = new DataInputStream(new ByteArrayInputStream(bytes));
fOriginHandle= dataIn.readUTF();
int count= dataIn.readInt();
fImports= new String[count];
for (int i = 0; i < count; i++) {
fImports[i]= dataIn.readUTF();
}
dataIn.close();
}
public String[] getImports() {
return fImports;
}
public boolean isFromSame(IJavaElement elem) {
return fOriginHandle.equals(elem.getHandleIdentifier());
}
public byte[] serialize() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeUTF(fOriginHandle);
dataOut.writeInt(fImports.length);
for (int i = 0; i < fImports.length; i++) {
dataOut.writeUTF(fImports[i]);
}
dataOut.close();
out.close();
return out.toByteArray();
}
}
private static class ClipboardTransfer extends ByteArrayTransfer {
private static final String TYPE_NAME = "source-with-imports-transfer-format" + System.currentTimeMillis(); //$NON-NLS-1$
private static final int TYPEID = registerType(TYPE_NAME);
/* (non-Javadoc)
* @see org.eclipse.swt.dnd.Transfer#getTypeIds()
*/
protected int[] getTypeIds() {
return new int[] { TYPEID };
}
/* (non-Javadoc)
* @see org.eclipse.swt.dnd.Transfer#getTypeNames()
*/
protected String[] getTypeNames() {
return new String[] { TYPE_NAME };
}
/* (non-Javadoc)
* @see org.eclipse.swt.dnd.Transfer#javaToNative(java.lang.Object, org.eclipse.swt.dnd.TransferData)
*/
protected void javaToNative(Object data, TransferData transferData) {
if (data instanceof ClipboardData) {
try {
super.javaToNative(((ClipboardData) data).serialize(), transferData);
} catch (IOException e) {
//it's best to send nothing if there were problems
}
}
}
/* (non-Javadoc)
* Method declared on Transfer.
*/
protected Object nativeToJava(TransferData transferData) {
byte[] bytes = (byte[]) super.nativeToJava(transferData);
if (bytes != null) {
try {
return new ClipboardData(bytes);
} catch (IOException e) {
}
}
return null;
}
}
private static final ClipboardTransfer fgTransferInstance = new ClipboardTransfer();
/** The text operation code */
private int fOperationCode= -1;
/** The text operation target */
private ITextOperationTarget fOperationTarget;
/**
* Creates the action.
*/
public ClipboardOperationAction(ResourceBundle bundle, String prefix, ITextEditor editor, int operationCode) {
super(bundle, prefix, editor);
fOperationCode= operationCode;
if (operationCode == ITextOperationTarget.CUT) {
setHelpContextId(IAbstractTextEditorHelpContextIds.CUT_ACTION);
setActionDefinitionId(ITextEditorActionDefinitionIds.CUT);
} else if (operationCode == ITextOperationTarget.COPY) {
setHelpContextId(IAbstractTextEditorHelpContextIds.COPY_ACTION);
setActionDefinitionId(ITextEditorActionDefinitionIds.COPY);
} else if (operationCode == ITextOperationTarget.PASTE) {
setHelpContextId(IAbstractTextEditorHelpContextIds.PASTE_ACTION);
setActionDefinitionId(ITextEditorActionDefinitionIds.PASTE);
} else {
Assert.isTrue(false, "Invalid operation code"); //$NON-NLS-1$
}
update();
}
private boolean isReadOnlyOperation() {
return fOperationCode == ITextOperationTarget.COPY;
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
if (fOperationCode == -1 || fOperationTarget == null)
return;
ITextEditor editor= getTextEditor();
if (editor == null)
return;
if (!isReadOnlyOperation() && !validateEditorInputState())
return;
BusyIndicator.showWhile(getDisplay(), new Runnable() {
public void run() {
internalDoOperation();
}
});
}
private Display getDisplay() {
ITextEditor editor= getTextEditor();
if (editor != null) {
IWorkbenchPartSite site= editor.getSite();
Shell shell= site.getShell();
if (shell != null && !shell.isDisposed())
return shell.getDisplay();
}
return null;
}
protected final void internalDoOperation() {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_IMPORTS_ON_PASTE)) {
if (fOperationCode == ITextOperationTarget.PASTE) {
doPasteWithImportsOperation();
} else {
doCutCopyWithImportsOperation();
}
} else {
fOperationTarget.doOperation(fOperationCode);
}
}
/* (non-Javadoc)
* @see org.eclipse.ui.texteditor.IUpdate#update()
*/
public void update() {
super.update();
if (!isReadOnlyOperation() && !canModifyEditor()) {
setEnabled(false);
return;
}
ITextEditor editor= getTextEditor();
if (fOperationTarget == null && editor!= null && fOperationCode != -1)
fOperationTarget= (ITextOperationTarget) editor.getAdapter(ITextOperationTarget.class);
boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
setEnabled(isEnabled);
}
/* (non-Javadoc)
* @see org.eclipse.ui.texteditor.TextEditorAction#setEditor(org.eclipse.ui.texteditor.ITextEditor)
*/
public void setEditor(ITextEditor editor) {
super.setEditor(editor);
fOperationTarget= null;
}
private void doCutCopyWithImportsOperation() {
ITextEditor editor= getTextEditor();
IJavaElement inputElement= (IJavaElement) editor.getEditorInput().getAdapter(IJavaElement.class);
ISelection selection= editor.getSelectionProvider().getSelection();
Object clipboardData= null;
if (inputElement != null && selection instanceof ITextSelection && !selection.isEmpty()) {
ITextSelection textSelection= (ITextSelection) selection;
if (isNonTrivialSelection(textSelection)) {
clipboardData= getClipboardData(inputElement, textSelection.getOffset(), textSelection.getLength());
}
}
fOperationTarget.doOperation(fOperationCode);
if (clipboardData != null) {
Clipboard clipboard= new Clipboard(getDisplay());
Object textData= clipboard.getContents(TextTransfer.getInstance());
Object rtfData= clipboard.getContents(RTFTransfer.getInstance());
// see bug 61876, I currently make assumptions about what the styled text widget sets
Transfer[] dataTypes= new Transfer[] { TextTransfer.getInstance(), RTFTransfer.getInstance(), fgTransferInstance};
Object[] data= new Object[] { textData, rtfData, clipboardData};
clipboard.setContents(data, dataTypes);
}
}
private boolean isNonTrivialSelection(ITextSelection selection) {
if (selection.getLength() < 30) {
String text= selection.getText();
for (int i= 0; i < text.length(); i++) {
if (!Character.isJavaIdentifierPart(text.charAt(i))) {
return true;
}
}
return false;
}
return true;
}
private ClipboardData getClipboardData(IJavaElement inputElement, int offset, int length) {
CompilationUnit astRoot= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
if (astRoot == null) {
return null;
}
// do process import if selection spans over import declaration or package
List list= astRoot.imports();
if (!list.isEmpty()) {
if (offset < ((ASTNode) list.get(list.size() - 1)).getStartPosition()) {
return null;
}
} else if (astRoot.getPackage() != null) {
if (offset < ((ASTNode) astRoot.getPackage()).getStartPosition()) {
return null;
}
}
ArrayList res= new ArrayList();
ImportReferencesCollector collector= new ImportReferencesCollector(new Region(offset, length), res);
astRoot.accept(collector);
HashSet namesToImport= new HashSet(res.size());
for (int i= 0; i < res.size(); i++) {
SimpleName curr= (SimpleName) res.get(i);
IBinding binding= curr.resolveBinding();
if (binding != null && binding.getKind() == IBinding.TYPE) {
ITypeBinding typeBinding= (ITypeBinding) binding;
if (typeBinding.isArray()) {
typeBinding= typeBinding.getElementType();
}
if (typeBinding.isMember() || typeBinding.isTopLevel()) {
String name= typeBinding.getQualifiedName();
if (name.length() > 0) {
namesToImport.add(name);
}
}
}
}
if (namesToImport.isEmpty()) {
return null;
}
return new ClipboardData(inputElement, (String[]) namesToImport.toArray(new String[namesToImport.size()]));
}
private void doPasteWithImportsOperation() {
ITextEditor editor= getTextEditor();
IJavaElement inputElement= (IJavaElement) editor.getEditorInput().getAdapter(IJavaElement.class);
Clipboard clipboard= new Clipboard(getDisplay());
ClipboardData importsData= (ClipboardData) clipboard.getContents(fgTransferInstance);
if (importsData != null && inputElement instanceof ICompilationUnit && !importsData.isFromSame(inputElement)) {
// combine operation and adding of imports
IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
if (target != null) {
target.beginCompoundChange();
}
try {
fOperationTarget.doOperation(fOperationCode);
addImports((ICompilationUnit) inputElement, importsData);
} catch (CoreException e) {
JavaPlugin.log(e);
} finally {
if (target != null) {
target.endCompoundChange();
}
}
} else {
fOperationTarget.doOperation(fOperationCode);
}
}
private void addImports(ICompilationUnit unit, ClipboardData data) throws CoreException {
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ImportsStructure importsStructure= new ImportsStructure(unit, settings.importOrder, settings.importThreshold, true);
importsStructure.setFindAmbiguousImports(false);
String[] imports= data.getImports();
for (int i= 0; i < imports.length; i++) {
importsStructure.addImport(imports[i]);
}
importsStructure.create(false, null);
}
}
|
53,629
|
Bug 53629 ChangeMethodSignature: content assist with focus doesn't work
|
M7++ - ChangeMethodSignature - Edit a parameter type - content assist - Tab -> cell editor disappears, proposals are NOT inserted. The problem is the TextCellEditor: When content assist proposal popup gets focus (Tab or mouseclick), the Text loses focus and the TextCellEditor is deactivated. Subclass of TextCellEditor could override focusLost() and only deactivate the editor if focus is not lost to proposal popup. Additional problem might be TableViewerImpl, which installs as focusListener on the CellEditor and directly calls applyEditorValue() to deactivate the editor.
|
resolved wontfix
|
c9204ea
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-16T12:29:49Z
| 2004-03-03T16:06:40Z
|
org.eclipse.jdt.ui/ui
| |
53,629
|
Bug 53629 ChangeMethodSignature: content assist with focus doesn't work
|
M7++ - ChangeMethodSignature - Edit a parameter type - content assist - Tab -> cell editor disappears, proposals are NOT inserted. The problem is the TextCellEditor: When content assist proposal popup gets focus (Tab or mouseclick), the Text loses focus and the TextCellEditor is deactivated. Subclass of TextCellEditor could override focusLost() and only deactivate the editor if focus is not lost to proposal popup. Additional problem might be TableViewerImpl, which installs as focusListener on the CellEditor and directly calls applyEditorValue() to deactivate the editor.
|
resolved wontfix
|
c9204ea
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-16T12:29:49Z
| 2004-03-03T16:06:40Z
|
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
54,658
|
Bug 54658 Bug in Code Formatter > Line Wrapping
|
Code Formatter > Line Wrapping: The preview is not shown correctly from the beginning. The "Set line width for preview window" number has to be reset to another OR even THE SAME value to correct the display.
|
verified fixed
|
112f7d9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-16T15:47:50Z
| 2004-03-12T16:46:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/LineWrappingTabPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences.formatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* The line wrapping tab page.
*/
public class LineWrappingTabPage extends ModifyDialogTabPage {
/**
* Represents a line wrapping category. All members are final.
*/
private final static class Category {
public final String key;
public final String name;
public final String previewText;
public final List children;
public int index;
public Category(String key, String previewText, String name) {
this.key= key;
this.name= name;
this.previewText= previewText != null ? createPreviewHeader(name) + previewText : null; //$NON-NLS-1$
children= new ArrayList();
}
public Category(String name) {
this(null, null, name);
}
public String toString() {
return name;
}
}
private final static String PREF_CATEGORY_INDEX= JavaUI.ID_PLUGIN + "formatter_page.line_wrapping_tab_page.last_category_index"; //$NON-NLS-1$
private final class CategoryListener implements ISelectionChangedListener, IDoubleClickListener {
private final List fCategoriesList;
private int fIndex= 0;
public CategoryListener(List categoriesTree) {
fCategoriesList= new ArrayList();
flatten(fCategoriesList, categoriesTree);
}
private void flatten(List categoriesList, List categoriesTree) {
for (final Iterator iter= categoriesTree.iterator(); iter.hasNext(); ) {
final Category category= (Category) iter.next();
category.index= fIndex++;
categoriesList.add(category);
flatten(categoriesList, category.children);
}
}
public void add(Category category) {
category.index= fIndex++;
fCategoriesList.add(category);
}
public void selectionChanged(SelectionChangedEvent event) {
final IStructuredSelection selection= (IStructuredSelection)event.getSelection();
final Category category= (Category)selection.getFirstElement();
fDialogSettings.put(PREF_CATEGORY_INDEX, category.index);
fCurrentKey= category.key;
if (fCurrentKey != null) {
fOptionsGroup.setText(FormatterMessages.getString("LineWrappingTabPage.group") + category.name.toLowerCase()); //$NON-NLS-1$
} else {
fOptionsGroup.setText(""); //$NON-NLS-1$
}
fPreview.setPreviewText(category.previewText);
final String value= (String)fWorkingValues.get(category.key);
final boolean enabled= value != null;
fOptionsGroup.setVisible(enabled);
if (enabled) {
int wrappingStyle;
int indentStyle;
boolean forceWrapping;
try {
forceWrapping= DefaultCodeFormatterConstants.getForceWrapping(value);
indentStyle= DefaultCodeFormatterConstants.getIndentStyle(value);
wrappingStyle= DefaultCodeFormatterConstants.getWrappingStyle(value);
} catch (IllegalArgumentException e) {
forceWrapping= false;
indentStyle= DefaultCodeFormatterConstants.INDENT_DEFAULT;
wrappingStyle= DefaultCodeFormatterConstants.WRAP_NO_SPLIT;
}
fForceSplit.setSelection(forceWrapping);
fIndentStyleCombo.setText(INDENT_NAMES[indentStyle]);
fWrappingStyleCombo.setText(WRAPPING_NAMES[wrappingStyle]);
updateControls(wrappingStyle);
}
}
public void restoreSelection() {
int index;
try {
index= fDialogSettings.getInt(PREF_CATEGORY_INDEX);
} catch (NumberFormatException ex) {
index= -1;
}
if (index < 0 || index > fCategoriesList.size() - 1) {
index= 1; // In order to select a category with preview initially
}
final Category category= (Category)fCategoriesList.get(index);
fCategoriesViewer.setSelection(new StructuredSelection(new Category[] {category}));
}
public void doubleClick(DoubleClickEvent event) {
final ISelection selection= event.getSelection();
if (selection instanceof IStructuredSelection) {
final Category node= (Category)((IStructuredSelection)selection).getFirstElement();
fCategoriesViewer.setExpandedState(node, !fCategoriesViewer.getExpandedState(node));
}
}
}
protected final static String[] INDENT_NAMES = {
FormatterMessages.getString("LineWrappingTabPage.indentation.default"), //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.indentation.on_column"), //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.indentation.by_one") //$NON-NLS-1$
};
protected final static String[] WRAPPING_NAMES = {
FormatterMessages.getString("LineWrappingTabPage.splitting.do_not_split"), //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.splitting.wrap_when_necessary"), // COMPACT_SPLIT //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.splitting.always_wrap_first_others_when_necessary"), // COMPACT_FIRST_BREAK_SPLIT //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.splitting.wrap_always"), // ONE_PER_LINE_SPLIT //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.splitting.wrap_always_indent_all_but_first"), // NEXT_SHIFTED_SPLIT //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.splitting.wrap_always_except_first_only_if_necessary") // NEXT_PER_LINE_SPLIT //$NON-NLS-1$
};
private final static Category fCompactIfCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_COMPACT_IF,
"class Example {" + //$NON-NLS-1$
"int foo(int argument) {" + //$NON-NLS-1$
" if (argument==0) return 0;" + //$NON-NLS-1$
" if (argument==1) return 42; else return 43;" + //$NON-NLS-1$
"}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.compact_if_else") //$NON-NLS-1$
);
private final static Category fTypeDeclarationSuperclassCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERCLASS_IN_TYPE_DECLARATION,
"class Example extends OtherClass {}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.extends_clause") //$NON-NLS-1$
);
private final static Category fTypeDeclarationSuperinterfacesCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SUPERINTERFACES_IN_TYPE_DECLARATION,
"class Example implements I1, I2, I3 {}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.implements_clause") //$NON-NLS-1$
);
private final static Category fConstructorDeclarationsParametersCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_CONSTRUCTOR_DECLARATION,
"class Example {Example(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) { this();}" + //$NON-NLS-1$
"Example() {}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.parameters") //$NON-NLS-1$
);
private final static Category fMethodDeclarationsParametersCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_PARAMETERS_IN_METHOD_DECLARATION,
"class Example {void foo(int arg1, int arg2, int arg3, int arg4, int arg5, int arg6) {}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.parameters") //$NON-NLS-1$
);
private final static Category fMessageSendArgumentsCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_METHOD_INVOCATION,
"class Example {void foo() {Other.bar( 100, 200, 300, 400, 500, 600, 700, 800, 900 );}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.arguments") //$NON-NLS-1$
);
private final static Category fMessageSendSelectorCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_SELECTOR_IN_METHOD_INVOCATION,
"class Example {int foo(Some a) {return a.getFirst();}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.qualified_invocations") //$NON-NLS-1$
);
private final static Category fMethodThrowsClauseCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_METHOD_DECLARATION,
"class Example {" + //$NON-NLS-1$
"int foo() throws FirstException, SecondException, ThirdException {" + //$NON-NLS-1$
" return Other.doSomething();}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.throws_clause") //$NON-NLS-1$
);
private final static Category fConstructorThrowsClauseCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_THROWS_CLAUSE_IN_CONSTRUCTOR_DECLARATION,
"class Example {" + //$NON-NLS-1$
"Example() throws FirstException, SecondException, ThirdException {" + //$NON-NLS-1$
" return Other.doSomething();}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.throws_clause") //$NON-NLS-1$
);
private final static Category fAllocationExpressionArgumentsCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_ALLOCATION_EXPRESSION,
"class Example {SomeClass foo() {return new SomeClass(100, 200, 300, 400, 500, 600, 700, 800, 900 );}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.object_allocation") //$NON-NLS-1$
);
private final static Category fQualifiedAllocationExpressionCategory= new Category (
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_QUALIFIED_ALLOCATION_EXPRESSION,
"class Example {SomeClass foo() {return SomeOtherClass.new SomeClass(100, 200, 300, 400, 500 );}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.qualified_object_allocation") //$NON-NLS-1$
);
private final static Category fArrayInitializerExpressionsCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_EXPRESSIONS_IN_ARRAY_INITIALIZER,
"class Example {int [] fArray= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.array_init") //$NON-NLS-1$
);
private final static Category fExplicitConstructorArgumentsCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_ARGUMENTS_IN_EXPLICIT_CONSTRUCTOR_CALL,
"class Example extends AnotherClass {Example() {super(100, 200, 300, 400, 500, 600, 700);}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.explicit_constructor_invocations") //$NON-NLS-1$
);
private final static Category fConditionalExpressionCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_CONDITIONAL_EXPRESSION,
"class Example extends AnotherClass {int Example(boolean Argument) {return argument ? 100000 : 200000;}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.conditionals") //$NON-NLS-1$
);
private final static Category fBinaryExpressionCategory= new Category(
DefaultCodeFormatterConstants.FORMATTER_ALIGNMENT_FOR_BINARY_EXPRESSION,
"class Example extends AnotherClass {" + //$NON-NLS-1$
"int foo() {" + //$NON-NLS-1$
" int sum= 100 + 200 + 300 + 400 + 500 + 600 + 700 + 800;" + //$NON-NLS-1$
" int product= 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10;" + //$NON-NLS-1$
" boolean val= true && false && true && false && true;" + //$NON-NLS-1$
" return product / sum;}}", //$NON-NLS-1$
FormatterMessages.getString("LineWrappingTabPage.binary_exprs") //$NON-NLS-1$
);
/**
* The default preview line width.
*/
private static int DEFAULT_PREVIEW_WINDOW_LINE_WIDTH= 40;
/**
* The key to save the user's preview window width in the dialog settings.
*/
private static final String PREF_PREVIEW_LINE_WIDTH= JavaUI.ID_PLUGIN + ".codeformatter.line_wrapping_tab_page.preview_line_width"; //$NON-NLS-1$
/**
* The dialog settings.
*/
protected final IDialogSettings fDialogSettings;
protected TreeViewer fCategoriesViewer;
protected Combo fWrappingStyleCombo;
protected Label fIndentStyleLabel;
protected Combo fIndentStyleCombo;
protected Button fForceSplit;
protected CompilationUnitPreview fPreview;
protected Group fOptionsGroup;
/**
* A collection containing the categories tree. This is used as model for the tree viewer.
* @see TreeViewer
*/
private final List fCategories;
/**
* The category listener which makes the selection persistent.
*/
protected final CategoryListener fCategoryListener;
/**
* The key representing the category for which the options are currently shown.
*/
protected String fCurrentKey;
/**
* A special options store wherein the preview line width is kept.
*/
protected final Map fPreviewPreferences;
/**
* The key for the preview line width.
*/
private final String LINE_SPLIT= DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT;
/**
* Create a new line wrapping tab page.
*/
public LineWrappingTabPage(ModifyDialog modifyDialog, Map workingValues) {
super(modifyDialog, workingValues);
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
final String previewLineWidth= fDialogSettings.get(PREF_PREVIEW_LINE_WIDTH);
fPreviewPreferences= new HashMap();
fPreviewPreferences.put(LINE_SPLIT, previewLineWidth != null ? previewLineWidth : Integer.toString(DEFAULT_PREVIEW_WINDOW_LINE_WIDTH));
fCategories= createCategories();
fCategoryListener= new CategoryListener(fCategories);
fCurrentKey= ((Category)fCategories.iterator().next()).key;
}
/**
* Create the categories tree.
*/
protected List createCategories() {
final Category classDeclarations= new Category(FormatterMessages.getString("LineWrappingTabPage.class_decls")); //$NON-NLS-1$
classDeclarations.children.add(fTypeDeclarationSuperclassCategory);
classDeclarations.children.add(fTypeDeclarationSuperinterfacesCategory);
final Category constructorDeclarations= new Category(null, null, FormatterMessages.getString("LineWrappingTabPage.constructor_decls")); //$NON-NLS-1$
constructorDeclarations.children.add(fConstructorDeclarationsParametersCategory);
constructorDeclarations.children.add(fConstructorThrowsClauseCategory);
final Category methodDeclarations= new Category(null, null, FormatterMessages.getString("LineWrappingTabPage.method_decls")); //$NON-NLS-1$
methodDeclarations.children.add(fMethodDeclarationsParametersCategory);
methodDeclarations.children.add(fMethodThrowsClauseCategory);
final Category functionCalls= new Category(FormatterMessages.getString("LineWrappingTabPage.function_calls")); //$NON-NLS-1$
functionCalls.children.add(fMessageSendArgumentsCategory);
functionCalls.children.add(fMessageSendSelectorCategory);
functionCalls.children.add(fExplicitConstructorArgumentsCategory);
functionCalls.children.add(fAllocationExpressionArgumentsCategory);
functionCalls.children.add(fQualifiedAllocationExpressionCategory);
final Category expressions= new Category(FormatterMessages.getString("LineWrappingTabPage.expressions")); //$NON-NLS-1$
expressions.children.add(fBinaryExpressionCategory);
expressions.children.add(fConditionalExpressionCategory);
expressions.children.add(fArrayInitializerExpressionsCategory);
final Category statements= new Category(FormatterMessages.getString("LineWrappingTabPage.statements")); //$NON-NLS-1$
statements.children.add(fCompactIfCategory);
final List root= new ArrayList();
root.add(classDeclarations);
root.add(constructorDeclarations);
root.add(methodDeclarations);
root.add(functionCalls);
root.add(expressions);
root.add(statements);
return root;
}
protected void doCreatePreferences(Composite composite, int numColumns) {
final Group lineWidthGroup= createGroup(numColumns, composite, FormatterMessages.getString("LineWrappingTabPage.width_indent")); //$NON-NLS-1$
createNumberPref(lineWidthGroup, numColumns, FormatterMessages.getString("LineWrappingTabPage.width_indent.option.max_line_width"), DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, 0, 9999); //$NON-NLS-1$
createNumberPref(lineWidthGroup, numColumns, FormatterMessages.getString("LineWrappingTabPage.width_indent.option.default_indent_wrapped"), DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, 0, 9999); //$NON-NLS-1$
createNumberPref(lineWidthGroup, numColumns, FormatterMessages.getString("LineWrappingTabPage.width_indent.option.default_indent_array"), DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION_FOR_ARRAY_INITIALIZER, 0, 9999); //$NON-NLS-1$
fCategoriesViewer= new TreeViewer(composite /*categoryGroup*/, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY | SWT.V_SCROLL );
fCategoriesViewer.setContentProvider(new ITreeContentProvider() {
public Object[] getElements(Object inputElement) {
return ((Collection)inputElement).toArray();
}
public Object[] getChildren(Object parentElement) {
return ((Category)parentElement).children.toArray();
}
public Object getParent(Object element) { return null; }
public boolean hasChildren(Object element) {
return !((Category)element).children.isEmpty();
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {}
public void dispose() {}
});
fCategoriesViewer.setLabelProvider(new LabelProvider());
fCategoriesViewer.setInput(fCategories);
fCategoriesViewer.setExpandedElements(fCategories.toArray());
final GridData gd= createGridData(numColumns, GridData.FILL_BOTH, 0);
fCategoriesViewer.getControl().setLayoutData(gd);
fOptionsGroup = createGroup(numColumns, composite, ""); //$NON-NLS-1$
// label "Select split style:"
createLabel(numColumns, fOptionsGroup, FormatterMessages.getString("LineWrappingTabPage.wrapping_policy.label.text")); //$NON-NLS-1$
// combo SplitStyleCombo
fWrappingStyleCombo= new Combo(fOptionsGroup, SWT.SINGLE | SWT.READ_ONLY);
fWrappingStyleCombo.setItems(WRAPPING_NAMES);
fWrappingStyleCombo.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
// label "Select indentation style:"
fIndentStyleLabel= createLabel(numColumns, fOptionsGroup, FormatterMessages.getString("LineWrappingTabPage.indentation_policy.label.text")); //$NON-NLS-1$
// combo SplitStyleCombo
fIndentStyleCombo= new Combo(fOptionsGroup, SWT.SINGLE | SWT.READ_ONLY);
fIndentStyleCombo.setItems(INDENT_NAMES);
fIndentStyleCombo.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
// button "Force split"
fForceSplit= new Button(fOptionsGroup, SWT.CHECK);
fForceSplit.setLayoutData(createGridData(numColumns, GridData.HORIZONTAL_ALIGN_FILL, 0));
fForceSplit.setText(FormatterMessages.getString("LineWrappingTabPage.force_split.checkbox.text")); //$NON-NLS-1$
}
protected Composite doCreatePreviewPane(Composite composite, int numColumns) {
super.doCreatePreviewPane(composite, numColumns);
final NumberPreference previewLineWidth= new NumberPreference(composite, numColumns / 2, fPreviewPreferences, LINE_SPLIT,
0, 9999, FormatterMessages.getString("LineWrappingTabPage.line_width_for_preview.label.text")); //$NON-NLS-1$
fDefaultFocusManager.add(previewLineWidth);
previewLineWidth.addObserver(fUpdater);
previewLineWidth.addObserver(new Observer() {
public void update(Observable o, Object arg) {
fDialogSettings.put(PREF_PREVIEW_LINE_WIDTH, (String)fPreviewPreferences.get(LINE_SPLIT));
}
});
return composite;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.preferences.formatter.ModifyDialogTabPage#doCreateJavaPreview(org.eclipse.swt.widgets.Composite)
*/
protected JavaPreview doCreateJavaPreview(Composite parent) {
fPreview= new CompilationUnitPreview(fWorkingValues, parent);
return fPreview;
}
protected void initializePage() {
fCategoriesViewer.addSelectionChangedListener(fCategoryListener);
fCategoriesViewer.addDoubleClickListener(fCategoryListener);
fForceSplit.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
forceSplitChanged(fForceSplit.getSelection());
}
});
fIndentStyleCombo.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
indentStyleChanged(((Combo)e.widget).getSelectionIndex());
}
});
fWrappingStyleCombo.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
wrappingStyleChanged(((Combo)e.widget).getSelectionIndex());
}
});
fCategoryListener.restoreSelection();
fDefaultFocusManager.add(fCategoriesViewer.getControl());
fDefaultFocusManager.add(fWrappingStyleCombo);
fDefaultFocusManager.add(fIndentStyleCombo);
fDefaultFocusManager.add(fForceSplit);
}
protected void doUpdatePreview() {
final Object normalSetting= fWorkingValues.get(LINE_SPLIT);
fWorkingValues.put(LINE_SPLIT, fPreviewPreferences.get(LINE_SPLIT));
fPreview.update();
fWorkingValues.put(LINE_SPLIT, normalSetting);
}
protected void forceSplitChanged(boolean forceSplit) {
String value;
try {
value= (String)fWorkingValues.get(fCurrentKey);
value= DefaultCodeFormatterConstants.setForceWrapping(value, forceSplit);
fWorkingValues.put(fCurrentKey, value);
} catch (Exception e) {
fWorkingValues.put(fCurrentKey, DefaultCodeFormatterConstants.createAlignmentValue(forceSplit, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, DefaultCodeFormatterConstants.INDENT_DEFAULT));
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK,
FormatterMessages.getFormattedString("LineWrappingTabPage.error.invalid_value", fCurrentKey), e)); //$NON-NLS-1$
} finally {
doUpdatePreview();
}
}
protected void wrappingStyleChanged(int wrappingStyle) {
String value;
try {
value= (String)fWorkingValues.get(fCurrentKey);
value= DefaultCodeFormatterConstants.setWrappingStyle(value, wrappingStyle);
fWorkingValues.put(fCurrentKey, value);
} catch (Exception e) {
fWorkingValues.put(fCurrentKey, DefaultCodeFormatterConstants.createAlignmentValue(false, wrappingStyle, DefaultCodeFormatterConstants.INDENT_DEFAULT));
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK,
FormatterMessages.getFormattedString("LineWrappingTabPage.error.invalid_value", fCurrentKey), e)); //$NON-NLS-1$
} finally {
updateControls(wrappingStyle);
doUpdatePreview();
}
}
protected void indentStyleChanged(int indentStyle) {
String value;
try {
value= (String)fWorkingValues.get(fCurrentKey);
value= DefaultCodeFormatterConstants.setIndentStyle(value, indentStyle);
fWorkingValues.put(fCurrentKey, value);
} catch (Exception e) {
fWorkingValues.put(fCurrentKey, DefaultCodeFormatterConstants.createAlignmentValue(false, DefaultCodeFormatterConstants.WRAP_NO_SPLIT, indentStyle));
JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.OK,
FormatterMessages.getFormattedString("LineWrappingTabPage.error.invalid_value", fCurrentKey), e)); //$NON-NLS-1$
} finally {
doUpdatePreview();
}
}
protected void updateControls(int wrappingStyle) {
boolean doSplit= wrappingStyle != DefaultCodeFormatterConstants.WRAP_NO_SPLIT;
fIndentStyleLabel.setEnabled(doSplit);
fIndentStyleCombo.setEnabled(doSplit);
fForceSplit.setEnabled(doSplit);
}
}
|
55,661
|
Bug 55661 Cannot resize window "Generate Javadoc" [javadoc]
|
It would be very helpful if (more) windows could be resized, like the Javadoc-dialog. It's so small that you can barely read the package-names on the second view, and you have to read the tooltips to be able to determine which package to select. As package-names tend to get rather long, I think many users will run into this issue...
|
resolved fixed
|
edcbcc6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-16T15:56:35Z
| 2004-03-23T13:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/GenerateJavadocAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.jdt.internal.ui.javadocexport.JavadocWizard;
public class GenerateJavadocAction implements IWorkbenchWindowActionDelegate {
private ISelection fSelection;
private IWorkbenchWindow fWindow;
public void dispose() {
}
public void init(IWorkbenchWindow window) {
fWindow= window;
}
public void run(IAction action) {
JavadocWizard wizard= new JavadocWizard();
IStructuredSelection selection= null;
if (fSelection instanceof IStructuredSelection) {
selection= (IStructuredSelection)fSelection;
} else {
selection= new StructuredSelection();
}
wizard.init(fWindow.getWorkbench() , selection);
WizardDialog dialog= new WizardDialog(fWindow.getShell(), wizard);
dialog.open();
}
public void selectionChanged(IAction action, ISelection selection) {
fSelection= selection;
}
}
|
55,661
|
Bug 55661 Cannot resize window "Generate Javadoc" [javadoc]
|
It would be very helpful if (more) windows could be resized, like the Javadoc-dialog. It's so small that you can barely read the package-names on the second view, and you have to read the tooltips to be able to determine which package to select. As package-names tend to get rather long, I think many users will run into this issue...
|
resolved fixed
|
edcbcc6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-16T15:56:35Z
| 2004-03-23T13:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/CreateJavadocActionDelegate.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.util.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.internal.ui.JavaPlugin;
public class CreateJavadocActionDelegate implements IObjectActionDelegate {
private ISelection fCurrentSelection;
/*
* @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
}
/*
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
if (fCurrentSelection instanceof IStructuredSelection) {
IStructuredSelection structuredSelection= (IStructuredSelection) fCurrentSelection;
Iterator iter= structuredSelection.iterator();
if (iter.hasNext()) {
Object res= iter.next();
if (res instanceof IFile) {
IFile file= (IFile) res;
JavadocWizard wizard= new JavadocWizard(file);
wizard.init(JavaPlugin.getActiveWorkbenchWindow().getWorkbench(),structuredSelection);
WizardDialog dialog= new WizardDialog(JavaPlugin.getActiveWorkbenchShell(), wizard);
dialog.create();
// dialog.getShell().setText(WorkbenchMessages.getString("CreateFileAction.title")); //$NON-NLS-1$
dialog.open();
}
}
}
}
/*
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
fCurrentSelection= selection;
}
}
|
55,661
|
Bug 55661 Cannot resize window "Generate Javadoc" [javadoc]
|
It would be very helpful if (more) windows could be resized, like the Javadoc-dialog. It's so small that you can barely read the package-names on the second view, and you have to read the tooltips to be able to determine which package to select. As package-names tend to get rather long, I think many users will run into this issue...
|
resolved fixed
|
edcbcc6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-16T15:56:35Z
| 2004-03-23T13:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javadocexport/JavadocWizard.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids <sdavids@gmx.de> bug 38692
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javadocexport;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceDescription;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IExportWizard;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbench;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationType;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.OpenBrowserUtil;
import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog;
import org.eclipse.jdt.internal.ui.jarpackager.ConfirmSaveModifiedResourcesDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.ProgressService;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jdt.ui.JavaUI;
public class JavadocWizard extends Wizard implements IExportWizard {
private JavadocTreeWizardPage fJTWPage;
private JavadocSpecificsWizardPage fJSWPage;
private JavadocStandardWizardPage fJSpWPage;
private IPath fDestination;
private boolean fWriteCustom;
private boolean fOpenInBrowser;
private final String TREE_PAGE_DESC= "JavadocTreePage"; //$NON-NLS-1$
private final String SPECIFICS_PAGE_DESC= "JavadocSpecificsPage"; //$NON-NLS-1$
private final String STANDARD_PAGE_DESC= "JavadocStandardPage"; //$NON-NLS-1$
private final int YES= 0;
private final int YES_TO_ALL= 1;
private final int NO= 2;
private final int NO_TO_ALL= 3;
private final String JAVADOC_ANT_INFORMATION_DIALOG= "javadocAntInformationDialog";//$NON-NLS-1$
private JavadocOptionsManager fStore;
private IWorkspaceRoot fRoot;
private IFile fXmlJavadocFile;
private static final String ID_JAVADOC_PROCESS_TYPE= "org.eclipse.jdt.ui.javadocProcess"; //$NON-NLS-1$
//private ILaunchConfiguration fConfig;
public JavadocWizard() {
this(null);
}
public JavadocWizard(IFile xmlJavadocFile) {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_EXPORT_JAVADOC);
setWindowTitle(JavadocExportMessages.getString("JavadocWizard.javadocwizard.title")); //$NON-NLS-1$
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
fRoot= ResourcesPlugin.getWorkspace().getRoot();
fXmlJavadocFile= xmlJavadocFile;
fWriteCustom= false;
}
/*
* @see IWizard#performFinish()
*/
public boolean performFinish() {
IJavaProject[] checkedProjects= fJTWPage.getCheckedProjects();
updateStore(checkedProjects);
//If the wizard was not launched from an ant file store the setttings
if (fXmlJavadocFile == null) {
fStore.updateDialogSettings(getDialogSettings(), checkedProjects);
}
// Wizard will not run with unsaved files.
if (!checkPreconditions(fStore.getSourceElements())) {
return false;
}
fDestination= new Path(fStore.getDestination());
fDestination.toFile().mkdirs();
fOpenInBrowser= fStore.doOpenInBrowser();
//Ask if you wish to set the javadoc location for the projects (all) to
//the location of the newly generated javadoc
if (fStore.isFromStandard()) {
try {
URL newURL= fDestination.toFile().toURL();
List projs= new ArrayList();
//get javadoc locations for all projects
for (int i= 0; i < checkedProjects.length; i++) {
IJavaProject curr= checkedProjects[i];
URL currURL= JavaUI.getProjectJavadocLocation(curr);
if (!newURL.equals(currURL)) { // currURL can be null
//if not all projects have the same javadoc location ask if you want to change
//them to have the same javadoc location
projs.add(curr);
}
}
if (!projs.isEmpty()) {
setAllJavadocLocations((IJavaProject[]) projs.toArray(new IJavaProject[projs.size()]), newURL);
}
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
}
if (fJSWPage.generateAnt()) {
//@Improve: make a better message
OptionalMessageDialog.open(JAVADOC_ANT_INFORMATION_DIALOG, getShell(), JavadocExportMessages.getString("JavadocWizard.antInformationDialog.title"), null, JavadocExportMessages.getString("JavadocWizard.antInformationDialog.message"), MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); //$NON-NLS-1$ //$NON-NLS-2$
try {
fStore.createXML(checkedProjects);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(),JavadocExportMessages.getString("JavadocWizard.error.writeANT.title"), JavadocExportMessages.getString("JavadocWizard.error.writeANT.message")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
if (!executeJavadocGeneration())
return false;
return true;
}
private void updateStore(IJavaProject[] checkedProjects) {
//writes the new settings to store
fJTWPage.updateStore(checkedProjects);
if (!fJTWPage.getCustom())
fJSpWPage.updateStore();
fJSWPage.updateStore();
}
/* (non-Javadoc)
* @see org.eclipse.jface.wizard.IWizard#performCancel()
*/
public boolean performCancel() {
IJavaProject[] checkedProjects= fJTWPage.getCheckedProjects();
updateStore(checkedProjects);
//If the wizard was not launched from an ant file store the setttings
if (fXmlJavadocFile == null) {
fStore.updateDialogSettings(getDialogSettings(), checkedProjects);
}
return super.performCancel();
}
private void setAllJavadocLocations(IJavaProject[] projects, URL newURL) {
Shell shell= getShell();
Image image= shell == null ? null : shell.getDisplay().getSystemImage(SWT.ICON_QUESTION);
String[] buttonlabels= new String[] { IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.NO_TO_ALL_LABEL };
for (int j= 0; j < projects.length; j++) {
IJavaProject iJavaProject= projects[j];
String message= JavadocExportMessages.getFormattedString("JavadocWizard.updatejavadoclocation.message", new String[] { iJavaProject.getElementName(), fDestination.toOSString()}); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, JavadocExportMessages.getString("JavadocWizard.updatejavadocdialog.label"), image, message, 4, buttonlabels, 1);//$NON-NLS-1$
switch (dialog.open()) {
case YES :
JavaUI.setProjectJavadocLocation(iJavaProject, newURL);
break;
case YES_TO_ALL :
for (int i= j; i < projects.length; i++) {
iJavaProject= projects[i];
JavaUI.setProjectJavadocLocation(iJavaProject, newURL);
j++;
}
break;
case NO_TO_ALL :
j= projects.length;
break;
case NO :
default :
break;
}
}
}
private boolean executeJavadocGeneration() {
Process process= null;
try {
ArrayList vmArgs= new ArrayList();
ArrayList progArgs= new ArrayList();
fStore.getArgumentArray(vmArgs, progArgs);
File file= File.createTempFile("javadoc-arguments", ".tmp"); //$NON-NLS-1$//$NON-NLS-2$
vmArgs.add('@' + file.getAbsolutePath());
FileWriter writer= new FileWriter(file);
try {
for (int i= 0; i < progArgs.size(); i++) {
String curr= (String) progArgs.get(i);
curr= checkForSpaces(curr);
writer.write(curr);
writer.write(' ');
}
} finally {
writer.close();
}
String[] args= (String[]) vmArgs.toArray(new String[vmArgs.size()]);
process= Runtime.getRuntime().exec(args);
if (process != null) {
// construct a formatted command line for the process properties
StringBuffer buf= new StringBuffer();
for (int i= 0; i < args.length; i++) {
buf.append(args[i]);
buf.append(' ');
}
IDebugEventSetListener listener= new JavadocDebugEventListener(getShell().getDisplay(), file);
DebugPlugin.getDefault().addDebugEventListener(listener);
ILaunchConfigurationWorkingCopy wc= null;
try {
ILaunchConfigurationType lcType= DebugPlugin.getDefault().getLaunchManager().getLaunchConfigurationType(IJavaLaunchConfigurationConstants.ID_JAVA_APPLICATION);
String name= JavadocExportMessages.getString("JavadocWizard.launchconfig.name"); //$NON-NLS-1$
wc= lcType.newInstance(null, name);
wc.setAttribute(IDebugUIConstants.ATTR_PRIVATE, true);
ILaunch newLaunch= new Launch(wc, ILaunchManager.RUN_MODE, null);
IProcess iprocess= DebugPlugin.newProcess(newLaunch, process, JavadocExportMessages.getString("JavadocWizard.javadocprocess.label")); //$NON-NLS-1$
iprocess.setAttribute(IProcess.ATTR_CMDLINE, buf.toString());
iprocess.setAttribute(IProcess.ATTR_PROCESS_TYPE, ID_JAVADOC_PROCESS_TYPE);
DebugPlugin.getDefault().getLaunchManager().addLaunch(newLaunch);
} catch (CoreException e) {
String title= JavadocExportMessages.getString("JavadocWizard.error.title"); //$NON-NLS-1$
String message= JavadocExportMessages.getString("JavadocWizard.launch.error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
return true;
}
} catch (IOException e) {
String title= JavadocExportMessages.getString("JavadocWizard.error.title"); //$NON-NLS-1$
String message= JavadocExportMessages.getString("JavadocWizard.exec.error.message"); //$NON-NLS-1$
IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.ERROR, e.getMessage(), e);
ExceptionHandler.handle(new CoreException(status), getShell(), title, message);
return false;
}
return false;
}
private String checkForSpaces(String curr) {
if (curr.indexOf(' ') == -1) {
return curr;
}
StringBuffer buf= new StringBuffer();
buf.append('\'');
for (int i= 0; i < curr.length(); i++) {
char ch= curr.charAt(i);
if (ch == '\\' || ch == '\'') {
buf.append('\\');
}
buf.append(ch);
}
buf.append('\'');
return buf.toString();
}
/**
* Creates a list of all CompilationUnits and extracts from that list a list of dirty
* files. The user is then asked to confirm if those resources should be saved or
* not.
*
* @param elements
* @return <code>true</code> if all preconditions are satisfied otherwise false
*/
private boolean checkPreconditions(IJavaElement[] elements) {
ArrayList resources= new ArrayList();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof ICompilationUnit) {
resources.add(elements[i].getResource());
}
}
//message could be null
IFile[] unSavedFiles= getUnsavedFiles(resources);
return saveModifiedResourcesIfUserConfirms(unSavedFiles);
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @param resources
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles(List resources) {
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput) dirtyEditors[i].getEditorInput()).getFile();
if (resources.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[]) unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed. Must be run in the display thread.
*
* @param dirtyFiles
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles)) {
try {
if (saveModifiedResources(dirtyFiles))
return true;
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogCE.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.title"), JavadocExportMessages.getString("JavadocWizard.saveresourcedialogITE.message")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return false;
}
/**
* Asks the user to confirm to save the modified resources.
*
* @param dirtyFiles
* @return true if user pressed OK.
*/
private boolean confirmSaveModifiedResources(IFile[] dirtyFiles) {
if (dirtyFiles == null || dirtyFiles.length == 0)
return true;
// Get display for further UI operations
Display display= getShell().getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(getShell(), dirtyFiles);
final int[] intResult= new int[1];
Runnable runnable= new Runnable() {
public void run() {
intResult[0]= dlg.open();
}
};
display.syncExec(runnable);
return intResult[0] == IDialogConstants.OK_ID;
}
/**
* Save all of the editors in the workbench. Must be run in the display thread.
*
* @param dirtyFiles
* @return true if successful.
* @throws CoreException
* @throws InvocationTargetException
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) throws CoreException, InvocationTargetException {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IWorkspaceDescription description= workspace.getDescription();
boolean autoBuild= description.isAutoBuilding();
description.setAutoBuilding(false);
try {
workspace.setDescription(description);
// This save operation can not be cancelled.
try {
ProgressService.runSuspended(false, false, createSaveModifiedResourcesRunnable(dirtyFiles), workspace.getRoot());
} finally {
description.setAutoBuilding(autoBuild);
workspace.setDescription(description);
}
} catch (InterruptedException ex) {
return false;
}
return true;
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= JavaPlugin.getDirtyEditors();
String name= JavadocExportMessages.getString("JavadocWizard.savetask.name"); //$NON-NLS-1$
pm.beginTask(name, editorsToSave.length);
try {
List dirtyFilesList= Arrays.asList(dirtyFiles);
for (int i= 0; i < editorsToSave.length; i++) {
if (editorsToSave[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput) editorsToSave[i].getEditorInput()).getFile();
if (dirtyFilesList.contains((dirtyFile)))
editorsToSave[i].doSave(new SubProgressMonitor(pm, 1));
}
pm.worked(1);
}
} finally {
pm.done();
}
}
};
}
/*
* @see IWizard#addPages()
*/
public void addPages() {
fJTWPage= new JavadocTreeWizardPage(TREE_PAGE_DESC, fStore);
fJSWPage= new JavadocSpecificsWizardPage(SPECIFICS_PAGE_DESC, fJTWPage, fStore);
fJSpWPage= new JavadocStandardWizardPage(STANDARD_PAGE_DESC, fJTWPage, fStore);
super.addPage(fJTWPage);
super.addPage(fJSpWPage);
super.addPage(fJSWPage);
fJTWPage.init();
fJSpWPage.init();
fJSWPage.init();
}
public void init(IWorkbench workbench, IStructuredSelection structuredSelection) {
List selected= structuredSelection.toList();
if (selected.isEmpty()) {
IJavaElement element= EditorUtility.getActiveEditorJavaInput();
selected= new ArrayList();
selected.add(element);
}
fStore= new JavadocOptionsManager(fXmlJavadocFile, getDialogSettings(), selected);
}
private void refresh(IPath path) {
if (fRoot.findContainersForLocation(path).length > 0) {
try {
fRoot.refreshLocal(IResource.DEPTH_INFINITE, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
private void spawnInBrowser(Display display) {
if (fOpenInBrowser) {
try {
IPath indexFile= fDestination.append("index.html"); //$NON-NLS-1$
URL url= indexFile.toFile().toURL();
OpenBrowserUtil.open(url, display, getWindowTitle());
} catch (MalformedURLException e) {
JavaPlugin.log(e);
}
}
}
private class JavadocDebugEventListener implements IDebugEventSetListener {
private Display fDisplay;
private File fFile;
public JavadocDebugEventListener(Display display, File file) {
fDisplay= display;
fFile= file;
}
public void handleDebugEvents(DebugEvent[] events) {
for (int i= 0; i < events.length; i++) {
if (events[i].getKind() == DebugEvent.TERMINATE) {
try {
if (!fWriteCustom) {
fFile.delete();
refresh(fDestination); //If destination of javadoc is in workspace then refresh workspace
spawnInBrowser(fDisplay);
}
} finally {
DebugPlugin.getDefault().removeDebugEventListener(this);
}
return;
}
}
}
}
public IWizardPage getNextPage(IWizardPage page) {
if (page instanceof JavadocTreeWizardPage) {
if (!fJTWPage.getCustom()) {
return fJSpWPage;
}
return fJSWPage;
} else if (page instanceof JavadocSpecificsWizardPage) {
return null;
} else if (page instanceof JavadocStandardWizardPage)
return fJSWPage;
else
return null;
}
public IWizardPage getPreviousPage(IWizardPage page) {
if (page instanceof JavadocSpecificsWizardPage) {
if (!fJTWPage.getCustom()) {
return fJSpWPage;
}
return fJSWPage;
} else if (page instanceof JavadocTreeWizardPage) {
return null;
} else if (page instanceof JavadocStandardWizardPage)
return fJTWPage;
else
return null;
}
}
|
62,386
|
Bug 62386 can't turn off Filter imports
|
Version: 3.0.0 Build id: 200405140800 Linux Gtk+ Turned on Filter Imports in the search view, now I can't turn it off. Option to turn off Filter Imports is unavailable.
|
resolved fixed
|
39e0a7b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T08:24:29Z
| 2004-05-14T21:26:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.search.IMatchPresentation;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.search.ui.ISearchResult;
import org.eclipse.search.ui.ISearchResultViewPart;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.ui.text.AbstractTextSearchResult;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.search.ui.text.Match;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.ITextEditor;
public class JavaSearchResultPage extends AbstractTextSearchViewPage implements IAdaptable {
private static final String KEY_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$
private static final String KEY_SORTING= "org.eclipse.jdt.search.resultpage.sorting"; //$NON-NLS-1$
private static final String KEY_FILTERS= "org.eclipse.jdt.search.resultpage.filters"; //$NON-NLS-1$
private static final String GROUP_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$
private NewSearchViewActionGroup fActionGroup;
private JavaSearchContentProvider fContentProvider;
private int fCurrentSortOrder;
private SortAction fSortByNameAction;
private SortAction fSortByParentName;
private SortAction fSortByPathAction;
private GroupAction fGroupTypeAction;
private GroupAction fGroupFileAction;
private GroupAction fGroupPackageAction;
private GroupAction fGroupProjectAction;
private int fCurrentGrouping;
private Set fMatchFilters= new HashSet();
private FilterAction[] fFilterActions;
private static final String[] SHOW_IN_TARGETS= new String[] { JavaUI.ID_PACKAGES , IPageLayout.ID_RES_NAV };
public static final IShowInTargetList SHOW_IN_TARGET_LIST= new IShowInTargetList() {
public String[] getShowInTargetIds() {
return SHOW_IN_TARGETS;
}
};
private JavaSearchEditorOpener fEditorOpener= new JavaSearchEditorOpener();
public JavaSearchResultPage() {
initSortActions();
initGroupingActions();
initFilterActions();
}
private void initFilterActions() {
MatchFilter[] allFilters= MatchFilter.allFilters();
fFilterActions= new FilterAction[allFilters.length];
for (int i= 0; i < fFilterActions.length; i++) {
fFilterActions[i]= new FilterAction(this, allFilters[i]);
}
}
private void initSortActions() {
fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, SortingLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$
fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, SortingLabelProvider.SHOW_PATH); //$NON-NLS-1$
fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, SortingLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$
}
private void initGroupingActions() {
fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), SearchMessages.getString("JavaSearchResultPage.groupby_project.tooltip"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$
fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), SearchMessages.getString("JavaSearchResultPage.groupby_package.tooltip"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$
fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), SearchMessages.getString("JavaSearchResultPage.groupby_file.tooltip"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$
fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), SearchMessages.getString("JavaSearchResultPage.groupby_type.tooltip"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "type_mode.gif"); //$NON-NLS-1$
}
public void setViewPart(ISearchResultViewPart part) {
super.setViewPart(part);
fActionGroup= new NewSearchViewActionGroup(part);
}
public void showMatch(Match match, int offset, int length, boolean activate) throws PartInitException {
IEditorPart editor;
try {
editor= fEditorOpener.open(match);
} catch (JavaModelException e) {
throw new PartInitException(e.getStatus());
}
if (editor != null && activate)
editor.getEditorSite().getPage().activate(editor);
Object element= match.getElement();
if (editor instanceof ITextEditor) {
ITextEditor textEditor= (ITextEditor) editor;
textEditor.selectAndReveal(offset, length);
} else if (editor != null){
if (element instanceof IFile) {
IFile file= (IFile) element;
showWithMarker(editor, file, offset, length);
}
} else {
JavaSearchResult result= (JavaSearchResult) getInput();
IMatchPresentation participant= result.getSearchParticpant(element);
if (participant != null)
participant.showMatch(match, offset, length, activate);
}
}
private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException {
try {
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
HashMap attributes= new HashMap(4);
attributes.put(IMarker.CHAR_START, new Integer(offset));
attributes.put(IMarker.CHAR_END, new Integer(offset + length));
marker.setAttributes(attributes);
IDE.gotoMarker(editor, marker);
marker.delete();
} catch (CoreException e) {
throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$
}
}
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
addSortActions(mgr);
fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroup.fillContextMenu(mgr);
}
private void addFilterActions(IMenuManager viewMenu) {
String filteringGroup= "Filtering"; //$NON-NLS-1$
viewMenu.insertBefore(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(filteringGroup));
for (int i= 0; i < fFilterActions.length; i++) {
viewMenu.appendToGroup(filteringGroup, fFilterActions[i]);
}
}
private void addSortActions(IMenuManager mgr) {
if (getLayout() != FLAG_LAYOUT_FLAT)
return;
MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$
sortMenu.add(fSortByNameAction);
sortMenu.add(fSortByPathAction);
sortMenu.add(fSortByParentName);
fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder());
fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder());
fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder());
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
}
protected void fillToolbar(IToolBarManager tbm) {
super.fillToolbar(tbm);
if (getLayout() != FLAG_LAYOUT_FLAT)
addGroupActions(tbm);
}
private void addGroupActions(IToolBarManager mgr) {
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(GROUP_GROUPING));
mgr.appendToGroup(GROUP_GROUPING, fGroupProjectAction);
mgr.appendToGroup(GROUP_GROUPING, fGroupPackageAction);
mgr.appendToGroup(GROUP_GROUPING, fGroupFileAction);
mgr.appendToGroup(GROUP_GROUPING, fGroupTypeAction);
updateGroupingActions();
}
private void updateGroupingActions() {
fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT);
fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE);
fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE);
fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE);
}
public void dispose() {
fActionGroup.dispose();
super.dispose();
}
protected void elementsChanged(Object[] objects) {
if (fContentProvider != null)
fContentProvider.elementsChanged(objects);
}
protected void clear() {
if (fContentProvider != null)
fContentProvider.clear();
}
protected void configureTableViewer(TableViewer viewer) {
viewer.setUseHashlookup(true);
viewer.setLabelProvider(new DecoratingLabelProvider(new SortingLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
fContentProvider=new JavaSearchTableContentProvider(this);
viewer.setContentProvider(fContentProvider);
setSortOrder(fCurrentSortOrder);
}
protected void configureTreeViewer(TreeViewer viewer) {
viewer.setUseHashlookup(true);
viewer.setSorter(new ViewerSorter());
viewer.setLabelProvider(new DecoratingLabelProvider(new PostfixLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
fContentProvider= new LevelTreeContentProvider(this, fCurrentGrouping);
viewer.setContentProvider(fContentProvider);
}
protected TreeViewer createTreeViewer(Composite parent) {
return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
}
class MyProblemTable extends ProblemTableViewer {
MyProblemTable(Composite parent, int flags) {
super(parent, flags);
}
protected void internalRefresh(Object element, boolean updateLabels) {
if (element == null || equals(element, getRoot())) {
// the parent
// in the code below, it is important to do all disassociates
// before any associates, since a later disassociate can undo an earlier associate
// e.g. if (a, b) is replaced by (b, a), the disassociate of b to item 1 could undo
// the associate of b to item 0.
Object[] children = getSortedChildren(getRoot());
getTable().removeAll();
// add any remaining elements
for (int i = 0; i < children.length; ++i) {
updateItem(new TableItem(getTable(), SWT.NONE, i), children[i]);
}
}
else {
Widget w = findItem(element);
if (w != null) {
updateItem(w, element);
}
}
}
}
protected TableViewer createTableViewer(Composite parent) {
return new ProblemTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) {
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
getTable().setRedraw(false);
try {
super.handleLabelProviderChanged(event);
} finally {
getTable().setRedraw(true);
}
}
};
}
void setSortOrder(int order) {
fCurrentSortOrder= order;
StructuredViewer viewer= getViewer();
viewer.getControl().setRedraw(false);
DecoratingLabelProvider dlp= (DecoratingLabelProvider) viewer.getLabelProvider();
((SortingLabelProvider)dlp.getLabelProvider()).setOrder(order);
if (order == SortingLabelProvider.SHOW_ELEMENT_CONTAINER) {
viewer.setSorter(new NameSorter());
} else if (order == SortingLabelProvider.SHOW_PATH) {
viewer.setSorter(new PathSorter());
} else
viewer.setSorter(new ParentSorter());
viewer.getControl().setRedraw(true);
getSettings().put(KEY_SORTING, fCurrentSortOrder);
}
public void init(IPageSite site) {
super.init(site);
fActionGroup.fillActionBars(site.getActionBars());
addFilterActions(site.getActionBars().getMenuManager());
}
/**
* Precondition here: the viewer must be showing a tree with a LevelContentProvider.
* @param order
*/
void setGrouping(int grouping) {
fCurrentGrouping= grouping;
StructuredViewer viewer= getViewer();
LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider();
cp.setLevel(grouping);
updateGroupingActions();
getSettings().put(KEY_GROUPING, fCurrentGrouping);
}
protected StructuredViewer getViewer() {
// override so that it's visible in the package.
return super.getViewer();
}
/* (non-Javadoc)
* @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#restoreState(org.eclipse.ui.IMemento)
*/
public void restoreState(IMemento memento) {
super.restoreState(memento);
try {
fCurrentSortOrder= getSettings().getInt(KEY_SORTING);
} catch (NumberFormatException e) {
fCurrentSortOrder= SortingLabelProvider.SHOW_ELEMENT_CONTAINER;
}
try {
fCurrentGrouping= getSettings().getInt(KEY_GROUPING);
} catch (NumberFormatException e) {
fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE;
}
String encodedFilters= getSettings().get(KEY_FILTERS);
restoreFilters(encodedFilters);
if (memento != null) {
Integer value= memento.getInteger(KEY_GROUPING);
if (value != null)
fCurrentGrouping= value.intValue();
value= memento.getInteger(KEY_SORTING);
if (value != null)
fCurrentSortOrder= value.intValue();
encodedFilters= memento.getString(KEY_FILTERS);
restoreFilters(encodedFilters);
}
}
private void restoreFilters(String encodedFilters) {
if (encodedFilters != null) {
fMatchFilters.clear();
String[] decodedFilters= decodeFiltersString(encodedFilters);
for (int i= 0; i < decodedFilters.length; i++) {
MatchFilter filter= findMatchFilter(decodedFilters[i]);
if (filter != null)
fMatchFilters.add(filter);
}
}
updateFilterActions();
}
private MatchFilter findMatchFilter(String id) {
MatchFilter[] allFilters= MatchFilter.allFilters();
for (int i= 0; i < allFilters.length; i++) {
if (allFilters[i].getID().equals(id))
return allFilters[i];
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#saveState(org.eclipse.ui.IMemento)
*/
public void saveState(IMemento memento) {
super.saveState(memento);
memento.putInteger(KEY_GROUPING, fCurrentGrouping);
memento.putInteger(KEY_SORTING, fCurrentSortOrder);
memento.putString(KEY_FILTERS, encodeFilters());
}
void addMatchFilter(MatchFilter filter) {
fMatchFilters.add(filter);
filtersChanged();
}
void removeMatchFilter(MatchFilter filter) {
fMatchFilters.remove(filter);
filtersChanged();
}
private void filtersChanged() {
StructuredViewer viewer= getViewer();
JavaSearchContentProvider cp= (JavaSearchContentProvider) viewer.getContentProvider();
cp.filtersChanged(getMatchFilters());
updateFilterActions();
getViewPart().updateLabel();
getSettings().put(KEY_FILTERS, encodeFilters());
}
private void updateFilterActions() {
for (int i= 0; i < fFilterActions.length; i++) {
fFilterActions[i].updateCheckState();
}
getSite().getActionBars().updateActionBars();
getSite().getActionBars().getMenuManager().updateAll(true);
}
private String encodeFilters() {
StringBuffer buf= new StringBuffer();
MatchFilter[] enabledFilters= getMatchFilters();
buf.append(enabledFilters.length);
for (int i= 0; i < enabledFilters.length; i++) {
buf.append(';');
buf.append(enabledFilters[i].getID());
}
return buf.toString();
}
private String[] decodeFiltersString(String encodedString) {
StringTokenizer tokenizer= new StringTokenizer(encodedString, ";"); //$NON-NLS-1$
int count= Integer.valueOf(tokenizer.nextToken()).intValue();
String[] ids= new String[count];
for (int i= 0; i < count; i++) {
ids[i]= tokenizer.nextToken();
}
return ids;
}
boolean hasMatchFilter(MatchFilter filter) {
return fMatchFilters.contains(filter);
}
MatchFilter[] getMatchFilters() {
MatchFilter[] filters= new MatchFilter[fMatchFilters.size()];
return (MatchFilter[]) fMatchFilters.toArray(filters);
}
public int getDisplayedMatchCount(Object element) {
if (getMatchFilters().length == 0)
return super.getDisplayedMatchCount(element);
Match[] matches= super.getDisplayedMatches(element);
int count= 0;
for (int i= 0; i < matches.length; i++) {
if (!isFiltered(matches[i]))
count++;
}
return count;
}
public Match[] getDisplayedMatches(Object element) {
if (getMatchFilters().length == 0)
return super.getDisplayedMatches(element);
Match[] matches= super.getDisplayedMatches(element);
int count= 0;
for (int i= 0; i < matches.length; i++) {
if (isFiltered(matches[i]))
matches[i]= null;
else
count++;
}
Match[] filteredMatches= new Match[count];
int writeIndex= 0;
for (int i= 0; i < matches.length; i++) {
if (matches[i] != null)
filteredMatches[writeIndex++]= matches[i];
}
return filteredMatches;
}
private boolean isFiltered(Match match) {
MatchFilter[] filters= getMatchFilters();
for (int j= 0; j < filters.length; j++) {
if ((match instanceof JavaElementMatch) && filters[j].filters((JavaElementMatch) match))
return true;
}
return false;
}
public void setInput(ISearchResult search, Object viewState) {
updateFilterEnablement((JavaSearchResult)search);
super.setInput(search, viewState);
}
private void updateFilterEnablement(JavaSearchResult result) {
for (int i= 0; i < fFilterActions.length; i++) {
fFilterActions[i].setEnabled(shouldEnable(result, fFilterActions[i]));
}
}
private boolean shouldEnable(JavaSearchResult result, FilterAction filterAction) {
if (result == null) {
return false;
}
JavaSearchQuery query= (JavaSearchQuery) result.getQuery();
if (query == null)
return false;
return filterAction.getFilter().isApplicable(query);
}
private boolean isQueryRunning() {
AbstractTextSearchResult result= getInput();
if (result != null) {
return NewSearchUI.isQueryRunning(result.getQuery());
}
return false;
}
public String getLabel() {
String label= super.getLabel();
int matchFilterCount= getMatchFiltersCount();
if (matchFilterCount > 0) {
if (isQueryRunning()) {
String message= SearchMessages.getString("JavaSearchResultPage.filtered.message"); //$NON-NLS-1$
return MessageFormat.format(message, new Object[] { label });
} else {
String message= SearchMessages.getString("JavaSearchResultPage.filteredWithCount.message"); //$NON-NLS-1$
return MessageFormat.format(message, new Object[] { label, new Integer(getFilteredMatchCount()) });
}
}
return label;
}
private int getMatchFiltersCount() {
MatchFilter[] filters= getMatchFilters();
AbstractTextSearchResult result= getInput();
if (result == null)
return 0;
int filterCount= 0;
for (int i= 0; i < filters.length; i++) {
if (filters[i].isApplicable((JavaSearchQuery) result.getQuery()))
filterCount++;
}
return filterCount;
}
private int getFilteredMatchCount() {
AbstractTextSearchResult result= getInput();
if (result == null)
return 0;
Object[] elements= result.getElements();
int count= 0;
for (int i= 0; i < elements.length; i++) {
count+= getDisplayedMatchCount(elements[i]);
}
return count;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter(Class adapter) {
if (IShowInTargetList.class.equals(adapter)) {
return SHOW_IN_TARGET_LIST;
}
return null;
}
}
|
62,386
|
Bug 62386 can't turn off Filter imports
|
Version: 3.0.0 Build id: 200405140800 Linux Gtk+ Turned on Filter Imports in the search view, now I can't turn it off. Option to turn off Filter Imports is unavailable.
|
resolved fixed
|
39e0a7b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T08:24:29Z
| 2004-05-14T21:26:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/MatchFilter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* 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.search;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.ui.search.ElementQuerySpecification;
import org.eclipse.jdt.ui.search.PatternQuerySpecification;
import org.eclipse.jdt.ui.search.QuerySpecification;
abstract class MatchFilter {
public abstract boolean isApplicable(JavaSearchQuery query);
public abstract boolean filters(JavaElementMatch match);
public abstract String getName();
public abstract String getDescription();
public abstract String getID();
private static final MatchFilter[] ALL_FILTERS= new MatchFilter[] {
new ImportFilter(),
new JavadocFilter(),
new ReadFilter(),
new WriteFilter()
};
public static MatchFilter[] allFilters() {
return ALL_FILTERS;
}
}
class ImportFilter extends MatchFilter {
public boolean filters(JavaElementMatch match) {
return match.getElement() instanceof IImportDeclaration;
}
public String getName() {
return SearchMessages.getString("MatchFilter.ImportFilter.name"); //$NON-NLS-1$
}
public String getDescription() {
return SearchMessages.getString("MatchFilter.ImportFilter.description"); //$NON-NLS-1$
}
public boolean isApplicable(JavaSearchQuery query) {
QuerySpecification spec= query.getSpecification();
if (spec instanceof ElementQuerySpecification) {
ElementQuerySpecification elementSpec= (ElementQuerySpecification) spec;
return elementSpec.getElement() instanceof IType;
} else if (spec instanceof PatternQuerySpecification) {
PatternQuerySpecification patternSpec= (PatternQuerySpecification) spec;
return patternSpec.getSearchFor() == IJavaSearchConstants.TYPE;
}
return false;
}
public String getID() {
return "filter_imports"; //$NON-NLS-1$
}
}
abstract class FieldFilter extends MatchFilter {
public boolean isApplicable(JavaSearchQuery query) {
QuerySpecification spec= query.getSpecification();
if (spec instanceof ElementQuerySpecification) {
ElementQuerySpecification elementSpec= (ElementQuerySpecification) spec;
return elementSpec.getElement() instanceof IField;
} else if (spec instanceof ElementQuerySpecification) {
PatternQuerySpecification patternSpec= (PatternQuerySpecification) spec;
return patternSpec.getSearchFor() == IJavaSearchConstants.FIELD;
}
return false;
}
}
class WriteFilter extends FieldFilter {
public boolean filters(JavaElementMatch match) {
return match.isWriteAccess();
}
public String getName() {
return SearchMessages.getString("MatchFilter.WriteFilter.name"); //$NON-NLS-1$
}
public String getDescription() {
return SearchMessages.getString("MatchFilter.WriteFilter.description"); //$NON-NLS-1$
}
public String getID() {
return "filter_writes"; //$NON-NLS-1$
}
}
class ReadFilter extends FieldFilter {
public boolean filters(JavaElementMatch match) {
return match.isReadAccess();
}
public String getName() {
return SearchMessages.getString("MatchFilter.ReadFilter.name"); //$NON-NLS-1$
}
public String getDescription() {
return SearchMessages.getString("MatchFilter.ReadFilter.description"); //$NON-NLS-1$
}
public String getID() {
return "filter_reads"; //$NON-NLS-1$
}
}
class JavadocFilter extends MatchFilter {
public boolean filters(JavaElementMatch match) {
return match.isJavadoc();
}
public String getName() {
return SearchMessages.getString("MatchFilter.JavadocFilter.name"); //$NON-NLS-1$
}
public String getDescription() {
return SearchMessages.getString("MatchFilter.JavadocFilter.description"); //$NON-NLS-1$
}
public boolean isApplicable(JavaSearchQuery query) {
return true;
}
public String getID() {
return "filter_javadoc"; //$NON-NLS-1$
}
}
|
62,398
|
Bug 62398 Deadlock while editing Java File
|
Build id: 200405130010 While editing a java file the UI became unresponsive. I had just removed some projects then started typing into a java editor that was already open. As soon as i started typing the UI locked up. I don't have a reproducible test case, but luckily i was running with a console and got a thread dump.
|
resolved fixed
|
af7b8d3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T08:34:13Z
| 2004-05-15T08:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/OverrideIndicatorManager.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.ui.PartInitException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
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.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener;
/**
* Manages the override and overwrite indicators for
* the given Java element and annotation model.
*
* @since 3.0
*/
class OverrideIndicatorManager implements IJavaReconcilingListener {
/**
* Overwrite and override indicator annotation.
*
* @since 3.0
*/
class OverrideIndicator extends Annotation {
private boolean fIsOverwriteIndicator;
private String fAstNodeKey;
/**
* Creates a new override annotation.
*
* @param isOverwriteIndicator <code>true</code> if this annotation is
* an overwrite indicator, <code>false</code> otherwise
* @param text the text associated with this annotation
* @param key the method binding key
* @since 3.0
*/
OverrideIndicator(boolean isOverwriteIndicator, String text, String key) {
super(ANNOTATION_TYPE, false, text);
fIsOverwriteIndicator= isOverwriteIndicator;
fAstNodeKey= key;
}
/**
* Tells whether this is an overwrite or an override indicator.
*
* @return <code>true</code> if this is an overwrite indicator
*/
public boolean isOverwriteIndicator() {
return fIsOverwriteIndicator;
}
/**
* Opens and reveals the defining method.
*/
public void open() {
boolean hasLogEntry= false;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(fJavaElement, true, null);
ASTNode node= null;
if (ast != null)
node= ast.findDeclaringNode(fAstNodeKey);
if (node instanceof MethodDeclaration) {
try {
IMethodBinding methodBinding= ((MethodDeclaration)node).resolveBinding();
IMethodBinding definingMethodBinding= Bindings.findMethodDefininition(methodBinding);
if (definingMethodBinding != null) {
String definingTypeQualifiedName= definingMethodBinding.getDeclaringClass().getQualifiedName();
IType definingType= null;
IType type= getType(methodBinding);
if (type != null) {
ITypeHierarchy th= SuperTypeHierarchyCache.getTypeHierarchy(type);
IType[] superTypes= th.getAllSupertypes(type);
definingType= findType(superTypes, definingTypeQualifiedName);
} else {
definingType= JavaModelUtil.findType(fJavaElement.getJavaProject(), definingTypeQualifiedName);
}
if (definingType != null) {
IMethod definingMethod= Bindings.findMethod(definingMethodBinding, definingType);
if (definingMethod != null) {
OpenActionUtil.open(definingMethod, true);
return;
}
}
}
} catch (JavaModelException ex) {
JavaPlugin.log(ex.getStatus());
hasLogEntry= true;
} catch (PartInitException ex) {
JavaPlugin.log(ex.getStatus());
hasLogEntry= true;
}
}
String title= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.title"); //$NON-NLS-1$
String message;
if (hasLogEntry)
message= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.messageHasLogEntry"); //$NON-NLS-1$
else
message= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.message"); //$NON-NLS-1$
MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
private IType getType(IMethodBinding methodBinding) throws JavaModelException {
if (methodBinding == null)
return null;
int type= fJavaElement.getElementType();
IType[] types= null;
if (type == IJavaElement.COMPILATION_UNIT)
types= ((ICompilationUnit)fJavaElement).getAllTypes();
else if (type == IJavaElement.CLASS_FILE)
types= new IType[] { ((IClassFile)fJavaElement).getType() };
return findType(types, methodBinding.getDeclaringClass().getQualifiedName());
}
private IType findType(IType[] types, String fullyQualifiedName) throws JavaModelException {
if (types == null)
return null;
for (int i= 0; i < types.length; i++) {
IType type= types[i];
if (JavaModelUtil.getFullyQualifiedName(type).equals(fullyQualifiedName))
return type;
}
return null;
}
}
static final String ANNOTATION_TYPE= "org.eclipse.jdt.ui.overrideIndicator"; //$NON-NLS-1$
private IAnnotationModel fAnnotationModel;
private Object fAnnotationModelLockObject;
private Annotation[] fOverrideAnnotations;
private IJavaElement fJavaElement;
public OverrideIndicatorManager(IAnnotationModel annotationModel, IJavaElement javaElement, CompilationUnit ast) {
Assert.isNotNull(annotationModel);
Assert.isNotNull(javaElement);
fJavaElement= javaElement;
fAnnotationModel=annotationModel;
fAnnotationModelLockObject= getLockObject(fAnnotationModel);
updateAnnotations(ast, new NullProgressMonitor());
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the override and implements annotations based
* on the given AST.
*
* @param ast the compilation unit AST
* @param progressMonitor the progress monitor
* @since 3.0
*/
protected void updateAnnotations(CompilationUnit ast, IProgressMonitor progressMonitor) {
if (ast == null || progressMonitor.isCanceled())
return;
final Map annotationMap= new HashMap(50);
ast.accept(new ASTVisitor(false) {
/*
* @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodDeclaration)
*/
public boolean visit(MethodDeclaration node) {
IMethodBinding binding= node.resolveBinding();
if (binding != null) {
IMethodBinding definingMethod= Bindings.findMethodDefininition(binding);
if (definingMethod != null) {
ITypeBinding definingType= definingMethod.getDeclaringClass();
String qualifiedMethodName= definingType.getQualifiedName() + "." + binding.getName(); //$NON-NLS-1$
boolean isOverwriteIndicator= definingType.isInterface();
String text;
if (isOverwriteIndicator)
text= JavaEditorMessages.getFormattedString("OverrideIndicatorManager.implements", qualifiedMethodName); //$NON-NLS-1$
else
text= JavaEditorMessages.getFormattedString("OverrideIndicatorManager.overrides", qualifiedMethodName); //$NON-NLS-1$
SimpleName name= node.getName();
Position position= new Position(name.getStartPosition(), name.getLength());
annotationMap.put(
new OverrideIndicator(isOverwriteIndicator, text, binding.getKey()), //$NON-NLS-1$
position);
}
}
return false;
}
});
if (progressMonitor.isCanceled())
return;
synchronized (fAnnotationModelLockObject) {
if (fAnnotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, annotationMap);
} else {
removeAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
fAnnotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOverrideAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
}
/**
* Removes all override indicators from this manager's annotation model.
*/
void removeAnnotations() {
if (fOverrideAnnotations == null)
return;
synchronized (fAnnotationModelLockObject) {
if (fAnnotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, null);
} else {
for (int i= 0, length= fOverrideAnnotations.length; i < length; i++)
fAnnotationModel.removeAnnotation(fOverrideAnnotations[i]);
}
fOverrideAnnotations= null;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
*/
public synchronized void aboutToBeReconciled() {
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor)
*/
public synchronized void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) {
updateAnnotations(ast, progressMonitor);
}
}
|
62,425
|
Bug 62425 Externalizing Strings dump (Internal Error) [nls] [refactoring]
|
I Build id: 200405111200 Externalizing Strings fails on a java file that I have, but it is hard to isolate the problem. Im opening the defect just for the stack dump: Internal Error: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:749) at org.eclipse.ltk.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:559) at org.eclipse.ltk.ui.refactoring.RefactoringWizard.computeUserInputSuccessorPage (RefactoringWizard.java:405) at org.eclipse.ltk.ui.refactoring.UserInputWizardPage.computeSuccessorPage (UserInputWizardPage.java:72) at org.eclipse.ltk.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:112) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage.getNextPage (ExternalizeWizardPage.java:1066) at org.eclipse.jface.wizard.WizardDialog.nextPressed(WizardDialog.java:672) at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:300) at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:505) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.jface.window.Window.runEventLoop(Window.java:668) at org.eclipse.jface.window.Window.open(Window.java:648) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run (RefactoringWizardOpenOperation.java:120) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.openExternalizeStringsWizar d(ExternalizeStringsAction.java:157) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction$NonNLSListDialog.open Wizard(FindStringsToExternalizeAction.java:406) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction$NonNLSListDialog.butt onPressed(FindStringsToExternalizeAction.java:400) at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:505) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.jface.window.Window.runEventLoop(Window.java:668) at org.eclipse.jface.window.Window.open(Window.java:648) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction.showResults (FindStringsToExternalizeAction.java:196) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction.run (FindStringsToExternalizeAction.java:150) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:891) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:842) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:761) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.unwindEscapeChars(PropertyFileDocumentModel.java:216) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.getEncodedText(PropertyFileDocumentModel.java:158) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel.inser t(PropertyFileDocumentModel.java:41) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addInse rtEdits(NLSPropertyFileModifier.java:95) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addChan ges(NLSPropertyFileModifier.java:66) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.create (NLSPropertyFileModifier.java:44) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.createChange (NLSRefactoring.java:215) at org.eclipse.ltk.core.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:117) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1674) at org.eclipse.ltk.internal.ui.refactoring.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:52) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Root exception: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.unwindEscapeChars(PropertyFileDocumentModel.java:216) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.getEncodedText(PropertyFileDocumentModel.java:158) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel.inser t(PropertyFileDocumentModel.java:41) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addInse rtEdits(NLSPropertyFileModifier.java:95) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addChan ges(NLSPropertyFileModifier.java:66) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.create (NLSPropertyFileModifier.java:44) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.createChange (NLSRefactoring.java:215) at org.eclipse.ltk.core.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:117) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1674) at org.eclipse.ltk.internal.ui.refactoring.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:52) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
d262001
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T12:34:00Z
| 2004-05-16T17:53:20Z
|
org.eclipse.jdt.ui/core
| |
62,425
|
Bug 62425 Externalizing Strings dump (Internal Error) [nls] [refactoring]
|
I Build id: 200405111200 Externalizing Strings fails on a java file that I have, but it is hard to isolate the problem. Im opening the defect just for the stack dump: Internal Error: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:749) at org.eclipse.ltk.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:559) at org.eclipse.ltk.ui.refactoring.RefactoringWizard.computeUserInputSuccessorPage (RefactoringWizard.java:405) at org.eclipse.ltk.ui.refactoring.UserInputWizardPage.computeSuccessorPage (UserInputWizardPage.java:72) at org.eclipse.ltk.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:112) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage.getNextPage (ExternalizeWizardPage.java:1066) at org.eclipse.jface.wizard.WizardDialog.nextPressed(WizardDialog.java:672) at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:300) at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:505) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.jface.window.Window.runEventLoop(Window.java:668) at org.eclipse.jface.window.Window.open(Window.java:648) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run (RefactoringWizardOpenOperation.java:120) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.openExternalizeStringsWizar d(ExternalizeStringsAction.java:157) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction$NonNLSListDialog.open Wizard(FindStringsToExternalizeAction.java:406) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction$NonNLSListDialog.butt onPressed(FindStringsToExternalizeAction.java:400) at org.eclipse.jface.dialogs.Dialog$2.widgetSelected(Dialog.java:505) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.jface.window.Window.runEventLoop(Window.java:668) at org.eclipse.jface.window.Window.open(Window.java:648) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction.showResults (FindStringsToExternalizeAction.java:196) at org.eclipse.jdt.ui.actions.FindStringsToExternalizeAction.run (FindStringsToExternalizeAction.java:150) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:212) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:891) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:842) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:761) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.unwindEscapeChars(PropertyFileDocumentModel.java:216) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.getEncodedText(PropertyFileDocumentModel.java:158) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel.inser t(PropertyFileDocumentModel.java:41) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addInse rtEdits(NLSPropertyFileModifier.java:95) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addChan ges(NLSPropertyFileModifier.java:66) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.create (NLSPropertyFileModifier.java:44) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.createChange (NLSRefactoring.java:215) at org.eclipse.ltk.core.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:117) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1674) at org.eclipse.ltk.internal.ui.refactoring.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:52) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101) Root exception: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.unwindEscapeChars(PropertyFileDocumentModel.java:216) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel$KeyVa luePairModell.getEncodedText(PropertyFileDocumentModel.java:158) at org.eclipse.jdt.internal.corext.refactoring.nls.PropertyFileDocumentModel.inser t(PropertyFileDocumentModel.java:41) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addInse rtEdits(NLSPropertyFileModifier.java:95) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.addChan ges(NLSPropertyFileModifier.java:66) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSPropertyFileModifier.create (NLSPropertyFileModifier.java:44) at org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring.createChange (NLSRefactoring.java:215) at org.eclipse.ltk.core.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:117) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1674) at org.eclipse.ltk.internal.ui.refactoring.WorkbenchRunnableAdapter.run (WorkbenchRunnableAdapter.java:52) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
|
resolved fixed
|
d262001
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T12:34:00Z
| 2004-05-16T17:53:20Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSPropertyFileModifier.java
| |
54,459
|
Bug 54459 New search view: Double click on type should open CU [search]
|
20040311 in the new search results view, I happen to have to click a lot to expand the trees so I can finally double click the method element to open the editor. What I always expect is that doouble clicking the type opens the editor and I'm always irritated that it doesn't, propably because in all other views (package explorer, hierarchy, outline) this is the case. is there a good reason why not offering this short cut?
|
resolved fixed
|
fc556e8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T12:34:06Z
| 2004-03-11T13:00:00Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.search.IMatchPresentation;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.search.ui.IContextMenuConstants;
import org.eclipse.search.ui.ISearchResult;
import org.eclipse.search.ui.ISearchResultViewPart;
import org.eclipse.search.ui.NewSearchUI;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.ui.text.AbstractTextSearchResult;
import org.eclipse.search.ui.text.AbstractTextSearchViewPage;
import org.eclipse.search.ui.text.Match;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.ide.IDE;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.ITextEditor;
public class JavaSearchResultPage extends AbstractTextSearchViewPage implements IAdaptable {
private static final String KEY_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$
private static final String KEY_SORTING= "org.eclipse.jdt.search.resultpage.sorting"; //$NON-NLS-1$
private static final String KEY_FILTERS= "org.eclipse.jdt.search.resultpage.filters"; //$NON-NLS-1$
private static final String GROUP_GROUPING= "org.eclipse.jdt.search.resultpage.grouping"; //$NON-NLS-1$
private NewSearchViewActionGroup fActionGroup;
private JavaSearchContentProvider fContentProvider;
private int fCurrentSortOrder;
private SortAction fSortByNameAction;
private SortAction fSortByParentName;
private SortAction fSortByPathAction;
private GroupAction fGroupTypeAction;
private GroupAction fGroupFileAction;
private GroupAction fGroupPackageAction;
private GroupAction fGroupProjectAction;
private int fCurrentGrouping;
private Set fMatchFilters= new HashSet();
private FilterAction[] fFilterActions;
private static final String[] SHOW_IN_TARGETS= new String[] { JavaUI.ID_PACKAGES , IPageLayout.ID_RES_NAV };
public static final IShowInTargetList SHOW_IN_TARGET_LIST= new IShowInTargetList() {
public String[] getShowInTargetIds() {
return SHOW_IN_TARGETS;
}
};
private JavaSearchEditorOpener fEditorOpener= new JavaSearchEditorOpener();
public JavaSearchResultPage() {
initSortActions();
initGroupingActions();
initFilterActions();
}
private void initFilterActions() {
MatchFilter[] allFilters= MatchFilter.allFilters();
fFilterActions= new FilterAction[allFilters.length];
for (int i= 0; i < fFilterActions.length; i++) {
fFilterActions[i]= new FilterAction(this, allFilters[i]);
fFilterActions[i].setId("org.eclipse.jdt.search.filters."+i); //$NON-NLS-1$
}
}
private void initSortActions() {
fSortByNameAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByName"), this, SortingLabelProvider.SHOW_ELEMENT_CONTAINER); //$NON-NLS-1$
fSortByPathAction= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByPath"), this, SortingLabelProvider.SHOW_PATH); //$NON-NLS-1$
fSortByParentName= new SortAction(SearchMessages.getString("JavaSearchResultPage.sortByParentName"), this, SortingLabelProvider.SHOW_CONTAINER_ELEMENT); //$NON-NLS-1$
}
private void initGroupingActions() {
fGroupProjectAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_project"), SearchMessages.getString("JavaSearchResultPage.groupby_project.tooltip"), this, LevelTreeContentProvider.LEVEL_PROJECT); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupProjectAction, "prj_mode.gif"); //$NON-NLS-1$
fGroupPackageAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_package"), SearchMessages.getString("JavaSearchResultPage.groupby_package.tooltip"), this, LevelTreeContentProvider.LEVEL_PACKAGE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupPackageAction, "package_mode.gif"); //$NON-NLS-1$
fGroupFileAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_file"), SearchMessages.getString("JavaSearchResultPage.groupby_file.tooltip"), this, LevelTreeContentProvider.LEVEL_FILE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupFileAction, "file_mode.gif"); //$NON-NLS-1$
fGroupTypeAction= new GroupAction(SearchMessages.getString("JavaSearchResultPage.groupby_type"), SearchMessages.getString("JavaSearchResultPage.groupby_type.tooltip"), this, LevelTreeContentProvider.LEVEL_TYPE); //$NON-NLS-1$ //$NON-NLS-2$
JavaPluginImages.setLocalImageDescriptors(fGroupTypeAction, "type_mode.gif"); //$NON-NLS-1$
}
public void setViewPart(ISearchResultViewPart part) {
super.setViewPart(part);
fActionGroup= new NewSearchViewActionGroup(part);
}
public void showMatch(Match match, int offset, int length, boolean activate) throws PartInitException {
IEditorPart editor;
try {
editor= fEditorOpener.open(match);
} catch (JavaModelException e) {
throw new PartInitException(e.getStatus());
}
if (editor != null && activate)
editor.getEditorSite().getPage().activate(editor);
Object element= match.getElement();
if (editor instanceof ITextEditor) {
ITextEditor textEditor= (ITextEditor) editor;
textEditor.selectAndReveal(offset, length);
} else if (editor != null){
if (element instanceof IFile) {
IFile file= (IFile) element;
showWithMarker(editor, file, offset, length);
}
} else {
JavaSearchResult result= (JavaSearchResult) getInput();
IMatchPresentation participant= result.getSearchParticpant(element);
if (participant != null)
participant.showMatch(match, offset, length, activate);
}
}
private void showWithMarker(IEditorPart editor, IFile file, int offset, int length) throws PartInitException {
try {
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
HashMap attributes= new HashMap(4);
attributes.put(IMarker.CHAR_START, new Integer(offset));
attributes.put(IMarker.CHAR_END, new Integer(offset + length));
marker.setAttributes(attributes);
IDE.gotoMarker(editor, marker);
marker.delete();
} catch (CoreException e) {
throw new PartInitException(SearchMessages.getString("JavaSearchResultPage.error.marker"), e); //$NON-NLS-1$
}
}
protected void fillContextMenu(IMenuManager mgr) {
super.fillContextMenu(mgr);
addSortActions(mgr);
fActionGroup.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroup.fillContextMenu(mgr);
}
private void addFilterActions(IMenuManager viewMenu) {
String filteringGroup= "Filtering"; //$NON-NLS-1$
viewMenu.insertBefore(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(filteringGroup));
for (int i= 0; i < fFilterActions.length; i++) {
viewMenu.appendToGroup(filteringGroup, fFilterActions[i]);
}
}
private void addSortActions(IMenuManager mgr) {
if (getLayout() != FLAG_LAYOUT_FLAT)
return;
MenuManager sortMenu= new MenuManager(SearchMessages.getString("JavaSearchResultPage.sortBylabel")); //$NON-NLS-1$
sortMenu.add(fSortByNameAction);
sortMenu.add(fSortByPathAction);
sortMenu.add(fSortByParentName);
fSortByNameAction.setChecked(fCurrentSortOrder == fSortByNameAction.getSortOrder());
fSortByPathAction.setChecked(fCurrentSortOrder == fSortByPathAction.getSortOrder());
fSortByParentName.setChecked(fCurrentSortOrder == fSortByParentName.getSortOrder());
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, sortMenu);
}
protected void fillToolbar(IToolBarManager tbm) {
super.fillToolbar(tbm);
if (getLayout() != FLAG_LAYOUT_FLAT)
addGroupActions(tbm);
}
private void addGroupActions(IToolBarManager mgr) {
mgr.appendToGroup(IContextMenuConstants.GROUP_VIEWER_SETUP, new Separator(GROUP_GROUPING));
mgr.appendToGroup(GROUP_GROUPING, fGroupProjectAction);
mgr.appendToGroup(GROUP_GROUPING, fGroupPackageAction);
mgr.appendToGroup(GROUP_GROUPING, fGroupFileAction);
mgr.appendToGroup(GROUP_GROUPING, fGroupTypeAction);
updateGroupingActions();
}
private void updateGroupingActions() {
fGroupProjectAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PROJECT);
fGroupPackageAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_PACKAGE);
fGroupFileAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_FILE);
fGroupTypeAction.setChecked(fCurrentGrouping == LevelTreeContentProvider.LEVEL_TYPE);
}
public void dispose() {
fActionGroup.dispose();
super.dispose();
}
protected void elementsChanged(Object[] objects) {
if (fContentProvider != null)
fContentProvider.elementsChanged(objects);
}
protected void clear() {
if (fContentProvider != null)
fContentProvider.clear();
}
protected void configureTableViewer(TableViewer viewer) {
viewer.setUseHashlookup(true);
viewer.setLabelProvider(new DecoratingLabelProvider(new SortingLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
fContentProvider=new JavaSearchTableContentProvider(this);
viewer.setContentProvider(fContentProvider);
setSortOrder(fCurrentSortOrder);
}
protected void configureTreeViewer(TreeViewer viewer) {
viewer.setUseHashlookup(true);
viewer.setSorter(new ViewerSorter());
viewer.setLabelProvider(new DecoratingLabelProvider(new PostfixLabelProvider(this), PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator()));
fContentProvider= new LevelTreeContentProvider(this, fCurrentGrouping);
viewer.setContentProvider(fContentProvider);
}
protected TreeViewer createTreeViewer(Composite parent) {
return new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
}
class MyProblemTable extends ProblemTableViewer {
MyProblemTable(Composite parent, int flags) {
super(parent, flags);
}
protected void internalRefresh(Object element, boolean updateLabels) {
if (element == null || equals(element, getRoot())) {
// the parent
// in the code below, it is important to do all disassociates
// before any associates, since a later disassociate can undo an earlier associate
// e.g. if (a, b) is replaced by (b, a), the disassociate of b to item 1 could undo
// the associate of b to item 0.
Object[] children = getSortedChildren(getRoot());
getTable().removeAll();
// add any remaining elements
for (int i = 0; i < children.length; ++i) {
updateItem(new TableItem(getTable(), SWT.NONE, i), children[i]);
}
}
else {
Widget w = findItem(element);
if (w != null) {
updateItem(w, element);
}
}
}
}
protected TableViewer createTableViewer(Composite parent) {
return new ProblemTableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL) {
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
getTable().setRedraw(false);
try {
super.handleLabelProviderChanged(event);
} finally {
getTable().setRedraw(true);
}
}
};
}
void setSortOrder(int order) {
fCurrentSortOrder= order;
StructuredViewer viewer= getViewer();
viewer.getControl().setRedraw(false);
DecoratingLabelProvider dlp= (DecoratingLabelProvider) viewer.getLabelProvider();
((SortingLabelProvider)dlp.getLabelProvider()).setOrder(order);
if (order == SortingLabelProvider.SHOW_ELEMENT_CONTAINER) {
viewer.setSorter(new NameSorter());
} else if (order == SortingLabelProvider.SHOW_PATH) {
viewer.setSorter(new PathSorter());
} else
viewer.setSorter(new ParentSorter());
viewer.getControl().setRedraw(true);
getSettings().put(KEY_SORTING, fCurrentSortOrder);
}
public void init(IPageSite site) {
super.init(site);
fActionGroup.fillActionBars(site.getActionBars());
addFilterActions(site.getActionBars().getMenuManager());
}
/**
* Precondition here: the viewer must be showing a tree with a LevelContentProvider.
* @param order
*/
void setGrouping(int grouping) {
fCurrentGrouping= grouping;
StructuredViewer viewer= getViewer();
LevelTreeContentProvider cp= (LevelTreeContentProvider) viewer.getContentProvider();
cp.setLevel(grouping);
updateGroupingActions();
getSettings().put(KEY_GROUPING, fCurrentGrouping);
}
protected StructuredViewer getViewer() {
// override so that it's visible in the package.
return super.getViewer();
}
/* (non-Javadoc)
* @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#restoreState(org.eclipse.ui.IMemento)
*/
public void restoreState(IMemento memento) {
super.restoreState(memento);
try {
fCurrentSortOrder= getSettings().getInt(KEY_SORTING);
} catch (NumberFormatException e) {
fCurrentSortOrder= SortingLabelProvider.SHOW_ELEMENT_CONTAINER;
}
try {
fCurrentGrouping= getSettings().getInt(KEY_GROUPING);
} catch (NumberFormatException e) {
fCurrentGrouping= LevelTreeContentProvider.LEVEL_PACKAGE;
}
String encodedFilters= getSettings().get(KEY_FILTERS);
restoreFilters(encodedFilters);
if (memento != null) {
Integer value= memento.getInteger(KEY_GROUPING);
if (value != null)
fCurrentGrouping= value.intValue();
value= memento.getInteger(KEY_SORTING);
if (value != null)
fCurrentSortOrder= value.intValue();
encodedFilters= memento.getString(KEY_FILTERS);
restoreFilters(encodedFilters);
}
}
private void restoreFilters(String encodedFilters) {
if (encodedFilters != null) {
fMatchFilters.clear();
String[] decodedFilters= decodeFiltersString(encodedFilters);
for (int i= 0; i < decodedFilters.length; i++) {
MatchFilter filter= findMatchFilter(decodedFilters[i]);
if (filter != null)
fMatchFilters.add(filter);
}
}
updateFilterActions();
}
private MatchFilter findMatchFilter(String id) {
MatchFilter[] allFilters= MatchFilter.allFilters();
for (int i= 0; i < allFilters.length; i++) {
if (allFilters[i].getID().equals(id))
return allFilters[i];
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.search.ui.text.AbstractTextSearchViewPage#saveState(org.eclipse.ui.IMemento)
*/
public void saveState(IMemento memento) {
super.saveState(memento);
memento.putInteger(KEY_GROUPING, fCurrentGrouping);
memento.putInteger(KEY_SORTING, fCurrentSortOrder);
memento.putString(KEY_FILTERS, encodeFilters());
}
void addMatchFilter(MatchFilter filter) {
fMatchFilters.add(filter);
filtersChanged();
}
void removeMatchFilter(MatchFilter filter) {
fMatchFilters.remove(filter);
filtersChanged();
}
private void filtersChanged() {
StructuredViewer viewer= getViewer();
JavaSearchContentProvider cp= (JavaSearchContentProvider) viewer.getContentProvider();
cp.filtersChanged(getMatchFilters());
updateFilterActions();
getViewPart().updateLabel();
getSettings().put(KEY_FILTERS, encodeFilters());
}
private void updateFilterActions() {
IMenuManager menu= getSite().getActionBars().getMenuManager();
for (int i= 0; i < fFilterActions.length; i++) {
fFilterActions[i].updateCheckState();
}
getSite().getActionBars().updateActionBars();
menu.updateAll(true);
}
private String encodeFilters() {
StringBuffer buf= new StringBuffer();
MatchFilter[] enabledFilters= getMatchFilters();
buf.append(enabledFilters.length);
for (int i= 0; i < enabledFilters.length; i++) {
buf.append(';');
buf.append(enabledFilters[i].getID());
}
return buf.toString();
}
private String[] decodeFiltersString(String encodedString) {
StringTokenizer tokenizer= new StringTokenizer(encodedString, ";"); //$NON-NLS-1$
int count= Integer.valueOf(tokenizer.nextToken()).intValue();
String[] ids= new String[count];
for (int i= 0; i < count; i++) {
ids[i]= tokenizer.nextToken();
}
return ids;
}
boolean hasMatchFilter(MatchFilter filter) {
return fMatchFilters.contains(filter);
}
MatchFilter[] getMatchFilters() {
MatchFilter[] filters= new MatchFilter[fMatchFilters.size()];
return (MatchFilter[]) fMatchFilters.toArray(filters);
}
public int getDisplayedMatchCount(Object element) {
if (getMatchFilters().length == 0)
return super.getDisplayedMatchCount(element);
Match[] matches= super.getDisplayedMatches(element);
int count= 0;
for (int i= 0; i < matches.length; i++) {
if (!isFiltered(matches[i]))
count++;
}
return count;
}
public Match[] getDisplayedMatches(Object element) {
if (getMatchFilters().length == 0)
return super.getDisplayedMatches(element);
Match[] matches= super.getDisplayedMatches(element);
int count= 0;
for (int i= 0; i < matches.length; i++) {
if (isFiltered(matches[i]))
matches[i]= null;
else
count++;
}
Match[] filteredMatches= new Match[count];
int writeIndex= 0;
for (int i= 0; i < matches.length; i++) {
if (matches[i] != null)
filteredMatches[writeIndex++]= matches[i];
}
return filteredMatches;
}
private boolean isFiltered(Match match) {
MatchFilter[] filters= getMatchFilters();
for (int j= 0; j < filters.length; j++) {
if ((match instanceof JavaElementMatch) && filters[j].filters((JavaElementMatch) match))
return true;
}
return false;
}
public void setInput(ISearchResult search, Object viewState) {
updateFilterEnablement((JavaSearchResult)search);
super.setInput(search, viewState);
}
private void updateFilterEnablement(JavaSearchResult result) {
IActionBars bars= getSite().getActionBars();
IMenuManager menu= bars.getMenuManager();
for (int i= 0; i < fFilterActions.length; i++) {
menu.remove(fFilterActions[i].getId());
}
for (int i= 0; i < fFilterActions.length; i++) {
if (shouldEnable(result, fFilterActions[i]))
menu.add(fFilterActions[i]);
}
menu.updateAll(true);
bars.updateActionBars();
}
private boolean shouldEnable(JavaSearchResult result, FilterAction filterAction) {
if (result == null) {
return false;
}
JavaSearchQuery query= (JavaSearchQuery) result.getQuery();
if (query == null)
return false;
return filterAction.getFilter().isApplicable(query);
}
private boolean isQueryRunning() {
AbstractTextSearchResult result= getInput();
if (result != null) {
return NewSearchUI.isQueryRunning(result.getQuery());
}
return false;
}
public String getLabel() {
String label= super.getLabel();
int matchFilterCount= getMatchFiltersCount();
if (matchFilterCount > 0) {
if (isQueryRunning()) {
String message= SearchMessages.getString("JavaSearchResultPage.filtered.message"); //$NON-NLS-1$
return MessageFormat.format(message, new Object[] { label });
} else {
String message= SearchMessages.getString("JavaSearchResultPage.filteredWithCount.message"); //$NON-NLS-1$
return MessageFormat.format(message, new Object[] { label, new Integer(getFilteredMatchCount()) });
}
}
return label;
}
private int getMatchFiltersCount() {
MatchFilter[] filters= getMatchFilters();
AbstractTextSearchResult result= getInput();
if (result == null)
return 0;
int filterCount= 0;
for (int i= 0; i < filters.length; i++) {
if (filters[i].isApplicable((JavaSearchQuery) result.getQuery()))
filterCount++;
}
return filterCount;
}
private int getFilteredMatchCount() {
AbstractTextSearchResult result= getInput();
if (result == null)
return 0;
Object[] elements= result.getElements();
int count= 0;
for (int i= 0; i < elements.length; i++) {
count+= getDisplayedMatchCount(elements[i]);
}
return count;
}
/* (non-Javadoc)
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter(Class adapter) {
if (IShowInTargetList.class.equals(adapter)) {
return SHOW_IN_TARGET_LIST;
}
return null;
}
}
|
54,459
|
Bug 54459 New search view: Double click on type should open CU [search]
|
20040311 in the new search results view, I happen to have to click a lot to expand the trees so I can finally double click the method element to open the editor. What I always expect is that doouble clicking the type opens the editor and I'm always irritated that it doesn't, propably because in all other views (package explorer, hierarchy, outline) this is the case. is there a good reason why not offering this short cut?
|
resolved fixed
|
fc556e8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T12:34:06Z
| 2004-03-11T13:00:00Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/NewSearchViewActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.actions.ActionGroup;
class NewSearchViewActionGroup extends CompositeActionGroup {
public NewSearchViewActionGroup(IViewPart part) {
Assert.isNotNull(part);
setGroups(new ActionGroup[] {
new JavaSearchActionGroup(part),
new NavigateActionGroup(part)});
}
}
|
52,064
|
Bug 52064 Content assist in "New Class" Dialog shows interfaces
|
Content Assist is available for the superclass in M7. However it also lists interfaces. If an interface is selected, the generated class "extends" it instead of "implementing" it.
|
resolved fixed
|
7c1795f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T14:00:54Z
| 2004-02-14T20:20:00Z
|
org.eclipse.jdt.ui/ui
| |
52,064
|
Bug 52064 Content assist in "New Class" Dialog shows interfaces
|
Content Assist is available for the superclass in M7. However it also lists interfaces. If an interface is selected, the generated class "extends" it instead of "implementing" it.
|
resolved fixed
|
7c1795f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T14:00:54Z
| 2004-02-14T20:20:00Z
|
refactoring/org/eclipse/jdt/internal/ui/refactoring/contentassist/CUPositionCompletionProcessor.java
| |
52,064
|
Bug 52064 Content assist in "New Class" Dialog shows interfaces
|
Content Assist is available for the superclass in M7. However it also lists interfaces. If an interface is selected, the generated class "extends" it instead of "implementing" it.
|
resolved fixed
|
7c1795f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T14:00:54Z
| 2004-02-14T20:20:00Z
|
org.eclipse.jdt.ui/ui
| |
52,064
|
Bug 52064 Content assist in "New Class" Dialog shows interfaces
|
Content Assist is available for the superclass in M7. However it also lists interfaces. If an interface is selected, the generated class "extends" it instead of "implementing" it.
|
resolved fixed
|
7c1795f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T14:00:54Z
| 2004-02-14T20:20:00Z
|
refactoring/org/eclipse/jdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java
| |
52,064
|
Bug 52064 Content assist in "New Class" Dialog shows interfaces
|
Content Assist is available for the superclass in M7. However it also lists interfaces. If an interface is selected, the generated class "extends" it instead of "implementing" it.
|
resolved fixed
|
7c1795f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T14:00:54Z
| 2004-02-14T20:20:00Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.templates.Template;
import org.eclipse.jface.text.templates.TemplateException;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.core.*;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.formatter.CodeFormatter;
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.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.PreferenceConstants;
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.dom.TokenScanner;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIStatus;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.ControlContentAssistHelper;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaPackageCompletionProcessor;
import org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.*;
/**
* The class <code>NewTypeWizardPage</code> contains controls and validation routines
* for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
* Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
* is intended to serve as base class of all wizards that create types like applets, servlets, classes,
* interfaces, etc.
* <p>
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of <code>NewTypeWizardPage</code>.
* </p>
*
* @see org.eclipse.jdt.ui.wizards.NewClassWizardPage
* @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage
*
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
/**
* Class used in stub creation routines to add needed imports to a
* compilation unit.
*/
public static class ImportsManager {
private ImportsStructure fImportsStructure;
private HashSet fAddedTypes;
/* package */ ImportsManager(IImportsStructure importsStructure) {
fImportsStructure= (ImportsStructure) importsStructure;
}
/* package */ ImportsManager(ICompilationUnit createdWorkingCopy) throws CoreException {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
fAddedTypes= new HashSet();
fImportsStructure= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, true);
}
/* package */ ImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
fAddedTypes.add(qualifiedTypeName);
return fImportsStructure.addImport(qualifiedTypeName);
}
/* package */ void create(boolean needsSave, SubProgressMonitor monitor) throws CoreException {
fImportsStructure.create(needsSave, monitor);
}
/* package */ void removeImport(String qualifiedName) {
if (fAddedTypes.contains(qualifiedName)) {
fImportsStructure.removeImport(qualifiedName);
}
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the enclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier check boxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs check boxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
private JavaPackageCompletionProcessor fCurrPackageCompletionProcessor;
private JavaTypeCompletionProcessor fEnclosingTypeCompletionProcessor;
private JavaTypeCompletionProcessor fSuperClassCompletionProcessor;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1, STATIC_INDEX= 2;
/**
* Creates a new <code>NewTypeWizardPage</code>
*
* @param isClass <code>true</code> if a new class is to be created; otherwise
* an interface is to be created
* @param pageName the wizard page's name
*/
public NewTypeWizardPage(boolean isClass, String pageName) {
super(pageName);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
} else {
buttonNames2= new String[] {};
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(STATIC_INDEX, false);
fCurrPackageCompletionProcessor= new JavaPackageCompletionProcessor();
fEnclosingTypeCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fSuperClassCompletionProcessor= new JavaTypeCompletionProcessor(false, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to initialize this page or <code>
* null</code> if no selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= cu.findPrimaryType();
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// ignore this exception now
}
}
String typeName= ""; //$NON-NLS-1$
ITextSelection selection= getCurrentTextSelection();
if (selection != null) {
String text= selection.getText();
if (JavaConventions.validateJavaTypeName(text).isOK()) {
typeName= text;
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName(typeName, true);
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
Text text= fPackageDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(text);
ControlContentAssistHelper.createTextContentAssistant(text, fCurrPackageCompletionProcessor);
}
/**
* Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Text text= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
text.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeightHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
ControlContentAssistHelper.createTextContentAssistant(text, fEnclosingTypeCompletionProcessor);
}
/**
* Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
* least 2 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/checkbox buttons. Expects a
* <code>GridLayout</code> with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
if (fIsClass) {
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
* with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
Text text= fSuperClassDialogField.getTextControl(null);
LayoutUtil.setWidthHint(text, getMaxFieldWidth());
ControlContentAssistHelper.createTextContentAssistant(text, fSuperClassCompletionProcessor);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
* at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name input field.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependent
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(STATIC_INDEX)) {
fOtherMdfButtons.setSelection(STATIC_INDEX, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType);
fOtherMdfButtons.enableSelectionButton(STATIC_INDEX, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons || field == fAccMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Returns the text of the package input field.
*
* @return the text of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Returns the text of the enclosing type input field.
*
* @return the text of the enclosing type input field
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
*
* @return a package fragment or <code>null</code> if the input
* could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment to the given value. The method updates the model
* and the text of the control.
*
* @param pack the package fragment to be set
* @param canBeModified if <code>true</code> the package fragment is
* editable; otherwise it is read-only.
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the enclosing type corresponding to the current input.
*
* @return the enclosing type or <code>null</code> if the enclosing type is
* not selected or the input could not be resolved
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the enclosing type. The method updates the underlying model
* and the text of the control.
*
* @param type the enclosing type
* @param canBeModified if <code>true</code> the enclosing type field is
* editable; otherwise it is read-only.
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns the selection state of the enclosing type checkbox.
*
* @return the selection state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <code>true</code> the enclosing type checkbox is
* modifiable; otherwise it is read-only.
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Returns the type name entered into the type input field.
*
* @return the type name
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name input field's text to the given value. Method doesn't update
* the model.
*
* @param name the new type name
* @param canBeModified if <code>true</code> the enclosing type name field is
* editable; otherwise it is read-only.
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Returns the selected modifiers.
*
* @return the selected modifiers
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= F_PUBLIC;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= F_PRIVATE;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= F_PROTECTED;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(STATIC_INDEX)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
* <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
* or <code>F_STATIC</code> or, a valid combination.
* @param canBeModified if <code>true</code> the modifier fields are
* editable; otherwise they are read-only
* @see Flags
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(STATIC_INDEX, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <code>true</code> the superclass name field is
* editable; otherwise it is read-only.
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Returns the chosen super interfaces.
*
* @return a list of chosen super interfaces. The list's elements
* are of type <code>String</code>
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
*
* @param interfacesNames a list of super interface. The method requires that
* the list's elements are of type <code>String</code>
* @param canBeModified if <code>true</code> the super interface field is
* editable; otherwise it is read-only.
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
/**
* Returns the resource handle that corresponds to the compilation unit to was or
* will be created or modified.
* @return A resource or null if the page contains illegal values.
* @since 3.0
*/
public IResource getModifiedResource() {
IType enclosing= getEnclosingType();
if (enclosing != null) {
return enclosing.getResource();
}
IPackageFragment pack= getPackageFragment();
if (pack != null) {
return pack.getCompilationUnit(getTypeName() + ".java").getResource(); //$NON-NLS-1$
}
return null;
}
// ----------- validation ----------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#containerChanged()
*/
protected IStatus containerChanged() {
IStatus status= super.containerChanged();
fCurrPackageCompletionProcessor.setPackageFragmentRoot(getPackageFragmentRoot());
if (getPackageFragmentRoot() != null)
fEnclosingTypeCompletionProcessor.setPackageFragment(getPackageFragmentRoot().getPackageFragment("")); //$NON-NLS-1$
return status;
}
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
} else {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.DefaultPackageDiscouraged")); //$NON-NLS-1$
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, don't allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
fSuperClassCompletionProcessor.setPackageFragment(fCurrPackage);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= findType(root.getJavaProject(), enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
if (!enclosingRoot.equals(root)) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$
}
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e);
return status;
}
}
/**
* Hook method that gets called when the type name has changed. The method validates the
* type name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
IResource resource= cu.getResource();
if (resource.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
IPath location= resource.getLocation();
if (location != null && location.toFile().exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExistsDifferentCase")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e);
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
if (!jproject.exists()) {
return null;
}
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= jproject.findType(res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= jproject.findType(packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(sclassName);
}
}
return type;
}
private IType findType(IJavaProject project, String typeName) throws JavaModelException {
if (project.exists()) {
return project.findType(typeName);
}
return null;
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the super interfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= findType(root.getJavaProject(), intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Hook method that gets called when the modifiers have changed. The method validates
* the modifiers and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
IPackageFragment pack= getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == Window.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$
dialog.setFilter(getSuperClass());
if (dialog.open() == Window.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates the new type using the entered field values.
*
* @param monitor a progress monitor to report progress.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
ICompilationUnit createdWorkingCopy= null;
try {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= getTypeName();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsManager imports;
int indent= 0;
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
// create a working copy with a new owner
createdWorkingCopy= parentCU.getWorkingCopy(null);
// use the compiler template a first time to read the imports
String content= CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$
if (content != null) {
createdWorkingCopy.getBuffer().setContents(content);
}
imports= new ImportsManager(createdWorkingCopy);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(JavaModelUtil.concatenateName(pack.getElementName(), getTypeName()));
String typeContent= constructTypeStub(imports, lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsManager(parentCU);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
String comment= getTypeComment(parentCU, lineDelimiter);
if (comment != null) {
content.append(comment);
content.append(lineDelimiter);
}
}
content.append(constructTypeStub(imports, lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
if (monitor.isCanceled()) {
throw new InterruptedException();
}
// add imports for superclass/interfaces, so types can be resolved correctly
ICompilationUnit cu= createdType.getCompilationUnit();
boolean needsSave= !cu.isWorkingCopy();
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
JavaModelUtil.reconcile(cu);
if (monitor.isCanceled()) {
throw new InterruptedException();
}
// set up again
imports= new ImportsManager(imports.getImportsStructure().getCompilationUnit());
createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
// add imports
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
removeUnusedImports(cu, needsSave);
JavaModelUtil.reconcile(cu);
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, pack.getJavaProject());
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commitWorkingCopy(false, new SubProgressMonitor(monitor, 1));
} else {
if (needsSave) {
buf.save(null, false);
}
monitor.worked(1);
}
if (createdWorkingCopy != null) {
fCreatedType= (IType) createdType.getPrimaryElement();
} else {
fCreatedType= createdType;
}
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.discardWorkingCopy();
}
monitor.done();
}
}
private void removeUnusedImports(ICompilationUnit cu, boolean needsSave) throws CoreException {
ASTParser parser= ASTParser.newParser(AST.JLS2);
parser.setSource(cu);
parser.setResolveBindings(true);
CompilationUnit root= (CompilationUnit) parser.createAST(null);
IProblem[] problems= root.getProblems();
ArrayList res= new ArrayList();
for (int i= 0; i < problems.length; i++) {
if (problems[i].getID() == IProblem.UnusedImport) {
String imp= problems[i].getArguments()[0];
res.add(imp);
}
}
if (!res.isEmpty()) {
ImportsManager imports= new ImportsManager(cu);
for (int i= 0; i < res.size(); i++) {
String curr= (String) res.get(i);
imports.removeImport(curr);
}
imports.create(needsSave, null);
}
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
* @since 2.1
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
String typeComment= getTypeComment(cu, lineDelimiter);
IPackageFragment pack= (IPackageFragment) cu.getParent();
String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter);
if (content != null) {
ASTParser parser= ASTParser.newParser(AST.JLS2);
parser.setSource(content.toCharArray());
CompilationUnit unit= (CompilationUnit) parser.createAST(null);
if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
return content;
}
}
StringBuffer buf= new StringBuffer();
if (!pack.isDefaultPackage()) {
buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
}
buf.append(lineDelimiter).append(lineDelimiter);
if (typeComment != null) {
buf.append(typeComment).append(lineDelimiter);
}
buf.append(typeContent);
return buf.toString();
}
/**
* Returns the created type. The method only returns a valid type
* after <code>createType</code> has been called.
*
* @return the created type
* @see #createType(IProgressMonitor)
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct CU body----------------
private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
buf.append(imports.addImport(qualifiedName));
}
}
private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
buf.append(imports.addImport(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(ImportsManager imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append('{');
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* Hook method that gets called from <code>createType</code> to support adding of
* unanticipated methods, fields, and inner types to the created type.
* <p>
* Implementers can use any methods defined on <code>IType</code> to manipulate the
* new type.
* </p>
* <p>
* The source code of the new type will be formatted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </p>
*
* @param newType the new type created via <code>createType</code>
* @param imports an import manager which can be used to add new imports
* @param monitor a progress monitor to report progress. Must not be <code>null</code>
*
* @see #createType(IProgressMonitor)
*/
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
// call for compatibility
createTypeMembers(newType, imports.getImportsStructure(), monitor);
// default implementation does nothing
// example would be
// String mainMathod= "public void foo(Vector vec) {}"
// createdType.createMethod(main, null, false, null);
// imports.addImport("java.lang.Vector");
}
/**
* @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
//deprecated
if (false) {
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, null));
}
}
/**
* @deprecated Instead of file templates, the new type code template
* specifies the stub for a compilation unit.
*/
protected String getFileComment(ICompilationUnit parentCU) {
return null;
}
private boolean isValidComment(String template) {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(template.toCharArray());
try {
int next= scanner.getNextToken();
while (TokenScanner.isComment(next)) {
next= scanner.getNextToken();
}
return next == ITerminalSymbols.TokenNameEOF;
} catch (InvalidInputException e) {
}
return false;
}
/**
* Hook method that gets called from <code>createType</code> to retrieve
* a type comment. This default implementation returns the content of the
* 'type comment' template.
*
* @return the type comment or <code>null</code> if a type comment
* is not desired
*
* @since 3.0
*/
protected String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) {
try {
StringBuffer typeName= new StringBuffer();
if (isEnclosingTypeSelected()) {
typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.');
}
typeName.append(getTypeName());
String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), lineDelimiter);
if (comment != null && isValidComment(comment)) {
return comment;
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use getTypeComment(ICompilationUnit, String)
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) {
return getTypeComment(parentCU, String.valueOf('\n'));
}
return null;
}
/**
* @deprecated Use getTemplate(String,ICompilationUnit,int)
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
return getTemplate(name, parentCU, 0);
}
/**
* Returns the string resulting from evaluation the given template in
* the context of the given compilation unit. This accesses the normal
* template page, not the code templates. To use code templates use
* <code>constructCUContent</code> to construct a compilation unit stub or
* getTypeComment for the comment of the type.
*
* @param name the template to be evaluated
* @param parentCU the templates evaluation context
* @param pos a source offset into the parent compilation unit. The
* template is evaluated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template template= JavaPlugin.getDefault().getTemplateStore().findTemplate(name);
if (template != null) {
return JavaContext.evaluateTemplate(template, parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (TemplateException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
* needed method and constructors.
*
* @param type the type for which the new methods and constructor are to be created
* @param doConstructors if <code>true</code> unimplemented constructors are created
* @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
* @param imports an import manager to add all needed import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= null;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
hierarchy= type.newSupertypeHierarchy(monitor);
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
if (hierarchy == null) {
hierarchy= type.newSupertypeHierarchy(monitor);
}
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, OK to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
/**
* @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor)
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor);
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
59,832
|
Bug 59832 Bindings.findMethodDefininition(binding) finds wrong definition
|
I20040422 0800 1) Enabled annotation roll-overs 2) Create the following type: package p1; public class A { void doit() { } } 3) Create a subclass in a different package: package p2; import p1.A; public class B extends A { void doit() { // } } I get two roll-overs in the editor next to B.doit: - "The method B.doit() does not override the inherited method from A since it is private to a different package" - "overrides P1.A.doit" These statements contradict eath other.
|
resolved fixed
|
4bb7340
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T16:07:59Z
| 2004-04-23T19:53:20Z
|
org.eclipse.jdt.ui/core
| |
59,832
|
Bug 59832 Bindings.findMethodDefininition(binding) finds wrong definition
|
I20040422 0800 1) Enabled annotation roll-overs 2) Create the following type: package p1; public class A { void doit() { } } 3) Create a subclass in a different package: package p2; import p1.A; public class B extends A { void doit() { // } } I get two roll-overs in the editor next to B.doit: - "The method B.doit() does not override the inherited method from A since it is private to a different package" - "overrides P1.A.doit" These statements contradict eath other.
|
resolved fixed
|
4bb7340
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T16:07:59Z
| 2004-04-23T19:53:20Z
|
extension/org/eclipse/jdt/internal/corext/dom/Bindings.java
| |
59,832
|
Bug 59832 Bindings.findMethodDefininition(binding) finds wrong definition
|
I20040422 0800 1) Enabled annotation roll-overs 2) Create the following type: package p1; public class A { void doit() { } } 3) Create a subclass in a different package: package p2; import p1.A; public class B extends A { void doit() { // } } I get two roll-overs in the editor next to B.doit: - "The method B.doit() does not override the inherited method from A since it is private to a different package" - "overrides P1.A.doit" These statements contradict eath other.
|
resolved fixed
|
4bb7340
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T16:07:59Z
| 2004-04-23T19:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/OverrideIndicatorManager.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.ui.PartInitException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
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.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener;
/**
* Manages the override and overwrite indicators for
* the given Java element and annotation model.
*
* @since 3.0
*/
class OverrideIndicatorManager implements IJavaReconcilingListener {
/**
* Overwrite and override indicator annotation.
*
* @since 3.0
*/
class OverrideIndicator extends Annotation {
private boolean fIsOverwriteIndicator;
private String fAstNodeKey;
/**
* Creates a new override annotation.
*
* @param isOverwriteIndicator <code>true</code> if this annotation is
* an overwrite indicator, <code>false</code> otherwise
* @param text the text associated with this annotation
* @param key the method binding key
* @since 3.0
*/
OverrideIndicator(boolean isOverwriteIndicator, String text, String key) {
super(ANNOTATION_TYPE, false, text);
fIsOverwriteIndicator= isOverwriteIndicator;
fAstNodeKey= key;
}
/**
* Tells whether this is an overwrite or an override indicator.
*
* @return <code>true</code> if this is an overwrite indicator
*/
public boolean isOverwriteIndicator() {
return fIsOverwriteIndicator;
}
/**
* Opens and reveals the defining method.
*/
public void open() {
boolean hasLogEntry= false;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(fJavaElement, true, null);
ASTNode node= null;
if (ast != null)
node= ast.findDeclaringNode(fAstNodeKey);
if (node instanceof MethodDeclaration) {
try {
IMethodBinding methodBinding= ((MethodDeclaration)node).resolveBinding();
IMethodBinding definingMethodBinding= Bindings.findMethodDefininition(methodBinding);
if (definingMethodBinding != null) {
String definingTypeQualifiedName= definingMethodBinding.getDeclaringClass().getQualifiedName();
IType definingType= null;
IType type= getType(methodBinding);
if (type != null) {
ITypeHierarchy th= SuperTypeHierarchyCache.getTypeHierarchy(type);
IType[] superTypes= th.getAllSupertypes(type);
definingType= findType(superTypes, definingTypeQualifiedName);
} else {
definingType= JavaModelUtil.findType(fJavaElement.getJavaProject(), definingTypeQualifiedName);
}
if (definingType != null) {
IMethod definingMethod= Bindings.findMethod(definingMethodBinding, definingType);
if (definingMethod != null) {
OpenActionUtil.open(definingMethod, true);
return;
}
}
}
} catch (JavaModelException ex) {
JavaPlugin.log(ex.getStatus());
hasLogEntry= true;
} catch (PartInitException ex) {
JavaPlugin.log(ex.getStatus());
hasLogEntry= true;
}
}
String title= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.title"); //$NON-NLS-1$
String message;
if (hasLogEntry)
message= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.messageHasLogEntry"); //$NON-NLS-1$
else
message= JavaEditorMessages.getString("OverrideIndicatorManager.open.error.message"); //$NON-NLS-1$
MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
private IType getType(IMethodBinding methodBinding) throws JavaModelException {
if (methodBinding == null)
return null;
int type= fJavaElement.getElementType();
IType[] types= null;
if (type == IJavaElement.COMPILATION_UNIT)
types= ((ICompilationUnit)fJavaElement).getAllTypes();
else if (type == IJavaElement.CLASS_FILE)
types= new IType[] { ((IClassFile)fJavaElement).getType() };
return findType(types, methodBinding.getDeclaringClass().getQualifiedName());
}
private IType findType(IType[] types, String fullyQualifiedName) throws JavaModelException {
if (types == null)
return null;
for (int i= 0; i < types.length; i++) {
IType type= types[i];
if (JavaModelUtil.getFullyQualifiedName(type).equals(fullyQualifiedName))
return type;
}
return null;
}
}
static final String ANNOTATION_TYPE= "org.eclipse.jdt.ui.overrideIndicator"; //$NON-NLS-1$
private IAnnotationModel fAnnotationModel;
private Object fAnnotationModelLockObject;
private Annotation[] fOverrideAnnotations;
private IJavaElement fJavaElement;
public OverrideIndicatorManager(IAnnotationModel annotationModel, IJavaElement javaElement, CompilationUnit ast) {
Assert.isNotNull(annotationModel);
Assert.isNotNull(javaElement);
fJavaElement= javaElement;
fAnnotationModel=annotationModel;
fAnnotationModelLockObject= getLockObject(fAnnotationModel);
updateAnnotations(ast, new NullProgressMonitor());
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the override and implements annotations based
* on the given AST.
*
* @param ast the compilation unit AST
* @param progressMonitor the progress monitor
* @since 3.0
*/
protected void updateAnnotations(CompilationUnit ast, IProgressMonitor progressMonitor) {
if (ast == null || progressMonitor.isCanceled())
return;
final Map annotationMap= new HashMap(50);
ast.accept(new ASTVisitor(false) {
/*
* @see org.eclipse.jdt.core.dom.ASTVisitor#visit(org.eclipse.jdt.core.dom.MethodDeclaration)
*/
public boolean visit(MethodDeclaration node) {
IMethodBinding binding= node.resolveBinding();
if (binding != null) {
IMethodBinding definingMethod= Bindings.findMethodDefininition(binding);
if (definingMethod != null) {
ITypeBinding definingType= definingMethod.getDeclaringClass();
String qualifiedMethodName= definingType.getQualifiedName() + "." + binding.getName(); //$NON-NLS-1$
boolean isOverwriteIndicator= definingType.isInterface();
String text;
if (isOverwriteIndicator)
text= JavaEditorMessages.getFormattedString("OverrideIndicatorManager.implements", qualifiedMethodName); //$NON-NLS-1$
else
text= JavaEditorMessages.getFormattedString("OverrideIndicatorManager.overrides", qualifiedMethodName); //$NON-NLS-1$
SimpleName name= node.getName();
Position position= new Position(name.getStartPosition(), name.getLength());
annotationMap.put(
new OverrideIndicator(isOverwriteIndicator, text, binding.getKey()), //$NON-NLS-1$
position);
}
}
return false;
}
});
if (progressMonitor.isCanceled())
return;
synchronized (fAnnotationModelLockObject) {
if (fAnnotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, annotationMap);
} else {
removeAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
fAnnotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOverrideAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
}
/**
* Removes all override indicators from this manager's annotation model.
*/
void removeAnnotations() {
if (fOverrideAnnotations == null)
return;
synchronized (fAnnotationModelLockObject) {
if (fAnnotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)fAnnotationModel).replaceAnnotations(fOverrideAnnotations, null);
} else {
for (int i= 0, length= fOverrideAnnotations.length; i < length; i++)
fAnnotationModel.removeAnnotation(fOverrideAnnotations[i]);
}
fOverrideAnnotations= null;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#aboutToBeReconciled()
*/
public void aboutToBeReconciled() {
}
/*
* @see org.eclipse.jdt.internal.ui.text.java.IJavaReconcilingListener#reconciled(CompilationUnit, boolean, IProgressMonitor)
*/
public void reconciled(CompilationUnit ast, boolean forced, IProgressMonitor progressMonitor) {
updateAnnotations(ast, progressMonitor);
}
}
|
59,832
|
Bug 59832 Bindings.findMethodDefininition(binding) finds wrong definition
|
I20040422 0800 1) Enabled annotation roll-overs 2) Create the following type: package p1; public class A { void doit() { } } 3) Create a subclass in a different package: package p2; import p1.A; public class B extends A { void doit() { // } } I get two roll-overs in the editor next to B.doit: - "The method B.doit() does not override the inherited method from A since it is private to a different package" - "overrides P1.A.doit" These statements contradict eath other.
|
resolved fixed
|
4bb7340
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T16:07:59Z
| 2004-04-23T19:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ModifierCorrectionSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Collection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.Assert;
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.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
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 final int TO_NON_FINAL= 5;
public static void addNonAccessibleReferenceProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int kind, int relevance) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
IBinding binding=null;
switch (selectedNode.getNodeType()) {
case ASTNode.SIMPLE_NAME:
binding= ((SimpleName) selectedNode).resolveBinding();
break;
case ASTNode.QUALIFIED_NAME:
binding= ((QualifiedName) selectedNode).resolveBinding();
break;
case ASTNode.SIMPLE_TYPE:
binding= ((SimpleType) selectedNode).resolveBinding();
break;
case ASTNode.METHOD_INVOCATION:
binding= ((MethodInvocation) selectedNode).getName().resolveBinding();
break;
case ASTNode.SUPER_METHOD_INVOCATION:
binding= ((SuperMethodInvocation) selectedNode).getName().resolveBinding();
break;
case ASTNode.FIELD_ACCESS:
binding= ((FieldAccess) selectedNode).getName().resolveBinding();
break;
case ASTNode.SUPER_FIELD_ACCESS:
binding= ((SuperFieldAccess) selectedNode).getName().resolveBinding();
break;
case ASTNode.CLASS_INSTANCE_CREATION:
binding= ((ClassInstanceCreation) selectedNode).resolveConstructorBinding();
break;
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
binding= ((SuperConstructorInvocation) selectedNode).resolveConstructorBinding();
break;
default:
return;
}
ITypeBinding typeBinding= null;
String name;
boolean isLocalVar= false;
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();
isLocalVar= !((IVariableBinding) binding).isField();
} else if (binding instanceof ITypeBinding) {
typeBinding= (ITypeBinding) binding;
name= binding.getName();
} else {
return;
}
if (typeBinding != null && typeBinding.isFromSource() || isLocalVar) {
int includedModifiers= 0;
int excludedModifiers= 0;
String label;
switch (kind) {
case TO_VISIBLE:
excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
includedModifiers= getNeededVisibility(selectedNode, typeBinding);
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changevisibility.description", new String[] { name, getVisibilityString(includedModifiers) }); //$NON-NLS-1$
break;
case TO_STATIC:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertostatic.description", name); //$NON-NLS-1$
includedModifiers= Modifier.STATIC;
break;
case TO_NON_STATIC:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertononstatic.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.STATIC;
break;
case TO_NON_PRIVATE:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertodefault.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.PRIVATE;
break;
case TO_NON_FINAL:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemodifiertononfinal.description", name); //$NON-NLS-1$
excludedModifiers= Modifier.FINAL;
break;
default:
Assert.isTrue(false, "not supported"); //$NON-NLS-1$
return;
}
ICompilationUnit targetCU= isLocalVar ? cu : ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), typeBinding);
if (targetCU != null) {
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
proposals.add(new ModifierChangeCompletionProposal(label, targetCU, binding, selectedNode, includedModifiers, excludedModifiers, relevance, image));
}
}
if (kind == TO_VISIBLE && binding.getKind() == IBinding.VARIABLE && Modifier.isPrivate(binding.getModifiers())) {
if (selectedNode instanceof SimpleName || selectedNode instanceof FieldAccess && ((FieldAccess) selectedNode).getExpression() instanceof ThisExpression) {
UnresolvedElementsSubProcessor.getVariableProposals(context, problem, proposals);
}
}
}
public static void addChangeOverriddenModfierProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int kind) throws JavaModelException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
IMethodBinding method= ((MethodDeclaration) selectedNode).resolveBinding();
ITypeBinding curr= method.getDeclaringClass();
IMethodBinding overriddenClass= null;
if (overriddenClass == null && curr.getSuperclass() != null) {
curr= curr.getSuperclass();
overriddenClass= Bindings.findMethodInType(curr, method.getName(), method.getParameterTypes());
}
if (overriddenClass != null) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, context.getASTRoot(), curr);
if (targetCU != null) {
String methodName= curr.getName() + '.' + overriddenClass.getName();
String label;
int excludedModifiers;
int includedModifiers;
switch (kind) {
case TO_VISIBLE:
excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
includedModifiers= method.getModifiers() & (Modifier.PROTECTED | Modifier.PUBLIC);
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changeoverriddenvisibility.description", new String[] { methodName, getVisibilityString(includedModifiers) }); //$NON-NLS-1$
break;
case TO_NON_FINAL:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemethodtononfinal.description", methodName); //$NON-NLS-1$
excludedModifiers= Modifier.FINAL;
includedModifiers= 0;
break;
case TO_NON_STATIC:
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemethodtononstatic.description", methodName); //$NON-NLS-1$
excludedModifiers= Modifier.STATIC;
includedModifiers= 0;
break;
default:
Assert.isTrue(false, "not supported"); //$NON-NLS-1$
return;
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
proposals.add(new ModifierChangeCompletionProposal(label, targetCU, overriddenClass, selectedNode, includedModifiers, excludedModifiers, 9, image));
}
}
if (kind == TO_VISIBLE && problem.getProblemId() != IProblem.OverridingNonVisibleMethod) {
IMethodBinding defining= Bindings.findMethodDefininition(method);
if (defining != null) {
int excludedModifiers= Modifier.PRIVATE | Modifier.PROTECTED | Modifier.PUBLIC;
int includedModifiers= defining.getModifiers() & (Modifier.PROTECTED | Modifier.PUBLIC);
String label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemethodvisibility.description", new String[] { getVisibilityString(includedModifiers) }); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
proposals.add(new ModifierChangeCompletionProposal(label, cu, method, selectedNode, includedModifiers, excludedModifiers, 8, image));
}
}
}
public static void addNonFinalLocalProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
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, 5, image));
}
}
public static void addRemoveInvalidModfiersProposal(IInvocationContext context, IProblemLocation problem, Collection proposals, int relevance) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof MethodDeclaration) {
selectedNode= ((MethodDeclaration) selectedNode).getName();
}
if (!(selectedNode instanceof SimpleName)) {
return;
}
IBinding binding= ((SimpleName) selectedNode).resolveBinding();
if (binding != null) {
String methodName= binding.getName();
String label;
if (problem.getProblemId() == IProblem.CannotHideAnInstanceMethodWithAStaticMethod) {
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.changemethodtononstatic.description", methodName); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("ModifierCorrectionSubProcessor.removeinvalidmodifiers.description", methodName); //$NON-NLS-1$
}
int excludedModifiers= 0;
int includedModifiers= 0;
switch (problem.getProblemId()) {
case IProblem.CannotHideAnInstanceMethodWithAStaticMethod:
excludedModifiers= Modifier.STATIC;
break;
case IProblem.IllegalModifierForInterfaceMethod:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.ABSTRACT);
break;
case IProblem.IllegalModifierForInterface:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.ABSTRACT | Modifier.STRICTFP);
break;
case IProblem.IllegalModifierForClass:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.ABSTRACT | Modifier.FINAL | Modifier.STRICTFP);
break;
case IProblem.IllegalModifierForInterfaceField:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.ABSTRACT | Modifier.FINAL);
break;
case IProblem.IllegalModifierForMemberInterface:
case IProblem.IllegalVisibilityModifierForInterfaceMemberType:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.STATIC | Modifier.STRICTFP);
break;
case IProblem.IllegalModifierForMemberClass:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.ABSTRACT | Modifier.FINAL | Modifier.STRICTFP);
break;
case IProblem.IllegalModifierForLocalClass:
excludedModifiers= ~(Modifier.ABSTRACT | Modifier.FINAL | Modifier.STRICTFP);
break;
case IProblem.IllegalModifierForArgument:
excludedModifiers= ~Modifier.FINAL;
break;
case IProblem.IllegalModifierForField:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL | Modifier.VOLATILE | Modifier.TRANSIENT);
break;
case IProblem.IllegalModifierForMethod:
excludedModifiers= ~(Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE | Modifier.STATIC | Modifier.ABSTRACT | Modifier.FINAL | Modifier.NATIVE | Modifier.STRICTFP);
break;
case IProblem.IllegalModifierForVariable:
excludedModifiers= ~Modifier.FINAL;
break;
default:
Assert.isTrue(false, "not supported"); //$NON-NLS-1$
return;
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
proposals.add(new ModifierChangeCompletionProposal(label, cu, binding, selectedNode, includedModifiers, excludedModifiers, relevance, 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= Bindings.getBindingOfParentType(currNode);
if (currNodeBinding == null) { // import
return Modifier.PUBLIC;
}
if (Bindings.isSuperType(targetType, currNodeBinding)) {
return Modifier.PROTECTED;
}
if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
return 0;
}
return Modifier.PUBLIC;
}
public static void addAbstractMethodProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
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 (problem.getProblemId() == IProblem.AbstractMethodInAbstractClass || parentIsAbstractClass) {
AST ast= astRoot.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
int newModifiers= decl.getModifiers() & ~Modifier.ABSTRACT;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
if (hasNoBody) {
Block newBody= ast.newBlock();
rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, newBody, null);
Expression expr= ASTNodeFactory.newDefaultExpression(ast, 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, 6, image);
proposals.add(proposal);
}
if (!hasNoBody && problem.getProblemId() == IProblem.BodyForAbstractMethod) {
ASTRewrite rewrite= ASTRewrite.create(decl.getAST());
rewrite.remove(decl.getBody(), null);
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.removebody.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal2= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
proposals.add(proposal2);
}
if (problem.getProblemId() == IProblem.AbstractMethodInAbstractClass && (parentTypeDecl != null)) {
ASTRewriteCorrectionProposal proposal= getMakeTypeAbstractProposal(cu, parentTypeDecl, 5);
proposals.add(proposal);
}
}
public static void addNativeMethodProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
MethodDeclaration decl;
if (selectedNode instanceof SimpleName) {
decl= (MethodDeclaration) selectedNode.getParent();
} else if (selectedNode instanceof MethodDeclaration) {
decl= (MethodDeclaration) selectedNode;
} else {
return;
}
{
AST ast= astRoot.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
int newModifiers= decl.getModifiers() & ~Modifier.NATIVE;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
Block newBody= ast.newBlock();
rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, newBody, null);
Expression expr= ASTNodeFactory.newDefaultExpression(ast, 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, 6, image);
proposals.add(proposal);
}
if (decl.getBody() != null) {
ASTRewrite rewrite= ASTRewrite.create(decl.getAST());
rewrite.remove(decl.getBody(), null);
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, 5, image);
proposals.add(proposal2);
}
}
public static ASTRewriteCorrectionProposal getMakeTypeAbstractProposal(ICompilationUnit cu, TypeDeclaration typeDeclaration, int relevance) {
ASTRewrite rewrite= ASTRewrite.create(typeDeclaration.getAST());
int newModifiers= typeDeclaration.getModifiers() | Modifier.ABSTRACT;
rewrite.set(typeDeclaration, TypeDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
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, relevance, image);
return proposal;
}
public static void addMethodRequiresBodyProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
AST ast= context.getASTRoot().getAST();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
MethodDeclaration decl= (MethodDeclaration) selectedNode;
{
ASTRewrite rewrite= ASTRewrite.create(ast);
int newModifiers= decl.getModifiers() & ~Modifier.ABSTRACT;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
Block body= ast.newBlock();
rewrite.set(decl, MethodDeclaration.BODY_PROPERTY, body, null);
Type returnType= decl.getReturnType();
if (!decl.isConstructor()) {
Expression expression= ASTNodeFactory.newDefaultExpression(ast, returnType, decl.getExtraDimensions());
if (expression != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expression);
body.statements().add(returnStatement);
}
}
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.addmissingbody.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 9, image);
proposals.add(proposal);
}
{
ASTRewrite rewrite= ASTRewrite.create(ast);
int newModifiers= decl.getModifiers() | Modifier.ABSTRACT;
rewrite.set(decl, MethodDeclaration.MODIFIERS_PROPERTY, new Integer(newModifiers), null);
String label= CorrectionMessages.getString("ModifierCorrectionSubProcessor.setmethodabstract.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
proposals.add(proposal);
}
}
public static void addNeedToEmulateProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
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, 5, image));
}
}
}
|
59,832
|
Bug 59832 Bindings.findMethodDefininition(binding) finds wrong definition
|
I20040422 0800 1) Enabled annotation roll-overs 2) Create the following type: package p1; public class A { void doit() { } } 3) Create a subclass in a different package: package p2; import p1.A; public class B extends A { void doit() { // } } I get two roll-overs in the editor next to B.doit: - "The method B.doit() does not override the inherited method from A since it is private to a different package" - "overrides P1.A.doit" These statements contradict eath other.
|
resolved fixed
|
4bb7340
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T16:07:59Z
| 2004-04-23T19:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/TypeMismatchSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
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.dom.ASTNode;
import org.eclipse.jdt.core.dom.Assignment;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.FieldAccess;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.PrimitiveType;
import org.eclipse.jdt.core.dom.SuperFieldAccess;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
public class TypeMismatchSubProcessor {
private TypeMismatchSubProcessor() {
}
public static void addTypeMismatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castTypeName= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveredNode(astRoot);
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
Name receiverNode= null;
ITypeBinding castTypeBinding= null;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
Expression leftHandSide= assign.getLeftHandSide();
if (selectedNode.equals(leftHandSide)) {
nodeToCast= assign.getRightHandSide();
}
castTypeBinding= assign.getLeftHandSide().resolveTypeBinding();
if (leftHandSide instanceof Name) {
receiverNode= (Name) leftHandSide;
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
IVariableBinding varBinding= frag.resolveBinding();
if (varBinding != null) {
castTypeBinding= varBinding.getType();
}
receiverNode= frag.getName();
}
} else {
// try to find the binding corresponding to 'castTypeName'
ITypeBinding guessedCastTypeBinding= ASTResolving.guessBindingForReference(nodeToCast);
if (guessedCastTypeBinding != null && castTypeName.equals(guessedCastTypeBinding.getQualifiedName())) {
castTypeBinding= guessedCastTypeBinding;
}
}
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding == null || canCast(castTypeName, castTypeBinding, binding)) {
proposals.add(createCastProposal(context, castTypeName, nodeToCast, 7));
}
ITypeBinding currBinding= nodeToCast.resolveTypeBinding();
if (currBinding == null || "void".equals(currBinding.getName())) { //$NON-NLS-1$
return;
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
currBinding= Bindings.normalizeTypeBinding(currBinding);
if (currBinding == null) {
currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
ASTRewrite rewrite= ASTRewrite.create(methodDeclaration.getAST());
ImportRewrite imports= new ImportRewrite(cu);
String returnTypeName= imports.addImport(currBinding);
Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName);
rewrite.replace(methodDeclaration.getReturnType(), newReturnType, null);
String label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.changereturntype.description", currBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
proposal.setImportRewrite(imports);
String returnKey= "return"; //$NON-NLS-1$
proposal.addLinkedPosition(rewrite.track(newReturnType), true, returnKey);
ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(astRoot.getAST(), currBinding);
for (int i= 0; i < typeSuggestions.length; i++) {
proposal.addLinkedPositionProposal(returnKey, typeSuggestions[i]);
}
proposals.add(proposal);
}
}
if (receiverNode != null) {
currBinding= Bindings.normalizeTypeBinding(currBinding);
if (currBinding == null) {
currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
addChangeSenderTypeProposals(context, receiverNode, currBinding, true, 6, proposals);
}
if (castTypeBinding != null) {
addChangeSenderTypeProposals(context, nodeToCast, castTypeBinding, false, 5, proposals);
}
}
public static void addChangeSenderTypeProposals(IInvocationContext context, Expression nodeToCast, ITypeBinding castTypeBinding, boolean isAssingedNode, int relevance, Collection proposals) throws JavaModelException {
IBinding callerBinding= null;
switch (nodeToCast.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
callerBinding= ((MethodInvocation) nodeToCast).resolveMethodBinding();
break;
case ASTNode.SUPER_METHOD_INVOCATION:
callerBinding= ((SuperMethodInvocation) nodeToCast).resolveMethodBinding();
break;
case ASTNode.FIELD_ACCESS:
callerBinding= ((FieldAccess) nodeToCast).resolveFieldBinding();
break;
case ASTNode.SUPER_FIELD_ACCESS:
callerBinding= ((SuperFieldAccess) nodeToCast).resolveFieldBinding();
break;
case ASTNode.SIMPLE_NAME:
case ASTNode.QUALIFIED_NAME:
callerBinding= ((Name) nodeToCast).resolveBinding();
break;
}
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ICompilationUnit targetCu= null;
ITypeBinding declaringType= null;
if (callerBinding instanceof IVariableBinding) {
IVariableBinding variableBinding= (IVariableBinding) callerBinding;
if (!variableBinding.isField()) {
targetCu= cu;
} else {
declaringType= variableBinding.getDeclaringClass();
}
} else if (callerBinding instanceof IMethodBinding) {
IMethodBinding methodBinding= (IMethodBinding) callerBinding;
if (!methodBinding.isConstructor()) {
declaringType= methodBinding.getDeclaringClass();
}
}
if (declaringType != null && declaringType.isFromSource()) {
targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
}
if (targetCu != null) {
proposals.add(new TypeChangeCompletionProposal(targetCu, callerBinding, astRoot, castTypeBinding, isAssingedNode, relevance));
}
// add interface to resulting type
if (!isAssingedNode) {
ITypeBinding nodeType= nodeToCast.resolveTypeBinding();
if (castTypeBinding.isInterface() && nodeType != null && nodeType.isClass() && !nodeType.isAnonymous() && nodeType.isFromSource()) {
ICompilationUnit nodeCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, nodeType);
if (nodeCu != null) {
proposals.add(new ImplementInterfaceProposal(nodeCu, nodeType, astRoot, castTypeBinding, relevance - 1));
}
}
}
}
private static boolean canCast(String castTarget, ITypeBinding castTypeBinding, ITypeBinding bindingToCast) {
if (castTypeBinding != null) {
return TypeRules.canCast(castTypeBinding, bindingToCast);
}
bindingToCast= Bindings.normalizeTypeBinding(bindingToCast);
if (bindingToCast == null) {
return false;
}
int arrStart= castTarget.indexOf('[');
if (arrStart != -1) {
if (!bindingToCast.isArray()) {
return "java.lang.Object".equals(bindingToCast.getQualifiedName()); //$NON-NLS-1$
}
castTarget= castTarget.substring(0, arrStart);
bindingToCast= bindingToCast.getElementType();
if (bindingToCast.isPrimitive() && !castTarget.equals(bindingToCast.getName())) {
return false; // can't cast arrays of primitive types into each other
}
}
Code targetCode= PrimitiveType.toCode(castTarget);
if (bindingToCast.isPrimitive()) {
Code castCode= PrimitiveType.toCode(bindingToCast.getName());
if (castCode == targetCode) {
return true;
}
return (targetCode != null && targetCode != PrimitiveType.BOOLEAN && castCode != PrimitiveType.BOOLEAN);
} else {
return targetCode == null; // can not check
}
}
public static ASTRewriteCorrectionProposal createCastProposal(IInvocationContext context, String castType, Expression nodeToCast, int relevance) {
ICompilationUnit cu= context.getCompilationUnit();
String label;
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.changecast.description", castType); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.addcast.description", castType); //$NON-NLS-1$
}
return new CastCompletionProposal(label, cu, nodeToCast, castType, relevance);
}
public static void addIncompatibleReturnTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaModelException {
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
MethodDeclaration decl= (MethodDeclaration) selectedNode;
IMethodBinding binding= decl.resolveBinding();
if (binding == null) {
return;
}
IMethodBinding overridden= Bindings.findMethodDefininition(binding);
if (overridden == null || overridden.getReturnType() == binding.getReturnType()) {
return;
}
ITypeBinding declaringType= overridden.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
proposals.add(new TypeChangeCompletionProposal(cu, binding, astRoot, overridden.getReturnType(), false, 8));
ICompilationUnit targetCu= cu;
if (declaringType != null && declaringType.isFromSource()) {
targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
}
if (targetCu != null) {
proposals.add(new TypeChangeCompletionProposal(targetCu, overridden, astRoot, binding.getReturnType(), false, 7));
}
}
public static void addIncompatibleThrowsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws JavaModelException {
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof MethodDeclaration)) {
return;
}
MethodDeclaration decl= (MethodDeclaration) selectedNode;
IMethodBinding binding= decl.resolveBinding();
if (binding == null) {
return;
}
IMethodBinding overridden= Bindings.findMethodDefininition(binding);
if (overridden == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
ITypeBinding[] methodExceptions= binding.getExceptionTypes();
ITypeBinding[] definedExceptions= overridden.getExceptionTypes();
ArrayList undeclaredExceptions= new ArrayList();
{
ChangeDescription[] changes= new ChangeDescription[methodExceptions.length];
for (int i= 0; i < methodExceptions.length; i++) {
if (!isDeclaredException(methodExceptions[i], definedExceptions)) {
changes[i]= new RemoveDescription();
undeclaredExceptions.add(methodExceptions[i]);
}
}
String label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.removeexceptions.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
proposals.add(new ChangeMethodSignatureProposal(label, cu, astRoot, binding, null, changes, 8, image));
}
ITypeBinding declaringType= overridden.getDeclaringClass();
ICompilationUnit targetCu= cu;
if (declaringType != null && declaringType.isFromSource()) {
targetCu= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
}
if (targetCu != null) {
ChangeDescription[] changes= new ChangeDescription[definedExceptions.length + undeclaredExceptions.size()];
for (int i= 0; i < undeclaredExceptions.size(); i++) {
changes[i + definedExceptions.length]= new InsertDescription((ITypeBinding) undeclaredExceptions.get(i), ""); //$NON-NLS-1$
}
String[] args= { declaringType.getName(), overridden.getName() };
String label= CorrectionMessages.getFormattedString("TypeMismatchSubProcessor.addexceptions.description", args); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
proposals.add(new ChangeMethodSignatureProposal(label, targetCu, astRoot, overridden, null, changes, 7, image));
}
}
private static boolean isDeclaredException(ITypeBinding curr, ITypeBinding[] declared) {
for (int i= 0; i < declared.length; i++) {
if (Bindings.isSuperType(declared[i], curr)) {
return true;
}
}
return false;
}
}
|
62,455
|
Bug 62455 Method stub for "main" interferes with main method template [code manipulation]
|
Build 20040513 When codeassisting behind "main", the codeassist menu incorrectly offers both a main method template and a main method stub (the latter appears first and shouldn't appear at all).
|
verified fixed
|
a753c63
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T17:54:24Z
| 2004-05-17T10:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/GetterSetterCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.Collection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class GetterSetterCompletionProposal extends JavaTypeCompletionProposal {
public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Collection result) throws CoreException {
if (prefix.length() == 0) {
relevance--;
}
IField[] fields= type.getFields();
IMethod[] methods= type.getMethods();
for (int i= 0; i < fields.length; i++) {
IField curr= fields[i];
String getterName= GetterSetterUtil.getGetterName(curr, null);
if (getterName.startsWith(prefix) && !hasMethod(methods, getterName)) {
result.add(new GetterSetterCompletionProposal(curr, offset, length, true, relevance));
}
String setterName= GetterSetterUtil.getSetterName(curr, null);
if (setterName.startsWith(prefix) && !hasMethod(methods, setterName)) {
result.add(new GetterSetterCompletionProposal(curr, offset, length, false, relevance));
}
}
}
private static boolean hasMethod(IMethod[] methods, String name) {
for (int i= 0; i < methods.length; i++) {
if (methods[i].getElementName().equals(name)) {
return true;
}
}
return false;
}
private final IField fField;
private final boolean fIsGetter;
public GetterSetterCompletionProposal(IField field, int start, int length, boolean isGetter, int relevance) throws JavaModelException {
super("", field.getCompilationUnit(), start, length, JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC), getDisplayName(field, isGetter), relevance); //$NON-NLS-1$
Assert.isNotNull(field);
fField= field;
fIsGetter= isGetter;
setProposalInfo(new ProposalInfo(field));
}
private static String getDisplayName(IField field, boolean isGetter) throws JavaModelException {
StringBuffer buf= new StringBuffer();
if (isGetter) {
buf.append(GetterSetterUtil.getGetterName(field, null));
buf.append("() "); //$NON-NLS-1$
buf.append(Signature.toString(field.getTypeSignature()));
buf.append(" - "); //$NON-NLS-1$
buf.append(JavaTextMessages.getFormattedString("GetterSetterCompletionProposal.getter.label", field.getElementName())); //$NON-NLS-1$
} else {
buf.append(GetterSetterUtil.getSetterName(field, null));
buf.append('(').append(Signature.toString(field.getTypeSignature())).append(')');
buf.append(" "); //$NON-NLS-1$
buf.append(Signature.toString(Signature.SIG_VOID));
buf.append(" - "); //$NON-NLS-1$
buf.append(JavaTextMessages.getFormattedString("GetterSetterCompletionProposal.setter.label", field.getElementName())); //$NON-NLS-1$
}
return buf.toString();
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportsStructure)
*/
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
boolean addComments= settings.createComments;
int flags= Flags.AccPublic | (fField.getFlags() & Flags.AccStatic);
String stub;
if (fIsGetter) {
String getterName= GetterSetterUtil.getGetterName(fField, null);
stub= GetterSetterUtil.getGetterStub(fField, getterName, addComments, flags);
} else {
String setterName= GetterSetterUtil.getSetterName(fField, null);
stub= GetterSetterUtil.getSetterStub(fField, setterName, addComments, flags);
}
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int lineStart= region.getOffset();
int indent= Strings.computeIndent(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth);
String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, null, lineDelim, fField.getJavaProject());
if (replacement.endsWith(lineDelim)) {
replacement= replacement.substring(0, replacement.length() - lineDelim.length());
}
setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
return true;
}
}
|
62,455
|
Bug 62455 Method stub for "main" interferes with main method template [code manipulation]
|
Build 20040513 When codeassisting behind "main", the codeassist menu incorrectly offers both a main method template and a main method stub (the latter appears first and shouldn't appear at all).
|
verified fixed
|
a753c63
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T17:54:24Z
| 2004-05-17T10:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/MethodCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.Collection;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
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.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
public class MethodCompletionProposal extends JavaTypeCompletionProposal {
public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Collection result) throws CoreException {
IMethod[] methods= type.getMethods();
String constructorName= type.getElementName();
if (constructorName.length() > 0 && constructorName.startsWith(prefix) && !hasMethod(methods, constructorName)) {
result.add(new MethodCompletionProposal(type, constructorName, null, offset, length, relevance));
}
if (prefix.length() > 0 && !constructorName.equals(prefix) && !hasMethod(methods, prefix)) {
result.add(new MethodCompletionProposal(type, prefix, Signature.SIG_VOID, offset, length, relevance));
}
}
private static boolean hasMethod(IMethod[] methods, String name) {
for (int i= 0; i < methods.length; i++) {
IMethod curr= methods[i];
if (curr.getElementName().equals(name) && curr.getParameterTypes().length == 0) {
return true;
}
}
return false;
}
private final IType fType;
private final String fReturnTypeSig;
private final String fMethodName;
public MethodCompletionProposal(IType type, String methodName, String returnTypeSig, int start, int length, int relevance) {
super("", type.getCompilationUnit(), start, length, null, getDisplayName(methodName, returnTypeSig), relevance); //$NON-NLS-1$
Assert.isNotNull(type);
Assert.isNotNull(methodName);
fType= type;
fMethodName= methodName;
fReturnTypeSig= returnTypeSig;
if (returnTypeSig == null) {
setProposalInfo(new ProposalInfo(type));
ImageDescriptor desc= new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
setImage(JavaPlugin.getImageDescriptorRegistry().get(desc));
} else {
setImage(JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE));
}
}
private static String getDisplayName(String methodName, String returnTypeSig) {
StringBuffer buf= new StringBuffer();
buf.append(methodName);
buf.append('(');
buf.append(')');
if (returnTypeSig != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(Signature.toString(returnTypeSig));
buf.append(" - "); //$NON-NLS-1$
buf.append(JavaTextMessages.getString("MethodCompletionProposal.method.label")); //$NON-NLS-1$
} else {
buf.append(" - "); //$NON-NLS-1$
buf.append(JavaTextMessages.getString("MethodCompletionProposal.constructor.label")); //$NON-NLS-1$
}
return buf.toString();
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportsStructure)
*/
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
boolean addComments= settings.createComments;
String[] empty= new String[0];
String lineDelim= StubUtility.getLineDelimiterFor(document);
String declTypeName= fType.getTypeQualifiedName('.');
StringBuffer buf= new StringBuffer();
if (addComments) {
String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), declTypeName, fMethodName, empty, empty, fReturnTypeSig, null, String.valueOf('\n'));
if (comment != null) {
buf.append(comment);
buf.append('\n');
}
}
if (fReturnTypeSig != null) {
buf.append("private "); //$NON-NLS-1$
} else {
buf.append("public "); //$NON-NLS-1$
}
if (fReturnTypeSig != null) {
buf.append(Signature.toString(fReturnTypeSig));
}
buf.append(' ');
buf.append(fMethodName);
buf.append("() {\n"); //$NON-NLS-1$
String body= CodeGeneration.getMethodBodyContent(fType.getCompilationUnit(), declTypeName, fMethodName, fReturnTypeSig == null, "", String.valueOf('\n')); //$NON-NLS-1$
if (body != null) {
buf.append(body);
buf.append('\n');
}
buf.append("}\n"); //$NON-NLS-1$
String stub= buf.toString();
// use the code formatter
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int lineStart= region.getOffset();
int indent= Strings.computeIndent(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth);
String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, null, lineDelim, fType.getJavaProject());
if (replacement.endsWith(lineDelim)) {
replacement= replacement.substring(0, replacement.length() - lineDelim.length());
}
setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
return true;
}
}
|
62,455
|
Bug 62455 Method stub for "main" interferes with main method template [code manipulation]
|
Build 20040513 When codeassisting behind "main", the codeassist menu incorrectly offers both a main method template and a main method stub (the latter appears first and shouldn't appear at all).
|
verified fixed
|
a753c63
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-17T17:54:24Z
| 2004-05-17T10:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jdt.core.CompletionRequestorAdapter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.codeassist.IExtendedCompletionRequestor;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeFilter;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
/**
* Bin to collect the proposal of the infrastructure on code assist in a java text.
*/
public class ResultCollector extends CompletionRequestorAdapter implements IExtendedCompletionRequestor {
private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' };
private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' };
private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' };
private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';', '.' };
protected IJavaProject fJavaProject;
protected ICompilationUnit fCompilationUnit; // set when imports can be added
protected int fCodeAssistOffset;
protected int fContextOffset;
protected ITextViewer fTextViewer;
private ArrayList fFields=
new ArrayList(),
fKeywords= new ArrayList(10),
fLabels= new ArrayList(10),
fMethods= new ArrayList(),
fModifiers= new ArrayList(10),
fPackages= new ArrayList(),
fTypes= new ArrayList(),
fVariables= new ArrayList();
private IProblem fLastProblem;
private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry();
private ArrayList[] fResults = new ArrayList[] {
fPackages, fLabels, fModifiers, fKeywords, fTypes, fMethods, fFields, fVariables
};
private int fUserReplacementLength;
/*
* Is eating code assist enabled or disabled? PR #3666
* When eating is enabled, JavaCompletionProposal must be revisited: PR #5533
*/
private boolean fPreventEating= true;
/*
* @see ICompletionRequestor#acceptClass
*/
public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, false, false, modifiers);
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICompletionRequestor#acceptError
*/
public void acceptError(IProblem error) {
fLastProblem= error;
}
/*
* @see ICompletionRequestor#acceptField
*/
public void acceptField(
char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[] typePackageName, char[] typeName, char[] completionName,
int modifiers, int start, int end, int relevance) {
if (TypeFilter.isFiltered(declaringTypePackageName)) {
return;
}
ImageDescriptor descriptor= getFieldDescriptor(modifiers);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
if (typeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(typeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name));
proposal.setTriggerCharacters(VAR_TRIGGER);
fFields.add(proposal);
}
/*
* @see ICompletionRequestor#acceptInterface
*/
public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(true, false, false, modifiers);
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICompletionRequestor#acceptAnonymousType
*/
public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) {
if (TypeFilter.isFiltered(superTypePackageName)) {
return;
}
JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd, relevance);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName));
fTypes.add(proposal);
}
/*
* @see ICompletionRequestor#acceptKeyword
*/
public void acceptKeyword(char[] keyword, int start, int end, int relevance) {
String kw= new String(keyword);
fKeywords.add(createCompletion(start, end, kw, null, kw, relevance));
}
/*
* @see ICompletionRequestor#acceptLabel
*/
public void acceptLabel(char[] labelName, int start, int end, int relevance) {
String ln= new String(labelName);
fLabels.add(createCompletion(start, end, ln, null, ln, relevance));
}
/*
* @see ICompletionRequestor#acceptLocalVariable
*/
public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end, int relevance) {
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(name), JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
protected String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) {
StringBuffer buf = new StringBuffer();
if (parameterTypeNames != null) {
for (int i = 0; i < parameterTypeNames.length; i++) {
if (i > 0) {
buf.append(',');
buf.append(' ');
}
buf.append(parameterTypeNames[i]);
if (parameterNames != null && parameterNames[i] != null) {
buf.append(' ');
buf.append(parameterNames[i]);
}
}
}
return buf.toString();
}
/*
* @see ICompletionRequestor#acceptMethod
*/
public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers,
int start, int end, int relevance) {
if (completionName == null)
return;
if (TypeFilter.isFiltered(declaringTypePackageName)) {
return;
}
JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterPackageNames, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, relevance);
boolean isConstructor= returnTypeName == null ? true : returnTypeName.length == 0;
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, isConstructor));
boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')');
ProposalContextInformation contextInformation= null;
if (hasOpeningBracket && parameterTypeNames.length > 0) {
contextInformation= new ProposalContextInformation();
contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames));
contextInformation.setContextDisplayString(proposal.getDisplayString());
contextInformation.setImage(proposal.getImage());
int position= (completionName.length == 0) ? fContextOffset : -1;
contextInformation.setContextInformationPosition(position);
proposal.setContextInformation(contextInformation);
}
boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0);
char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS;
proposal.setTriggerCharacters(triggers);
if (userMustCompleteParameters) {
// set the cursor before the closing bracket
proposal.setCursorPosition(completionName.length - 1);
}
fMethods.add(proposal);
}
/*
* @see ICompletionRequestor#acceptModifier
*/
public void acceptModifier(char[] modifier, int start, int end, int relevance) {
String mod= new String(modifier);
fModifiers.add(createCompletion(start, end, mod, null, mod, relevance));
}
/*
* @see ICompletionRequestor#acceptPackage
*/
public void acceptPackage(char[] packageName, char[] completionName, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName), relevance));
}
/*
* @see ICompletionRequestor#acceptType
*/
public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int relevance) {
if (TypeFilter.isFiltered(packageName)) {
return;
}
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info, relevance));
}
/*
* @see ICodeCompletionRequestor#acceptMethodDeclaration
*/
public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) {
StringBuffer displayString= getMethodDisplayString(null, name, parameterTypeNames, parameterNames, returnTypeName);
displayString.append(" - "); //$NON-NLS-1$
displayString.append(JavaTextMessages.getFormattedString("ResultCollector.overridingmethod", new String(declaringTypeName))); //$NON-NLS-1$
StringBuffer typeName= new StringBuffer();
if (declaringTypePackageName.length > 0) {
typeName.append(declaringTypePackageName);
typeName.append('.');
}
typeName.append(declaringTypeName);
String[] paramTypes= new String[parameterTypeNames.length];
for (int i= 0; i < parameterTypeNames.length; i++) {
paramTypes[i]= Signature.createTypeSignature(parameterTypeNames[i], true);
}
JavaCompletionProposal proposal= new OverrideCompletionProposal(fJavaProject, fCompilationUnit, typeName.toString(), new String(name), paramTypes, start, getLength(start, end), displayString.toString(), new String(completionName));
proposal.setImage(getImage(getMemberDescriptor(modifiers)));
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0));
proposal.setRelevance(relevance);
fMethods.add(proposal);
}
/*
* @see IExtendedCompletionRequestor#acceptPotentialMethodDeclaration
*/
public void acceptPotentialMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] selector, int completionStart, int completionEnd, int relevance) {
if (fCompilationUnit == null) {
return;
}
String prefix= new String(selector);
try {
IJavaElement element= fCompilationUnit.getElementAt(fCodeAssistOffset);
if (element != null) {
IType type= (IType) element.getAncestor(IJavaElement.TYPE);
if (type != null) {
GetterSetterCompletionProposal.evaluateProposals(type, prefix, completionStart, completionEnd - completionStart, 100, fMethods);
MethodCompletionProposal.evaluateProposals(type, prefix, completionStart, completionEnd - completionStart, 100, fMethods);
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
/*
* @see ICodeCompletionRequestor#acceptVariableName
*/
public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end, int relevance) {
// XXX: To be revised
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null && typeName.length > 0) {
buf.append(" - "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString(), relevance);
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
public String getErrorMessage() {
if (fLastProblem != null)
return fLastProblem.getMessage();
return ""; //$NON-NLS-1$
}
public JavaCompletionProposal[] getResults() {
// return unsorted
int totLen= 0;
for (int i= 0; i < fResults.length; i++) {
totLen += fResults[i].size();
}
JavaCompletionProposal[] result= new JavaCompletionProposal[totLen];
int k= 0;
for (int i= 0; i < fResults.length; i++) {
ArrayList curr= fResults[i];
int currLen= curr.size();
for (int j= 0; j < currLen; j++) {
JavaCompletionProposal proposal= (JavaCompletionProposal) curr.get(j);
// for equal relevance, take categories
proposal.setRelevance(proposal.getRelevance() * 16 + i);
result[k++]= proposal;
}
}
return result;
}
public JavaCompletionProposal[] getKeywordCompletions() {
return (JavaCompletionProposal[]) fKeywords.toArray(new JavaCompletionProposal[fKeywords.size()]);
}
private StringBuffer getMethodDisplayString(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName) {
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
nameBuffer.append('(');
if (parameterTypeNames != null && parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
if (returnTypeName != null && returnTypeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(returnTypeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
return nameBuffer;
}
protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypePackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) {
ImageDescriptor descriptor= getMemberDescriptor(modifiers);
StringBuffer nameBuffer= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName);
return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance);
}
protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end, int relevance) {
StringBuffer declTypeBuf= new StringBuffer();
if (declaringTypePackageName.length > 0) {
declTypeBuf.append(declaringTypePackageName);
declTypeBuf.append('.');
}
declTypeBuf.append(declaringTypeName);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(declaringTypeName);
nameBuffer.append('(');
if (parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$
int length= end - start;
return new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString(), relevance);
}
protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo, int relevance) {
String fullName= JavaModelUtil.concatenateName(containerName, typeName); // containername can be null
StringBuffer buf= new StringBuffer(Signature.getSimpleName(fullName));
String typeQualifier= Signature.getQualifier(fullName);
if (typeQualifier.length() > 0) {
buf.append(" - "); //$NON-NLS-1$
buf.append(typeQualifier);
} else if (containerName != null) {
buf.append(JavaTextMessages.getString("ResultCollector.default_package")); //$NON-NLS-1$
}
String name= buf.toString();
ICompilationUnit cu= null;
if (containerName != null && fCompilationUnit != null) {
if (completion.equals(fullName)) {
cu= fCompilationUnit;
}
}
JavaCompletionProposal proposal= new JavaTypeCompletionProposal(completion, cu, start, getLength(start, end), getImage(descriptor), name, relevance, typeName, containerName);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters(TYPE_TRIGGERS);
return proposal;
}
protected ImageDescriptor getMemberDescriptor(int modifiers) {
ImageDescriptor desc= JavaElementImageProvider.getMethodImageDescriptor(false, modifiers);
if (Flags.isDeprecated(modifiers))
desc= getDeprecatedDescriptor(desc);
if (Flags.isStatic(modifiers))
desc= getStaticDescriptor(desc);
return desc;
}
protected ImageDescriptor getFieldDescriptor(int modifiers) {
ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, modifiers);
if (Flags.isDeprecated(modifiers))
desc= getDeprecatedDescriptor(desc);
if (Flags.isStatic(modifiers))
desc= getStaticDescriptor(desc);
return desc;
}
protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) {
return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.DEPRECATED, JavaElementImageProvider.SMALL_SIZE);
}
protected ImageDescriptor getStaticDescriptor(ImageDescriptor descriptor) {
return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE);
}
protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name, int relevance) {
return new JavaCompletionProposal(completion, start, getLength(start, end), getImage(descriptor), name, relevance, fTextViewer);
}
private int getLength(int start, int end) {
int length;
if (fUserReplacementLength == -1) {
length= fPreventEating ? fCodeAssistOffset - start : end - start;
} else {
length= fUserReplacementLength;
// extend length to begin at start
if (start < fCodeAssistOffset) {
length+= fCodeAssistOffset - start;
}
}
return length;
}
private Image getImage(ImageDescriptor descriptor) {
return (descriptor == null) ? null : fRegistry.get(descriptor);
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset at which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param contextOffset The offset at which the context presumable start or -1.
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, int contextOffset, IJavaProject jproject, ICompilationUnit cu) {
fJavaProject= jproject;
fCompilationUnit= cu;
fCodeAssistOffset= codeAssistOffset;
fContextOffset= contextOffset;
fUserReplacementLength= -1;
fLastProblem= null;
for (int i= 0; i < fResults.length; i++)
fResults[i].clear();
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset on which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) {
reset(codeAssistOffset, -1, jproject, cu);
}
/**
* Sets the text viewer.
*/
public void setViewer(ITextViewer viewer) {
fTextViewer= viewer;
}
/**
* If the replacement length is set, it overrides the length returned from
* the content assist infrastructure.
* Use this setting if code assist is called with a none empty selection.
*/
public void setReplacementLength(int length) {
fUserReplacementLength= length;
}
/**
* If set, proposals created will not remove characters after the code assist position
* @param preventEating The preventEating to set
*/
public void setPreventEating(boolean preventEating) {
fPreventEating= preventEating;
}
}
|
61,014
|
Bug 61014 All types cache populated during start-up
|
When restoring a crashed workspace the AllTypeCache Updater has shown-up during the start-up sequence before an event loop is active. The suspicion is that this updating is triggered by a delta before the runnable that triggers the initial population is executed. The solution we have discussed is that the all types cache should ignore deltas and not start updating before the runnable is executed.
|
resolved fixed
|
3341f9e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T07:32:21Z
| 2004-05-05T12:26:40Z
|
org.eclipse.jdt.ui/core
| |
61,014
|
Bug 61014 All types cache populated during start-up
|
When restoring a crashed workspace the AllTypeCache Updater has shown-up during the start-up sequence before an event loop is active. The suspicion is that this updating is triggered by a delta before the runnable that triggers the initial population is executed. The solution we have discussed is that the all types cache should ignore deltas and not start updating before the runnable is executed.
|
resolved fixed
|
3341f9e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T07:32:21Z
| 2004-05-05T12:26:40Z
|
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
61,641
|
Bug 61641 Introduce Parameter introduces compile errors when used on arrays
|
In M8, applying the Introduce Parameter refactoring on the argument passed to doSomething(...) in the following scenario: public class AClass { public void method1() { method2(); } public void method2() { doSomething(new int[] {1, 2, 3}); ... } ... } Gives: public class AClass { public void method1() { method2(new int[]={1,2,3}); } public void method2(int[] ints) { doSomething(ints); ... } ... } Where did that equals sign in the call to method2 come from? It causes a compile error. Also, what happened to the spaces after the commas in the array creation?
|
resolved fixed
|
78a8cb1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:05:13Z
| 2004-05-10T20:13:20Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceParameter/simple/Formatting1.java
| |
61,641
|
Bug 61641 Introduce Parameter introduces compile errors when used on arrays
|
In M8, applying the Introduce Parameter refactoring on the argument passed to doSomething(...) in the following scenario: public class AClass { public void method1() { method2(); } public void method2() { doSomething(new int[] {1, 2, 3}); ... } ... } Gives: public class AClass { public void method1() { method2(new int[]={1,2,3}); } public void method2(int[] ints) { doSomething(ints); ... } ... } Where did that equals sign in the call to method2 come from? It causes a compile error. Also, what happened to the spaces after the commas in the array creation?
|
resolved fixed
|
78a8cb1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:05:13Z
| 2004-05-10T20:13:20Z
|
org.eclipse.jdt.ui.tests.refactoring/resources/IntroduceParameter/simple/out/Formatting1.java
| |
61,641
|
Bug 61641 Introduce Parameter introduces compile errors when used on arrays
|
In M8, applying the Introduce Parameter refactoring on the argument passed to doSomething(...) in the following scenario: public class AClass { public void method1() { method2(); } public void method2() { doSomething(new int[] {1, 2, 3}); ... } ... } Gives: public class AClass { public void method1() { method2(new int[]={1,2,3}); } public void method2(int[] ints) { doSomething(ints); ... } ... } Where did that equals sign in the call to method2 come from? It causes a compile error. Also, what happened to the spaces after the commas in the array creation?
|
resolved fixed
|
78a8cb1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:05:13Z
| 2004-05-10T20:13:20Z
|
org.eclipse.jdt.ui.tests.refactoring/test
| |
61,641
|
Bug 61641 Introduce Parameter introduces compile errors when used on arrays
|
In M8, applying the Introduce Parameter refactoring on the argument passed to doSomething(...) in the following scenario: public class AClass { public void method1() { method2(); } public void method2() { doSomething(new int[] {1, 2, 3}); ... } ... } Gives: public class AClass { public void method1() { method2(new int[]={1,2,3}); } public void method2(int[] ints) { doSomething(ints); ... } ... } Where did that equals sign in the call to method2 come from? It causes a compile error. Also, what happened to the spaces after the commas in the array creation?
|
resolved fixed
|
78a8cb1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:05:13Z
| 2004-05-10T20:13:20Z
|
cases/org/eclipse/jdt/ui/tests/refactoring/IntroduceParameterTests.java
| |
61,641
|
Bug 61641 Introduce Parameter introduces compile errors when used on arrays
|
In M8, applying the Introduce Parameter refactoring on the argument passed to doSomething(...) in the following scenario: public class AClass { public void method1() { method2(); } public void method2() { doSomething(new int[] {1, 2, 3}); ... } ... } Gives: public class AClass { public void method1() { method2(new int[]={1,2,3}); } public void method2(int[] ints) { doSomething(ints); ... } ... } Where did that equals sign in the call to method2 come from? It causes a compile error. Also, what happened to the spaces after the commas in the array creation?
|
resolved fixed
|
78a8cb1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:05:13Z
| 2004-05-10T20:13:20Z
|
org.eclipse.jdt.ui/core
| |
61,641
|
Bug 61641 Introduce Parameter introduces compile errors when used on arrays
|
In M8, applying the Introduce Parameter refactoring on the argument passed to doSomething(...) in the following scenario: public class AClass { public void method1() { method2(); } public void method2() { doSomething(new int[] {1, 2, 3}); ... } ... } Gives: public class AClass { public void method1() { method2(new int[]={1,2,3}); } public void method2(int[] ints) { doSomething(ints); ... } ... } Where did that equals sign in the call to method2 come from? It causes a compile error. Also, what happened to the spaces after the commas in the array creation?
|
resolved fixed
|
78a8cb1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:05:13Z
| 2004-05-10T20:13:20Z
|
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/IntroduceParameterRefactoring.java
| |
62,503
|
Bug 62503 Classloader problem with older versions of JUnit [JUnit]
|
I have a project with a version 3.6 junit.jar on the classpath. In 3.0M8 when I run a test with an assertEquals() that fails, I get this error: java.lang.NoClassDefFoundError: junit/framework/ComparisonFailure at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.addFailure(RemoteTestRunner.java:533) at junit.framework.TestResult.addFailure(TestResult.java:46) at junit.framework.TestResult.runProtected(TestResult.java:127) at junit.framework.TestResult.run(TestResult.java:109) at junit.framework.TestCase.run(TestCase.java:131) at junit.framework.TestSuite.runTest(TestSuite.java:173) at junit.framework.TestSuite.run(TestSuite.java:168) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:410) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:294) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:182) Exception in thread "main" This used to work with Eclipse 2.1 (which also had JUnit 3.8.1 built in), and it disappears when I upgrade my copy of junit.jar to 3.8.1 to match the Eclipse one.
|
resolved fixed
|
73ac583
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T08:56:39Z
| 2004-05-17T16:06:40Z
|
org.eclipse.jdt.junit.runtime/src/org/eclipse/jdt/internal/junit/runner/RemoteTestRunner.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Sebastian Davids: sdavids@gmx.de bug 26754
*******************************************************************************/
package org.eclipse.jdt.internal.junit.runner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.Socket;
import java.util.Vector;
import junit.extensions.TestDecorator;
import junit.framework.AssertionFailedError;
import junit.framework.ComparisonFailure;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestFailure;
import junit.framework.TestListener;
import junit.framework.TestResult;
import junit.framework.TestSuite;
/**
* A TestRunner that reports results via a socket connection.
* See MessageIds for more information about the protocl.
*/
public class RemoteTestRunner implements TestListener {
/**
* Holder for information for a rerun request
*/
private static class RerunRequest {
String fRerunClassName;
String fRerunTestName;
int fRerunTestId;
public RerunRequest(int testId, String className, String testName) {
fRerunTestId= testId;
fRerunClassName= className;
fRerunTestName= testName;
}
}
private static final String SET_UP_TEST_METHOD_NAME= "setUpTest"; //$NON-NLS-1$
private static final String SUITE_METHODNAME= "suite"; //$NON-NLS-1$
/**
* The name of the test classes to be executed
*/
private String[] fTestClassNames;
/**
* The name of the test (argument -test)
*/
private String fTestName;
/**
* The current test result
*/
private TestResult fTestResult;
/**
* The version expected by the client
*/
private String fVersion= ""; //$NON-NLS-1$
/**
* The client socket.
*/
private Socket fClientSocket;
/**
* Print writer for sending messages
*/
private PrintWriter fWriter;
/**
* Reader for incoming messages
*/
private BufferedReader fReader;
/**
* Host to connect to, default is the localhost
*/
private String fHost= ""; //$NON-NLS-1$
/**
* Port to connect to.
*/
private int fPort= -1;
/**
* Is the debug mode enabled?
*/
private boolean fDebugMode= false;
/**
* Keep the test run server alive after a test run has finished.
* This allows to rerun tests.
*/
private boolean fKeepAlive= false;
/**
* Has the server been stopped
*/
private boolean fStopped= false;
/**
* Queue of rerun requests.
*/
private Vector fRerunRequests= new Vector(10);
/**
* Thread reading from the socket
*/
private ReaderThread fReaderThread;
private String fRerunTest;
/**
* Reader thread that processes messages from the client.
*/
private class ReaderThread extends Thread {
public ReaderThread() {
super("ReaderThread"); //$NON-NLS-1$
}
public void run(){
try {
String message= null;
while (true) {
if ((message= fReader.readLine()) != null) {
if (message.startsWith(MessageIds.TEST_STOP)){
fStopped= true;
RemoteTestRunner.this.stop();
synchronized(RemoteTestRunner.this) {
RemoteTestRunner.this.notifyAll();
}
break;
}
else if (message.startsWith(MessageIds.TEST_RERUN)) {
String arg= message.substring(MessageIds.MSG_HEADER_LENGTH);
//format: testId className testName
int c0= arg.indexOf(' '); //$NON-NLS-1$
int c1= arg.indexOf(' ', c0+1);
String s= arg.substring(0, c0);
int testId= Integer.parseInt(s);
String className= arg.substring(c0+1, c1);
String testName= arg.substring(c1+1, arg.length());
synchronized(RemoteTestRunner.this) {
fRerunRequests.add(new RerunRequest(testId, className, testName));
RemoteTestRunner.this.notifyAll();
}
}
}
}
} catch (Exception e) {
RemoteTestRunner.this.stop();
}
}
}
/**
* The main entry point.
* Parameters<pre>
* -classnames: the name of the test suite class
* -testfilename: the name of a file containing classnames of test suites
* -test: the test method name (format classname testname)
* -host: the host to connect to default local host
* -port: the port to connect to, mandatory argument
* -keepalive: keep the process alive after a test run
* </pre>
*/
public static void main(String[] args) {
RemoteTestRunner testRunServer= new RemoteTestRunner();
testRunServer.init(args);
testRunServer.run();
// fix for 14434
System.exit(0);
}
/**
* Parse command line arguments. Hook for subclasses to process
* additional arguments.
*/
protected void init(String[] args) {
defaultInit(args);
}
/**
* The class loader to be used for loading tests.
* Subclasses may override to use another class loader.
*/
protected ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
/**
* Process the default arguments.
*/
protected final void defaultInit(String[] args) {
for(int i= 0; i < args.length; i++) {
if(args[i].toLowerCase().equals("-classnames") || args[i].toLowerCase().equals("-classname")){ //$NON-NLS-1$ //$NON-NLS-2$
Vector list= new Vector();
for (int j= i+1; j < args.length; j++) {
if (args[j].startsWith("-")) //$NON-NLS-1$
break;
list.add(args[j]);
}
fTestClassNames= (String[]) list.toArray(new String[list.size()]);
}
else if(args[i].toLowerCase().equals("-test")) { //$NON-NLS-1$
String testName= args[i+1];
int p= testName.indexOf(':');
if (p == -1)
throw new IllegalArgumentException("Testname not separated by \'%\'"); //$NON-NLS-1$
fTestName= testName.substring(p+1);
fTestClassNames= new String[]{ testName.substring(0, p) };
i++;
}
else if(args[i].toLowerCase().equals("-testnamefile")) { //$NON-NLS-1$
String testNameFile= args[i+1];
try {
readTestNames(testNameFile);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read testname file."); //$NON-NLS-1$
}
i++;
} else if(args[i].toLowerCase().equals("-port")) { //$NON-NLS-1$
fPort= Integer.parseInt(args[i+1]);
i++;
}
else if(args[i].toLowerCase().equals("-host")) { //$NON-NLS-1$
fHost= args[i+1];
i++;
}
else if(args[i].toLowerCase().equals("-rerun")) { //$NON-NLS-1$
fRerunTest= args[i+1];
i++;
}
else if(args[i].toLowerCase().equals("-keepalive")) { //$NON-NLS-1$
fKeepAlive= true;
}
else if(args[i].toLowerCase().equals("-debugging") || args[i].toLowerCase().equals("-debug")){ //$NON-NLS-1$ //$NON-NLS-2$
fDebugMode= true;
}
else if(args[i].toLowerCase().equals("-version")){ //$NON-NLS-1$
fVersion= args[i+1];
i++;
}
}
if(fTestClassNames == null || fTestClassNames.length == 0)
throw new IllegalArgumentException(JUnitMessages.getString("RemoteTestRunner.error.classnamemissing")); //$NON-NLS-1$
if (fPort == -1)
throw new IllegalArgumentException(JUnitMessages.getString("RemoteTestRunner.error.portmissing")); //$NON-NLS-1$
if (fDebugMode)
System.out.println("keepalive "+fKeepAlive); //$NON-NLS-1$
}
private void readTestNames(String testNameFile) throws IOException {
BufferedReader br= new BufferedReader(new FileReader(new File(testNameFile)));
try {
String line;
Vector list= new Vector();
while ((line= br.readLine()) != null) {
list.add(line);
}
fTestClassNames= (String[]) list.toArray(new String[list.size()]);
}
finally {
br.close();
}
if (fDebugMode) {
System.out.println("Tests:"); //$NON-NLS-1$
for (int i= 0; i < fTestClassNames.length; i++) {
System.out.println(" "+fTestClassNames[i]); //$NON-NLS-1$
}
}
}
/**
* Connects to the remote ports and runs the tests.
*/
protected void run() {
if (!connect())
return;
if (fRerunTest != null) {
rerunTest(Integer.parseInt(fRerunTest), fTestClassNames[0], fTestName);
return;
}
fTestResult= new TestResult();
fTestResult.addListener(this);
runTests(fTestClassNames, fTestName);
fTestResult.removeListener(this);
if (fTestResult != null) {
fTestResult.stop();
fTestResult= null;
}
if (fKeepAlive)
waitForReruns();
shutDown();
}
/**
* Waits for rerun requests until an explicit stop request
*/
private synchronized void waitForReruns() {
while (!fStopped) {
try {
wait();
if (!fStopped && fRerunRequests.size() > 0) {
RerunRequest r= (RerunRequest)fRerunRequests.remove(0);
rerunTest(r.fRerunTestId, r.fRerunClassName, r.fRerunTestName);
}
} catch (InterruptedException e) {
}
}
}
/**
* Returns the Test corresponding to the given suite.
*/
private Test getTest(String suiteClassName, String testName) {
Class testClass= null;
try {
testClass= loadSuiteClass(suiteClassName);
} catch (ClassNotFoundException e) {
String clazz= e.getMessage();
if (clazz == null)
clazz= suiteClassName;
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.classnotfound", clazz)); //$NON-NLS-1$
return null;
} catch(Exception e) {
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.exception", e )); //$NON-NLS-1$
return null;
}
if (testName != null) {
return setupTest(testClass, createTest(testName, testClass));
}
Method suiteMethod= null;
try {
suiteMethod= testClass.getMethod(SUITE_METHODNAME, new Class[0]);
} catch(Exception e) {
// try to extract a test suite automatically
return new TestSuite(testClass);
}
Test test= null;
try {
test= (Test)suiteMethod.invoke(null, new Class[0]); // static method
}
catch (InvocationTargetException e) {
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.invoke", e.getTargetException().toString() )); //$NON-NLS-1$
return null;
}
catch (IllegalAccessException e) {
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.invoke", e.toString() )); //$NON-NLS-1$
return null;
}
return test;
}
protected void runFailed(String message) {
System.err.println(message);
}
/**
* Loads the test suite class.
*/
private Class loadSuiteClass(String className) throws ClassNotFoundException {
if (className == null)
return null;
return getClassLoader().loadClass(className);
}
/**
* Runs a set of tests.
*/
private void runTests(String[] testClassNames, String testName) {
// instantiate all tests
Test[] suites= new Test[testClassNames.length];
for (int i= 0; i < suites.length; i++) {
suites[i]= getTest(testClassNames[i], testName);
}
// count all testMethods and inform ITestRunListeners
int count= countTests(suites);
notifyTestRunStarted(count);
if (count == 0) {
notifyTestRunEnded(0);
return;
}
long startTime= System.currentTimeMillis();
if (fDebugMode)
System.out.print("start send tree..."); //$NON-NLS-1$
for (int i= 0; i < suites.length; i++) {
sendTree(suites[i]);
}
if (fDebugMode)
System.out.println("done send tree - time(ms): "+(System.currentTimeMillis()-startTime)); //$NON-NLS-1$
long testStartTime= System.currentTimeMillis();
for (int i= 0; i < suites.length; i++) {
suites[i].run(fTestResult);
}
// inform ITestRunListeners of test end
if (fTestResult == null || fTestResult.shouldStop())
notifyTestRunStopped(System.currentTimeMillis() - testStartTime);
else
notifyTestRunEnded(System.currentTimeMillis() - testStartTime);
}
private int countTests(Test[] tests) {
int count= 0;
for (int i= 0; i < tests.length; i++) {
if (tests[i] != null)
count= count + tests[i].countTestCases();
}
return count;
}
/**
* Reruns a test as defined by the fully qualified class name and
* the name of the test.
*/
public void rerunTest(int testId, String className, String testName) {
Test reloadedTest= null;
Class reloadedTestClass= null;
try {
reloadedTestClass= getClassLoader().loadClass(className);
reloadedTest= createTest(testName, reloadedTestClass);
} catch(Exception e) {
reloadedTest= warning(JUnitMessages.getFormattedString("RemoteTestRunner.error.couldnotcreate", testName)); //$NON-NLS-1$
}
Test rerunTest= setupTest(reloadedTestClass, reloadedTest);
TestResult result= new TestResult();
rerunTest.run(result);
notifyTestReran(result, Integer.toString(testId), className, testName);
}
/**
* Prepare a single test to be run standalone. If the test case class provides
* a static method Test setUpTest(Test test) then this method will be invoked.
* Instead of calling the test method directly the "decorated" test returned from
* setUpTest will be called. The purpose of this mechanism is to enable
* tests which requires a set-up to be run individually.
*/
private Test setupTest(Class reloadedTestClass, Test reloadedTest) {
Method setup= null;
try {
setup= reloadedTestClass.getMethod(SET_UP_TEST_METHOD_NAME, new Class[] {Test.class});
} catch (SecurityException e1) {
return reloadedTest;
} catch (NoSuchMethodException e) {
return reloadedTest;
}
if (setup.getReturnType() != Test.class)
return warning(JUnitMessages.getString("RemoteTestRunner.error.notestreturn")); //$NON-NLS-1$
if (!Modifier.isPublic(setup.getModifiers()))
return warning(JUnitMessages.getString("RemoteTestRunner.error.shouldbepublic")); //$NON-NLS-1$
if (!Modifier.isStatic(setup.getModifiers()))
return warning(JUnitMessages.getString("RemoteTestRunner.error.shouldbestatic")); //$NON-NLS-1$
try {
Test test= (Test)setup.invoke(null, new Object[] {reloadedTest});
if (test == null)
return warning(JUnitMessages.getString("RemoteTestRunner.error.nullreturn")); //$NON-NLS-1$
return test;
} catch (IllegalArgumentException e) {
return warning(JUnitMessages.getFormattedString("RemoteTestRunner.error.couldnotinvoke", e)); //$NON-NLS-1$
} catch (IllegalAccessException e) {
return warning(JUnitMessages.getFormattedString("RemoteTestRunner.error.couldnotinvoke", e)); //$NON-NLS-1$
} catch (InvocationTargetException e) {
return warning(JUnitMessages.getFormattedString("RemoteTestRunner.error.invocationexception", e.getTargetException())); //$NON-NLS-1$
}
}
/**
* Returns a test which will fail and log a warning message.
*/
private Test warning(final String message) {
return new TestCase("warning") { //$NON-NLS-1$
protected void runTest() {
fail(message);
}
};
}
private Test createTest(String testName, Class testClass) {
Class[] classArgs= { String.class };
Test test;
Constructor constructor= null;
try {
try {
constructor= testClass.getConstructor(classArgs);
test= (Test)constructor.newInstance(new Object[]{testName});
} catch (NoSuchMethodException e) {
// try the no arg constructor supported in 3.8.1
constructor= testClass.getConstructor(new Class[0]);
test= (Test)constructor.newInstance(new Object[0]);
if (test instanceof TestCase)
((TestCase) test).setName(testName);
}
if (test != null)
return test;
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
} catch (ClassCastException e) {
}
return warning("Could not create test \'"+testName+"\' "); //$NON-NLS-1$ //$NON-NLS-2$
}
/*
* @see TestListener#addError(Test, Throwable)
*/
public final void addError(Test test, Throwable throwable) {
notifyTestFailed(test, MessageIds.TEST_ERROR, getTrace(throwable));
}
/*
* @see TestListener#addFailure(Test, AssertionFailedError)
*/
public final void addFailure(Test test, AssertionFailedError assertionFailedError) {
if ("3".equals(fVersion)) { //$NON-NLS-1$
if (assertionFailedError instanceof ComparisonFailure) {
// transmit the expected and the actual string
String expected = getField(assertionFailedError, "fExpected"); //$NON-NLS-1$
String actual = getField(assertionFailedError, "fActual"); //$NON-NLS-1$
if (expected != null && actual != null) {
notifyTestFailed2(test, MessageIds.TEST_FAILED, getTrace(assertionFailedError), expected, actual);
return;
}
}
}
notifyTestFailed(test, MessageIds.TEST_FAILED, getTrace(assertionFailedError));
}
/*
* @see TestListener#endTest(Test)
*/
public void endTest(Test test) {
notifyTestEnded(test);
}
/*
* @see TestListener#startTest(Test)
*/
public void startTest(Test test) {
notifyTestStarted(test);
}
private void sendTree(Test test){
if(test instanceof TestDecorator){
TestDecorator decorator= (TestDecorator) test;
sendTree(decorator.getTest());
}
else if(test instanceof TestSuite){
TestSuite suite= (TestSuite) test;
notifyTestTreeEntry(getTestId(test)+','+escapeComma(suite.toString().trim()) + ',' + true + ',' + suite.testCount());
for(int i=0; i < suite.testCount(); i++){
sendTree(suite.testAt(i));
}
}
else {
notifyTestTreeEntry(getTestId(test)+ ',' + escapeComma(getTestName(test).trim()) + ',' + false + ',' + test.countTestCases());
}
}
private String escapeComma(String s) {
if ((s.indexOf(',') < 0) && (s.indexOf('\\') < 0))
return s;
StringBuffer sb= new StringBuffer(s.length()+10);
for (int i= 0; i < s.length(); i++) {
char c= s.charAt(i);
if (c == ',')
sb.append("\\,"); //$NON-NLS-1$
else if (c == '\\')
sb.append("\\\\"); //$NON-NLS-1$
else
sb.append(c);
}
return sb.toString();
}
private String getTestId(Test test) {
return Integer.toString(System.identityHashCode(test));
}
private String getTestName(Test test) {
if (test instanceof TestCase) {
TestCase testCase= (TestCase) test;
return JUnitMessages.getFormattedString("RemoteTestRunner.testName", new String[] {testCase.getName(), test.getClass().getName()}); //$NON-NLS-1$
}
if (test instanceof TestSuite) {
TestSuite suite= (TestSuite) test;
if (suite.getName() != null)
return suite.getName();
return getClass().getName();
}
return test.toString();
}
/**
* Returns the stack trace for the given throwable.
*/
private String getTrace(Throwable t) {
StringWriter stringWriter= new StringWriter();
PrintWriter writer= new PrintWriter(stringWriter);
t.printStackTrace(writer);
StringBuffer buffer= stringWriter.getBuffer();
return buffer.toString();
}
/**
* Stop the current test run.
*/
protected void stop() {
if (fTestResult != null) {
fTestResult.stop();
}
}
/**
* Connect to the remote test listener.
*/
private boolean connect() {
if (fDebugMode)
System.out.println("RemoteTestRunner: trying to connect" + fHost + ":" + fPort); //$NON-NLS-1$ //$NON-NLS-2$
Exception exception= null;
for (int i= 1; i < 20; i++) {
try{
fClientSocket= new Socket(fHost, fPort);
try {
fWriter= new PrintWriter(new BufferedWriter(new OutputStreamWriter(fClientSocket.getOutputStream(), "UTF-8")), false/*true*/); //$NON-NLS-1$
} catch (UnsupportedEncodingException e1) {
fWriter= new PrintWriter(new BufferedWriter(new OutputStreamWriter(fClientSocket.getOutputStream())), false/*true*/);
}
try {
fReader= new BufferedReader(new InputStreamReader(fClientSocket.getInputStream(), "UTF-8")); //$NON-NLS-1$
} catch (UnsupportedEncodingException e1) {
fReader= new BufferedReader(new InputStreamReader(fClientSocket.getInputStream()));
}
fReaderThread= new ReaderThread();
fReaderThread.start();
return true;
} catch(IOException e){
exception= e;
}
try {
Thread.sleep(2000);
} catch(InterruptedException e) {
}
}
runFailed(JUnitMessages.getFormattedString("RemoteTestRunner.error.connect", new String[]{fHost, Integer.toString(fPort)} )); //$NON-NLS-1$
exception.printStackTrace();
return false;
}
/**
* Shutsdown the connection to the remote test listener.
*/
private void shutDown() {
if (fWriter != null) {
fWriter.close();
fWriter= null;
}
try {
if (fReaderThread != null) {
// interrupt reader thread so that we don't block on close
// on a lock held by the BufferedReader
// fix for bug: 38955
fReaderThread.interrupt();
}
if (fReader != null) {
fReader.close();
fReader= null;
}
} catch(IOException e) {
if (fDebugMode)
e.printStackTrace();
}
try {
if (fClientSocket != null) {
fClientSocket.close();
fClientSocket= null;
}
} catch(IOException e) {
if (fDebugMode)
e.printStackTrace();
}
}
private void sendMessage(String msg) {
if(fWriter == null)
return;
fWriter.println(msg);
}
private void notifyTestRunStarted(int testCount) {
sendMessage(MessageIds.TEST_RUN_START + testCount + " " + "v2"); //$NON-NLS-1$ //$NON-NLS-2$
}
private void notifyTestRunEnded(long elapsedTime) {
sendMessage(MessageIds.TEST_RUN_END + elapsedTime);
fWriter.flush();
//shutDown();
}
private void notifyTestRunStopped(long elapsedTime) {
sendMessage(MessageIds.TEST_STOPPED + elapsedTime );
fWriter.flush();
//shutDown();
}
private void notifyTestStarted(Test test) {
sendMessage(MessageIds.TEST_START + getTestId(test) + ','+test.toString());
fWriter.flush();
}
private void notifyTestEnded(Test test) {
sendMessage(MessageIds.TEST_END + getTestId(test)+','+getTestName(test));
}
private void notifyTestFailed(Test test, String status, String trace) {
sendMessage(status + getTestId(test) + ',' + getTestName(test));
sendMessage(MessageIds.TRACE_START);
sendMessage(trace);
sendMessage(MessageIds.TRACE_END);
fWriter.flush();
}
private void notifyTestFailed2(Test test, String status, String trace, String expected, String actual) {
sendMessage(status + getTestId(test) + ',' + getTestName(test));
sendMessage(MessageIds.EXPECTED_START);
sendMessage(expected);
sendMessage(MessageIds.EXPECTED_END);
sendMessage(MessageIds.ACTUAL_START);
sendMessage(actual);
sendMessage(MessageIds.ACTUAL_END);
sendMessage(MessageIds.TRACE_START);
sendMessage(trace);
sendMessage(MessageIds.TRACE_END);
fWriter.flush();
}
private void notifyTestTreeEntry(String treeEntry) {
sendMessage(MessageIds.TEST_TREE + treeEntry);
}
private void notifyTestReran(TestResult result, String testId, String testClass, String testName) {
TestFailure failure= null;
if (result.errorCount() > 0) {
failure= (TestFailure)result.errors().nextElement();
}
if (result.failureCount() > 0) {
failure= (TestFailure)result.failures().nextElement();
}
if (failure != null) {
Throwable t= failure.thrownException();
if ("3".equals(fVersion)) { //$NON-NLS-1$
if (t instanceof ComparisonFailure) {
// transmit the expected and the actual string
String expected = getField(t, "fExpected"); //$NON-NLS-1$
String actual = getField(t, "fActual"); //$NON-NLS-1$
if (expected != null && actual != null) {
sendMessage(MessageIds.EXPECTED_START);
sendMessage(expected);
sendMessage(MessageIds.EXPECTED_END);
sendMessage(MessageIds.ACTUAL_START);
sendMessage(actual);
sendMessage(MessageIds.ACTUAL_END);
}
}
}
String trace= getTrace(t);
sendMessage(MessageIds.RTRACE_START);
sendMessage(trace);
sendMessage(MessageIds.RTRACE_END);
fWriter.flush();
}
String status= "OK"; //$NON-NLS-1$
if (result.errorCount() > 0)
status= "ERROR"; //$NON-NLS-1$
else if (result.failureCount() > 0)
status= "FAILURE"; //$NON-NLS-1$
if (fPort != -1) {
sendMessage(MessageIds.TEST_RERAN + testId+ " "+testClass+" "+testName+" "+status); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
fWriter.flush();
}
}
private String getField(Object object, String fieldName) {
Class clazz= object.getClass();
try {
Field field= clazz.getDeclaredField(fieldName);
field.setAccessible(true);
Object result= field.get(object);
return result.toString();
} catch (Exception e) {
// fall through
}
return null;
}
}
|
62,603
|
Bug 62603 NPE in JavaTypeCompletionProcessor [refactoring]
|
I20040514 + ZRH plug-ins from 20040518 1. Have this java class: <pre> package org.eclipse.jdt.text.tests; import java.text.CharacterIterator; import junit.framework.Assert; import junit.framework.TestCase; import org.eclipse.jdt.internal.ui.text.WordNavigator; /** * @since 3.0 */ public class WordNavigationTest extends TestCase { private WordNavigator fWordNavigator; /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { fWordNavigator= new WordNavigator(); } public void testNext1() { CharacterIterator it= null; int pos= fWordNavigator.next(it); Assert.assertEquals(5, pos); } } </pre> 2. Select the two last lines of method testNext1 3. Press Alt+Shift+M to extract method -> get this: !ENTRY org.eclipse.ui 4 4 May 18, 2004 10:07:37.267 !MESSAGE The command for the key you pressed failed The command for the key you pressed failed Reason: !ENTRY org.eclipse.ui 4 0 May 18, 2004 10:07:37.295 !MESSAGE The command for the key you pressed failed !STACK 0 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor.setPackageFragment(JavaTypeCompletionProcessor.java:55) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.installParameterTypeContentAssist(ChangeParametersControl.java:640) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.addCellEditors(ChangeParametersControl.java:552) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.createParameterList(ChangeParametersControl.java:281) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:212) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:182) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.createControl(ExtractMethodInputPage.java:150) at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:533) at org.eclipse.jface.window.Window.create(Window.java:348) at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:924) at org.eclipse.jface.window.Window.open(Window.java:637) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:98) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Display.filterEvent(Display.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2284) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java) at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:41) at java.lang.reflect.Method.invoke(Method.java:386) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706)
|
resolved fixed
|
791085b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T09:04:24Z
| 2004-05-18T08:46:40Z
|
org.eclipse.jdt.ui/ui
| |
62,603
|
Bug 62603 NPE in JavaTypeCompletionProcessor [refactoring]
|
I20040514 + ZRH plug-ins from 20040518 1. Have this java class: <pre> package org.eclipse.jdt.text.tests; import java.text.CharacterIterator; import junit.framework.Assert; import junit.framework.TestCase; import org.eclipse.jdt.internal.ui.text.WordNavigator; /** * @since 3.0 */ public class WordNavigationTest extends TestCase { private WordNavigator fWordNavigator; /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { fWordNavigator= new WordNavigator(); } public void testNext1() { CharacterIterator it= null; int pos= fWordNavigator.next(it); Assert.assertEquals(5, pos); } } </pre> 2. Select the two last lines of method testNext1 3. Press Alt+Shift+M to extract method -> get this: !ENTRY org.eclipse.ui 4 4 May 18, 2004 10:07:37.267 !MESSAGE The command for the key you pressed failed The command for the key you pressed failed Reason: !ENTRY org.eclipse.ui 4 0 May 18, 2004 10:07:37.295 !MESSAGE The command for the key you pressed failed !STACK 0 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor.setPackageFragment(JavaTypeCompletionProcessor.java:55) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.installParameterTypeContentAssist(ChangeParametersControl.java:640) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.addCellEditors(ChangeParametersControl.java:552) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.createParameterList(ChangeParametersControl.java:281) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:212) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:182) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.createControl(ExtractMethodInputPage.java:150) at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:533) at org.eclipse.jface.window.Window.create(Window.java:348) at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:924) at org.eclipse.jface.window.Window.open(Window.java:637) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:98) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Display.filterEvent(Display.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2284) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java) at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:41) at java.lang.reflect.Method.invoke(Method.java:386) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706)
|
resolved fixed
|
791085b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T09:04:24Z
| 2004-05-18T08:46:40Z
|
refactoring/org/eclipse/jdt/internal/ui/refactoring/contentassist/CUPositionCompletionProcessor.java
| |
62,603
|
Bug 62603 NPE in JavaTypeCompletionProcessor [refactoring]
|
I20040514 + ZRH plug-ins from 20040518 1. Have this java class: <pre> package org.eclipse.jdt.text.tests; import java.text.CharacterIterator; import junit.framework.Assert; import junit.framework.TestCase; import org.eclipse.jdt.internal.ui.text.WordNavigator; /** * @since 3.0 */ public class WordNavigationTest extends TestCase { private WordNavigator fWordNavigator; /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { fWordNavigator= new WordNavigator(); } public void testNext1() { CharacterIterator it= null; int pos= fWordNavigator.next(it); Assert.assertEquals(5, pos); } } </pre> 2. Select the two last lines of method testNext1 3. Press Alt+Shift+M to extract method -> get this: !ENTRY org.eclipse.ui 4 4 May 18, 2004 10:07:37.267 !MESSAGE The command for the key you pressed failed The command for the key you pressed failed Reason: !ENTRY org.eclipse.ui 4 0 May 18, 2004 10:07:37.295 !MESSAGE The command for the key you pressed failed !STACK 0 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor.setPackageFragment(JavaTypeCompletionProcessor.java:55) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.installParameterTypeContentAssist(ChangeParametersControl.java:640) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.addCellEditors(ChangeParametersControl.java:552) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.createParameterList(ChangeParametersControl.java:281) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:212) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:182) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.createControl(ExtractMethodInputPage.java:150) at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:533) at org.eclipse.jface.window.Window.create(Window.java:348) at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:924) at org.eclipse.jface.window.Window.open(Window.java:637) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:98) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Display.filterEvent(Display.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2284) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java) at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:41) at java.lang.reflect.Method.invoke(Method.java:386) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706)
|
resolved fixed
|
791085b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T09:04:24Z
| 2004-05-18T08:46:40Z
|
org.eclipse.jdt.ui/ui
| |
62,603
|
Bug 62603 NPE in JavaTypeCompletionProcessor [refactoring]
|
I20040514 + ZRH plug-ins from 20040518 1. Have this java class: <pre> package org.eclipse.jdt.text.tests; import java.text.CharacterIterator; import junit.framework.Assert; import junit.framework.TestCase; import org.eclipse.jdt.internal.ui.text.WordNavigator; /** * @since 3.0 */ public class WordNavigationTest extends TestCase { private WordNavigator fWordNavigator; /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { fWordNavigator= new WordNavigator(); } public void testNext1() { CharacterIterator it= null; int pos= fWordNavigator.next(it); Assert.assertEquals(5, pos); } } </pre> 2. Select the two last lines of method testNext1 3. Press Alt+Shift+M to extract method -> get this: !ENTRY org.eclipse.ui 4 4 May 18, 2004 10:07:37.267 !MESSAGE The command for the key you pressed failed The command for the key you pressed failed Reason: !ENTRY org.eclipse.ui 4 0 May 18, 2004 10:07:37.295 !MESSAGE The command for the key you pressed failed !STACK 0 java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at org.eclipse.jdt.internal.ui.refactoring.contentassist.JavaTypeCompletionProcessor.setPackageFragment(JavaTypeCompletionProcessor.java:55) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.installParameterTypeContentAssist(ChangeParametersControl.java:640) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.addCellEditors(ChangeParametersControl.java:552) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.createParameterList(ChangeParametersControl.java:281) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:212) at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl.<init>(ChangeParametersControl.java:182) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.createControl(ExtractMethodInputPage.java:150) at org.eclipse.ltk.internal.ui.refactoring.RefactoringWizardDialog2.createContents(RefactoringWizardDialog2.java:533) at org.eclipse.jface.window.Window.create(Window.java:348) at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:924) at org.eclipse.jface.window.Window.open(Window.java:637) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run(RefactoringWizardOpenOperation.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:98) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Display.filterEvent(Display.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2284) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java) at org.eclipse.swt.widgets.Composite.gtk_key_press_event(Composite.java) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:79) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:41) at java.lang.reflect.Method.invoke(Method.java:386) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706)
|
resolved fixed
|
791085b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T09:04:24Z
| 2004-05-18T08:46:40Z
|
refactoring/org/eclipse/jdt/internal/ui/refactoring/contentassist/JavaTypeCompletionProcessor.java
| |
62,612
|
Bug 62612 NPE in EclipsePreferences.internalGet(...)
|
I200405171219 + ZRH smoke plugin-export 20040518_1115 After start and shutdown of the Buildmeister runtime I found the following exception. It looks like getTextPreferenceKey() in AbstractAnnotationHover#getHoverInfo() at line 83 returned null. java.lang.NullPointerException at org.eclipse.core.internal.preferences.EclipsePreferences.internalGet(EclipsePreferences.java:479) at org.eclipse.core.internal.preferences.EclipsePreferences.get(EclipsePreferences.java:349) at org.eclipse.core.internal.preferences.PreferenceForwarder.contains(PreferenceForwarder.java:181) at org.eclipse.ui.plugin.AbstractUIPlugin$CompatibilityPreferenceStore.contains(AbstractUIPlugin.java:277) at org.eclipse.ui.texteditor.ChainedPreferenceStore.getVisibleStore(ChainedPreferenceStore.java:525) at org.eclipse.ui.texteditor.ChainedPreferenceStore.getBoolean(ChainedPreferenceStore.java:166) at org.eclipse.jdt.internal.ui.text.java.hover.AbstractAnnotationHover.getHoverInfo(AbstractAnnotationHover.java:83) at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo(BestMatchHover.java:102) at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo(JavaEditorTextHoverProxy.java:69) at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:161)
|
resolved fixed
|
5db3d51
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T09:43:26Z
| 2004-05-18T08:46:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.CollationElementIterator;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ISelectionValidator;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.link.LinkedModeModel;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension2;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextNavigationAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.util.IModifierConstants;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.ui.text.folding.IJavaFoldingStructureProvider;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.FoldingActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
import org.eclipse.jdt.internal.ui.search.MethodExitsFinder;
import org.eclipse.jdt.internal.ui.search.OccurrencesFinder;
import org.eclipse.jdt.internal.ui.text.CustomSourceInformationControl;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.JavaPresentationReconciler;
import org.eclipse.jdt.internal.ui.text.PreferencesAdapter;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaExpandHover;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider the selection provider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
// XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
JavaEditor.this.selectionChanged();
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/**
* Adapts an options {@link java.util.Map} to {@link org.eclipse.jface.preference.IPreferenceStore}.
* <p>
* This preference store is read-only i.e. write access
* throws an {@link java.lang.UnsupportedOperationException}.
* </p>
*
* @since 3.0
*/
private static class OptionsAdapter implements IPreferenceStore {
/**
* A property change event filter.
*/
public interface IPropertyChangeEventFilter {
/**
* Should the given event be filtered?
* @param event The property change event.
* @return <code>true</code> iff the given event should be filtered.
*/
public boolean isFiltered(PropertyChangeEvent event);
}
/**
* Property change listener. Listens for events in the options Map and
* fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
* on this adapter with arguments from the received event.
*/
private class PropertyChangeListener implements IPropertyChangeListener {
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent event) {
if (getFilter().isFiltered(event))
return;
if (event.getNewValue() == null)
fOptions.remove(event.getProperty());
else
fOptions.put(event.getProperty(), event.getNewValue());
firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
}
}
/** Listeners on this adapter */
private ListenerList fListeners= new ListenerList();
/** Listener on the adapted options Map */
private IPropertyChangeListener fListener= new PropertyChangeListener();
/** Adapted options Map */
private Map fOptions;
/** Preference store through which events are received. */
private IPreferenceStore fMockupPreferenceStore;
/** Property event filter. */
private IPropertyChangeEventFilter fFilter;
/**
* Initialize with the given options.
*
* @param options The options to wrap
* @param mockupPreferenceStore the mock-up preference store
* @param filter the property change filter
*/
public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
fMockupPreferenceStore= mockupPreferenceStore;
fOptions= options;
setFilter(filter);
}
/**
* {@inheritDoc}
*/
public void addPropertyChangeListener(IPropertyChangeListener listener) {
if (fListeners.size() == 0)
fMockupPreferenceStore.addPropertyChangeListener(fListener);
fListeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removePropertyChangeListener(IPropertyChangeListener listener) {
fListeners.remove(listener);
if (fListeners.size() == 0)
fMockupPreferenceStore.removePropertyChangeListener(fListener);
}
/**
* {@inheritDoc}
*/
public boolean contains(String name) {
return fOptions.containsKey(name);
}
/**
* {@inheritDoc}
*/
public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
((IPropertyChangeListener) listeners[i]).propertyChange(event);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(String name) {
boolean value= BOOLEAN_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null)
value= s.equals(TRUE);
return value;
}
/**
* {@inheritDoc}
*/
public boolean getDefaultBoolean(String name) {
return BOOLEAN_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDefaultDouble(String name) {
return DOUBLE_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public float getDefaultFloat(String name) {
return FLOAT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public int getDefaultInt(String name) {
return INT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public long getDefaultLong(String name) {
return LONG_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public String getDefaultString(String name) {
return STRING_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDouble(String name) {
double value= DOUBLE_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Double(s).doubleValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public float getFloat(String name) {
float value= FLOAT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Float(s).floatValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public int getInt(String name) {
int value= INT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Integer(s).intValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public long getLong(String name) {
long value= LONG_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Long(s).longValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public String getString(String name) {
String value= (String) fOptions.get(name);
if (value == null)
value= STRING_DEFAULT_DEFAULT;
return value;
}
/**
* {@inheritDoc}
*/
public boolean isDefault(String name) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean needsSaving() {
return !fOptions.isEmpty();
}
/**
* {@inheritDoc}
*/
public void putValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, String defaultObject) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setToDefault(String name) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* Returns the adapted options Map.
*
* @return Returns the adapted options Map.
*/
public Map getOptions() {
return fOptions;
}
/**
* Returns the mock-up preference store, events are received through this preference store.
* @return Returns the mock-up preference store.
*/
public IPreferenceStore getMockupPreferenceStore() {
return fMockupPreferenceStore;
}
/**
* Set the event filter to the given filter.
*
* @param filter The new filter.
*/
public void setFilter(IPropertyChangeEventFilter filter) {
fFilter= filter;
}
/**
* Returns the event filter.
*
* @return The event filter.
*/
public IPropertyChangeEventFilter getFilter() {
return fFilter;
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
((ITextViewerExtension4)sourceViewer).addTextPresentationListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fall back to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
*
* @param store the preference store
* @param key the key
* @param display the display
* @return the color or <code>null</code> if there is no such information available
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
fActiveRegion= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
// Invalidate ==> remove applied text presentation
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// Remove underline
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
try {
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, false);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
public void applyTextPresentation(TextPresentation textPresentation) {
if (fActiveRegion == null)
return;
IRegion region= textPresentation.getExtent();
if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// Underline
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
text.redrawRange(offset, length, false);
// Invalidate region ==> apply text presentation
fActiveRegion= region;
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
else
viewer.invalidateTextPresentation();
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != fKeyModifierMask) {
deactivate();
return;
}
fActive= true;
// removed for #25871
//
// ISourceViewer viewer= getSourceViewer();
// if (viewer == null)
// return;
//
// IRegion region= getCurrentTextRegion(viewer);
// if (region == null)
// return;
//
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != fKeyModifierMask) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
boolean wasActive= fCursor != null;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != fKeyModifierMask)
return;
// modifier was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fActive && fActiveRegion != null) {
fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
try {
event.getDocument().addPosition(fRememberedPosition);
} catch (BadLocationException x) {
fRememberedPosition= null;
}
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
if (fRememberedPosition != null) {
if (!fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
} else {
fActiveRegion= null;
fRememberedPosition= null;
deactivate();
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(fActiveRegion);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action behaves in two different ways: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*
* @param resourceBundle the resource bundle
* @param prefix the prefix
* @param textOperationAction the text operation action
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
if (extension4.moveFocusToWidgetToken())
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset, true);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
/**
* This action implements smart home.
*
* Instead of going to the start of a line it does the following:
*
* - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account.
* - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line
* - if the caret is at the beginning of the line see first case.
*
* @since 3.0
*/
protected class SmartLineStartAction extends LineStartAction {
/**
* Creates a new smart line start action
*
* @param textWidget the styled text widget
* @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected
*/
public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
super(textWidget, doSelect);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String)
*/
protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
String type= IDocument.DEFAULT_CONTENT_TYPE;
try {
type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
} catch (BadLocationException exception) {
// Should not happen
}
int index= super.getLineStartPosition(document, line, length, offset);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
} else {
if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
index++;
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
}
return index;
}
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected abstract class NextSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new next sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected NextSubWordAction(int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Check whether right hand character of caret is valid identifier start
if (Character.isJavaIdentifierStart(document.getChar(position))) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final String buffer= document.get(position, region.getOffset() + region.getLength() - position);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
do {
// Check whether we reached end of word
offset= iterator.getOffset();
if (!Character.isJavaIdentifierPart(document.getChar(position + offset)))
throw new BadLocationException();
// Test next characters
order= iterator.next();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check for leading underscores
position += offset;
if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) {
setCaretPosition(position);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected class NavigateNextSubWordAction extends NextSubWordAction {
/**
* Creates a new navigate next sub-word action.
*/
public NavigateNextSubWordAction() {
super(ST.WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the next sub-word.
*
* @since 3.0
*/
protected class DeleteNextSubWordAction extends NextSubWordAction {
/**
* Creates a new delete next sub-word action.
*/
public DeleteNextSubWordAction() {
super(ST.DELETE_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the next sub-word.
*
* @since 3.0
*/
protected class SelectNextSubWordAction extends NextSubWordAction {
/**
* Creates a new select next sub-word action.
*/
public SelectNextSubWordAction() {
super(ST.SELECT_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected abstract class PreviousSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new previous sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected PreviousSubWordAction(final int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1;
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Ignore trailing white spaces
char character= document.getChar(position);
while (position > 0 && Character.isWhitespace(character)) {
--position;
character= document.getChar(position);
}
// Check whether left hand character of caret is valid identifier part
if (Character.isJavaIdentifierPart(character)) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
iterator.setOffset(buffer.length() - 1);
do {
// Check whether we reached begin of word or single upper-case start
offset= iterator.getOffset();
character= document.getChar(region.getOffset() + offset);
if (!Character.isJavaIdentifierPart(character))
throw new BadLocationException();
else if (Character.isUpperCase(character)) {
++offset;
break;
}
// Test next characters
order= iterator.previous();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check left character for multiple upper-case characters
position= position - buffer.length() + offset - 1;
character= document.getChar(position);
while (position >= 0 && Character.isUpperCase(character))
character= document.getChar(--position);
setCaretPosition(position + 1);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new navigate previous sub-word action.
*/
public NavigatePreviousSubWordAction() {
super(ST.WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the previous sub-word.
*
* @since 3.0
*/
protected class DeletePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new delete previous sub-word action.
*/
public DeletePreviousSubWordAction() {
super(ST.DELETE_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the previous sub-word.
*
* @since 3.0
*/
protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new select previous sub-word action.
*/
public SelectPreviousSubWordAction() {
super(ST.SELECT_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Format element action to format the enclosing java element.
* <p>
* The format element action works as follows:
* <ul>
* <li>If there is no selection and the caret is positioned on a Java element,
* only this element is formatted. If the element has some accompanying comment,
* then the comment is formatted as well.</li>
* <li>If the selection spans one or more partitions of the document, then all
* partitions covered by the selection are entirely formatted.</li>
* <p>
* Partitions at the end of the selection are not completed, except for comments.
*
* @since 3.0
*/
protected class FormatElementAction extends Action {
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
if (viewer.isEditable()) {
final Point selection= viewer.rememberSelection();
try {
viewer.setRedraw(false);
final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x, true);
if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
try {
final IJavaElement element= getElementAt(selection.x, true);
if (element != null && element.exists()) {
final int kind= element.getElementType();
if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
final ISourceReference reference= (ISourceReference)element;
final ISourceRange range= reference.getSourceRange();
if (range != null) {
viewer.setSelectedRange(range.getOffset(), range.getLength());
viewer.doOperation(ISourceViewer.FORMAT);
}
}
}
} catch (JavaModelException exception) {
// Should not happen
}
} else {
viewer.setSelectedRange(selection.x, 1);
viewer.doOperation(ISourceViewer.FORMAT);
}
} catch (BadLocationException exception) {
// Can not happen
} finally {
viewer.setRedraw(true);
viewer.restoreSelection();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
if (fMarkOccurrenceAnnotations && isActivePart()) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/**
* Indicates whether this editor is about to update any annotation views.
* @since 3.0
*/
private boolean fIsUpdatingAnnotationViews= false;
/**
* The marker that served as last target for a goto marker request.
* @since 3.0
*/
private IMarker fLastMarkerTarget= null;
protected CompositeActionGroup fActionGroups;
/**
* The action group for folding.
*
* @since 3.0
*/
private FoldingActionGroup fFoldingGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Holds the current occurrence annotations.
* @since 3.0
*/
private Annotation[] fOccurrenceAnnotations= null;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* Tells whether the occurrence annotations are sticky
* i.e. whether they stay even if there's no valid Java
* element at the current caret position.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fStickyOccurrenceAnnotations;
/**
* Tells whether to mark type occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkTypeOccurrences;
/**
* Tells whether to mark method occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodOccurrences;
/**
* Tells whether to mark constant occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkConstantOccurrences;
/**
* Tells whether to mark field occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkFieldOccurrences;
/**
* Tells whether to mark local variable occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkLocalVariableypeOccurrences;
/**
* Tells whether to mark exception occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkExceptionOccurrences;
/**
* Tells whether to mark method exits in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodExitPoints;
/**
*
*/
private ISelection fForcedMarkOccurrencesSelection;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
private ISelectionListenerWithAST fPostSelectionListenerWithAST;
private OccurrencesFinderJob fOccurrencesFinderJob;
/**
* This editor's projection support
* @since 3.0
*/
private ProjectionSupport fProjectionSupport;
/**
* This editor's projection model updater
* @since 3.0
*/
private IJavaFoldingStructureProvider fProjectionModelUpdater;
/**
* The override and implements indicator manager for this editor.
* @since 3.0
*/
protected OverrideIndicatorManager fOverrideIndicatorManager;
/**
* Semantic highlighting manager
* @since 3.0
*/
private SemanticHighlightingManager fSemanticManager;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement.
*
* @param element the java element
* @return the corresponding Java element
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*
* @param page the Java outline page
* @param input the editor input
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
*/
protected void initializeKeyBindingScopes() {
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
*/
protected void initializeEditor() {
IPreferenceStore store= createCombinedPreferenceStore(null);
setPreferenceStore(store);
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
fMarkTypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
fMarkMethodOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
fMarkConstantOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
fMarkFieldOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
fMarkLocalVariableypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
fMarkExceptionOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
fMarkMethodExitPoints= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore());
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
return ((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
}
/**
* Creates and returns the preference store for this Java editor with the given input.
*
* @param input The editor input for which to create the preference store
* @return the preference store for this editor
*
* @since 3.0
*/
private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
List stores= new ArrayList(3);
IJavaProject project= EditorUtility.getJavaProject(input);
if (project != null)
stores.add(new OptionsAdapter(project.getOptions(false), JavaPlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() {
public boolean isFiltered(PropertyChangeEvent event) {
IJavaElement inputJavaElement= getInputJavaElement();
IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
if (javaProject == null)
return true;
return !javaProject.getProject().equals(event.getSource());
}
}));
stores.add(JavaPlugin.getDefault().getPreferenceStore());
stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
stores.add(EditorsUI.getPreferenceStore());
return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
}
/**
* Sets the outliner's context menu ID.
*
* @param menuId the menu ID
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*
* @return returns this editor's standard action group
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*
* @return the created Java outline page
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
if (fProjectionSupport != null) {
Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
if (adapter != null)
return adapter;
}
return super.getAdapter(required);
}
/**
* React to changed selection.
*
* @since 3.0
*/
protected void selectionChanged() {
if (getSelectionProvider() == null)
return;
ISourceReference element= computeHighlightRangeSourceReference();
if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
synchronizeOutlinePage(element);
setSelection(element, false);
updateStatusLine();
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
if (getSelectionProvider() == null)
return;
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
// PR 39995: [navigation] Forward history cleared after going back in navigation history:
// mark only in navigation history if the cursor is being moved (which it isn't if
// this is called from a PostSelectionEvent that should only update the magnet)
if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0))
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= null;
if (reference instanceof ILocalVariable) {
IJavaElement je= ((ILocalVariable)reference).getParent();
if (je instanceof ISourceReference)
range= ((ISourceReference)je).getSourceRange();
} else
range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof ILocalVariable) {
range= ((ILocalVariable)reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set highlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
}
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(offset, length));
} else {
resetHighlightRange();
}
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
*/
protected void handleElementContentReplaced() {
super.handleElementContentReplaced();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
ISourceViewer sourceViewer= getSourceViewer();
if (!(sourceViewer instanceof ISourceViewerExtension2)) {
setPreferenceStore(createCombinedPreferenceStore(input));
internalDoSetInput(input);
return;
}
// uninstall & unregister preference store listener
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
getSourceViewerDecorationSupport(sourceViewer).uninstall();
((ISourceViewerExtension2)sourceViewer).unconfigure();
setPreferenceStore(createCombinedPreferenceStore(input));
// install & register preference store listener
sourceViewer.configure(getSourceViewerConfiguration());
getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
internalDoSetInput(input);
}
private void internalDoSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
if (isShowingOverrideIndicators())
installOverrideIndicator(true);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
* @since 3.0
*/
protected void setPreferenceStore(IPreferenceStore store) {
super.setPreferenceStore(store);
if (getSourceViewerConfiguration() instanceof JavaSourceViewerConfiguration) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
}
if (getSourceViewer() instanceof JavaSourceViewer)
((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.uninstall();
fProjectionModelUpdater= null;
}
if (fProjectionSupport != null) {
fProjectionSupport.dispose();
fProjectionSupport= null;
}
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
uninstallOccurrencesFinder();
uninstallOverrideIndicator();
uninstallSemanticHighlighting();
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
fFoldingGroup= new FoldingActionGroup(this, getViewer());
ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
action= new FormatElementAction();
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
setAction("QuickFormat", action); //$NON-NLS-1$
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
// add annotation actions
action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", action); //$NON-NLS-1$
// replace cut/copy paste actions with a version that implement 'add imports on paste'
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$
setAction(ITextEditorActionConstants.CUT, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Copy.", this, ITextOperationTarget.COPY); //$NON-NLS-1$
setAction(ITextEditorActionConstants.COPY, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
setAction(ITextEditorActionConstants.PASTE, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue())
selectionChanged();
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
enableOverwriteMode(!disable.booleanValue());
}
return;
}
if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
if (!fMarkOccurrenceAnnotations)
uninstallOccurrencesFinder();
else
installOccurrencesFinder();
}
}
return;
}
if (PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkTypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkConstantOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkFieldOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkLocalVariableypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkExceptionOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodExitPoints= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fStickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED.equals(property)) {
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
else
uninstallSemanticHighlighting();
return;
}
((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
if (affectsOverrideIndicatorAnnotations(event)) {
if (isShowingOverrideIndicators()) {
if (fOverrideIndicatorManager == null)
installOverrideIndicator(false);
} else {
if (fOverrideIndicatorManager != null)
uninstallOverrideIndicator();
}
return;
}
if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
if (sourceViewer instanceof ProjectionViewer) {
ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.uninstall();
// either freshly enabled or provider changed
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.install(this, projectionViewer);
}
}
return;
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
* @since 3.0
*/
protected void initializeViewerColors(ISourceViewer viewer) {
// is handled by JavaSourceViewer
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength(), false);
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param widgetLineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
boolean isFoldingEnabled() {
return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
}
});
fProjectionSupport.install();
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.install(this, projectionViewer);
if (isFoldingEnabled())
projectionViewer.doOperation(ProjectionViewer.TOGGLE);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
enableOverwriteMode(false);
if (fMarkOccurrenceAnnotations)
installOccurrencesFinder();
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews) {
super.gotoMarker(marker);
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$
method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set status line
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinderJob extends Job implements IDocumentListener {
private IDocument fDocument;
private ISelection fSelection;
private ISelectionValidator fPostSelectionValidator;
private boolean fCancelled= false;
private IProgressMonitor fProgressMonitor;
private Position[] fPositions;
public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) {
super(JavaEditorMessages.getString("JavaEditor.markOccurrences.job.name")); //$NON-NLS-1$
fDocument= document;
fSelection= selection;
fPositions= positions;
fDocument.addDocumentListener(this);
if (getSelectionProvider() instanceof ISelectionValidator)
fPostSelectionValidator= (ISelectionValidator)getSelectionProvider();
}
private boolean isCancelled() {
return fCancelled || fProgressMonitor.isCanceled()
|| fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
|| LinkedModeModel.hasInstalledModel(fDocument);
}
/*
* @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus run(IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
try {
if (isCancelled())
return Status.CANCEL_STATUS;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return Status.CANCEL_STATUS;
IDocument document= textViewer.getDocument();
if (document == null)
return Status.CANCEL_STATUS;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return Status.CANCEL_STATUS;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return Status.CANCEL_STATUS;
// Add occurrence annotations
int length= fPositions.length;
Map annotationMap= new HashMap(length);
for (int i= 0; i < length; i++) {
if (isCancelled())
return Status.CANCEL_STATUS;
String message;
Position position= fPositions[i];
// Create & add annotation
try {
message= document.get(position.offset, position.length);
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
position);
}
if (isCancelled())
return Status.CANCEL_STATUS;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
} else {
removeOccurrenceAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
} finally {
fDocument.removeDocumentListener(this);
}
return Status.OK_STATUS;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fCancelled= true;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @param selection the text selection
* @param astRoot the compilation unit AST
* @since 3.0
*/
protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) {
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.cancel();
if (!fMarkOccurrenceAnnotations)
return;
if (astRoot == null || selection == null)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
List matches= new ArrayList();
String message;
if (fMarkExceptionOccurrences || fMarkTypeOccurrences) {
ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= exceptionFinder.perform();
}
}
if (matches.size() == 0 && fMarkMethodExitPoints) {
MethodExitsFinder finder= new MethodExitsFinder();
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= finder.perform();
}
}
if (matches.size() == 0) {
ASTNode node= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
if (!(node instanceof Name)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
IBinding binding= ((Name)node).resolveBinding();
if (binding == null && fStickyOccurrenceAnnotations)
return;
if (!markOccurrencesOfType(binding)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
// Find the matches && extract positions so we can forget the AST
OccurrencesFinder finder = new OccurrencesFinder(binding);
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null)
matches= finder.perform();
} else if (!fMarkExceptionOccurrences) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
Position[] positions= new Position[matches.size()];
int i= 0;
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode currentNode= (ASTNode)each.next();
positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
}
fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions, selection);
//fOccurrencesFinderJob.setPriority(Job.DECORATE);
//fOccurrencesFinderJob.setSystem(true);
//fOccurrencesFinderJob.schedule();
fOccurrencesFinderJob.run(new NullProgressMonitor());
}
protected void installOccurrencesFinder() {
fMarkOccurrenceAnnotations= true;
fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
updateOccurrenceAnnotations(selection, astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
if (getSelectionProvider() != null) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
}
protected void uninstallOccurrencesFinder() {
fMarkOccurrenceAnnotations= false;
if (fOccurrencesFinderJob != null) {
fOccurrencesFinderJob.cancel();
fOccurrencesFinderJob= null;
}
if (fPostSelectionListenerWithAST != null) {
SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
fPostSelectionListenerWithAST= null;
}
removeOccurrenceAnnotations();
}
protected boolean isMarkingOccurrences() {
return fMarkOccurrenceAnnotations;
}
boolean markOccurrencesOfType(IBinding binding) {
if (binding == null)
return false;
int kind= binding.getKind();
if (fMarkTypeOccurrences && kind == IBinding.TYPE)
return true;
if (fMarkMethodOccurrences && kind == IBinding.METHOD)
return true;
if (kind == IBinding.VARIABLE) {
IVariableBinding variableBinding= (IVariableBinding)binding;
if (variableBinding.isField()) {
boolean isConstant= (variableBinding.getModifiers() & (IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL)) != 0;
if (isConstant)
return fMarkConstantOccurrences;
else
return fMarkFieldOccurrences;
}
return fMarkLocalVariableypeOccurrences;
}
return false;
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
protected void uninstallOverrideIndicator() {
if (fOverrideIndicatorManager != null) {
fOverrideIndicatorManager.removeAnnotations();
fOverrideIndicatorManager= null;
}
}
protected void installOverrideIndicator(boolean waitForReconcilation) {
uninstallOverrideIndicator();
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
IJavaElement inputElement= getInputJavaElement();
if (model == null || inputElement == null)
return;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast);
}
/**
* Tells whether override indicators are shown.
*
* @return <code>true</code> if the override indicators are shown
* @since 3.0
*/
protected boolean isShowingOverrideIndicators() {
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(preference.getHighlightPreferenceKey())
|| store.getBoolean(preference.getVerticalRulerPreferenceKey())
|| store.getBoolean(preference.getOverviewRulerPreferenceKey())
|| store.getBoolean(preference.getTextPreferenceKey());
}
/**
* Determines whether the preference change encoded by the given event
* changes the override indication.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a change
* @since 3.0
*/
protected boolean affectsOverrideIndicatorAnnotations(PropertyChangeEvent event) {
String key= event.getProperty();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
if (key == null || preference == null)
return false;
return key.equals(preference.getHighlightPreferenceKey())
|| key.equals(preference.getVerticalRulerPreferenceKey())
|| key.equals(preference.getOverviewRulerPreferenceKey())
|| key.equals(preference.getTextPreferenceKey());
}
/**
* @return <code>true</code> if Semantic Highlighting is enabled.
*
* @since 3.0
*/
private boolean isSemanticHighlightingEnabled() {
return getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED);
}
/**
* Install Semantic Highlighting.
*
* @since 3.0
*/
private void installSemanticHighlighting() {
if (fSemanticManager == null) {
fSemanticManager= new SemanticHighlightingManager();
JavaPresentationReconciler backgroundPresentationReconciler= (JavaPresentationReconciler) getSourceViewerConfiguration().getPresentationReconciler(getSourceViewer());
fSemanticManager.install(this, (JavaSourceViewer) getSourceViewer(), JavaPlugin.getDefault().getJavaTextTools().getColorManager(), getPreferenceStore(), backgroundPresentationReconciler);
}
}
/**
* Uninstall Semantic Highlighting.
*
* @since 3.0
*/
private void uninstallSemanticHighlighting() {
if (fSemanticManager != null) {
fSemanticManager.uninstall();
fSemanticManager= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
/**
* Returns the signed current selection.
* The length will be negative if the resulting selection
* is right-to-left (RtoL).
* <p>
* The selection offset is model based.
* </p>
*
* @param sourceViewer the source viewer
* @return a region denoting the current signed selection, for a resulting RtoL selections length is < 0
*/
protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
StyledText text= sourceViewer.getTextWidget();
Point selection= text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
selection.x= selection.x + selection.y;
selection.y= -selection.y;
}
selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x);
return new Region(selection.x, selection.y);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= EditorsUI.getPluginPreferences();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
*/
protected void createNavigationActions() {
super.createNavigationActions();
final StyledText textWidget= getSourceViewer().getTextWidget();
IAction action= new SmartLineStartAction(textWidget, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
setAction(ITextEditorActionDefinitionIds.LINE_START, action);
action= new SmartLineStartAction(textWidget, true);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
action= new NavigatePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
action= new NavigateNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
action= new DeletePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
action= new DeleteNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
action= new SelectPreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
action= new SelectNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
*/
protected CompositeRuler createCompositeRuler() {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
return super.createCompositeRuler();
CompositeRuler ruler= new CompositeRuler();
AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
// for now: just invoke ruler double click action
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
}
private void triggerAction(String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
// hack to propagate line change
if (action instanceof ISelectionListener) {
((ISelectionListener)action).selectionChanged(null, null);
}
if (action.isEnabled())
action.run();
}
}
}));
ruler.addDecorator(0, column);
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isPrefQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/**
* Returns the folding action group, or <code>null</code> if there is none.
*
* @return the folding action group, or <code>null</code> if there is none
* @since 3.0
*/
protected FoldingActionGroup getFoldingActionGroup() {
return fFoldingGroup;
}
}
|
62,612
|
Bug 62612 NPE in EclipsePreferences.internalGet(...)
|
I200405171219 + ZRH smoke plugin-export 20040518_1115 After start and shutdown of the Buildmeister runtime I found the following exception. It looks like getTextPreferenceKey() in AbstractAnnotationHover#getHoverInfo() at line 83 returned null. java.lang.NullPointerException at org.eclipse.core.internal.preferences.EclipsePreferences.internalGet(EclipsePreferences.java:479) at org.eclipse.core.internal.preferences.EclipsePreferences.get(EclipsePreferences.java:349) at org.eclipse.core.internal.preferences.PreferenceForwarder.contains(PreferenceForwarder.java:181) at org.eclipse.ui.plugin.AbstractUIPlugin$CompatibilityPreferenceStore.contains(AbstractUIPlugin.java:277) at org.eclipse.ui.texteditor.ChainedPreferenceStore.getVisibleStore(ChainedPreferenceStore.java:525) at org.eclipse.ui.texteditor.ChainedPreferenceStore.getBoolean(ChainedPreferenceStore.java:166) at org.eclipse.jdt.internal.ui.text.java.hover.AbstractAnnotationHover.getHoverInfo(AbstractAnnotationHover.java:83) at org.eclipse.jdt.internal.ui.text.java.hover.BestMatchHover.getHoverInfo(BestMatchHover.java:102) at org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverProxy.getHoverInfo(JavaEditorTextHoverProxy.java:69) at org.eclipse.jface.text.TextViewerHoverManager$4.run(TextViewerHoverManager.java:161)
|
resolved fixed
|
5db3d51
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T09:43:26Z
| 2004-05-18T08:46:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/AbstractAnnotationHover.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java.hover;
import java.util.Iterator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator;
import org.eclipse.jdt.internal.ui.text.HTMLPrinter;
/**
* Abstract super class for annotation hovers.
*
* @since 3.0
*/
public abstract class AbstractAnnotationHover extends AbstractJavaEditorTextHover {
private IPreferenceStore fStore= JavaPlugin.getDefault().getCombinedPreferenceStore();
private DefaultMarkerAnnotationAccess fAnnotationAccess= new DefaultMarkerAnnotationAccess();
private boolean fAllAnnotations;
public AbstractAnnotationHover(boolean allAnnotations) {
fAllAnnotations= allAnnotations;
}
/*
* Formats a message as HTML text.
*/
private String formatMessage(String message) {
StringBuffer buffer= new StringBuffer();
HTMLPrinter.addPageProlog(buffer);
HTMLPrinter.addParagraph(buffer, HTMLPrinter.convertToHTMLContent(message));
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
/*
* @see ITextHover#getHoverInfo(ITextViewer, IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
if (getEditor() == null)
return null;
IDocumentProvider provider= JavaPlugin.getDefault().getCompilationUnitDocumentProvider();
IAnnotationModel model= provider.getAnnotationModel(getEditor().getEditorInput());
if (model != null) {
Iterator e= new JavaAnnotationIterator(model, true, fAllAnnotations);
int layer= -1;
String message= null;
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
AnnotationPreference preference= getAnnotationPreference(a);
if (preference == null || !(fStore.getBoolean(preference.getTextPreferenceKey()) || (preference.getHighlightPreferenceKey() != null && fStore.getBoolean(preference.getHighlightPreferenceKey()))))
continue;
Position p= model.getPosition(a);
int l= fAnnotationAccess.getLayer(a);
if (l > layer && p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
String msg= a.getText();
if (msg != null && msg.trim().length() > 0) {
message= msg;
layer= l;
}
}
}
if (layer > -1)
return formatMessage(message);
}
return null;
}
/*
* @see IJavaEditorTextHover#setEditor(IEditorPart)
*/
public void setEditor(IEditorPart editor) {
if (editor instanceof CompilationUnitEditor)
super.setEditor(editor);
else
super.setEditor(null);
}
/**
* Returns the annotation preference for the given annotation.
*
* @param annotation the annotation
* @return the annotation preference or <code>null</code> if none
*/
private AnnotationPreference getAnnotationPreference(Annotation annotation) {
if (annotation.isMarkedDeleted())
return null;
return EditorsUI.getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
}
}
|
62,591
|
Bug 62591 [misc] Javadoc view keeps prompting about HTML widget
|
Dear Javadoc view, I was pleased the first time you warned me about the lack of an HTML widget on my platform. However, now that you've told me about it 100 times, I think it's time you and I stop talking about this problem. Thanks, Jared Linux-GTK
|
resolved fixed
|
58f9f0a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T10:58:17Z
| 2004-05-18T06:00:00Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/JavadocView.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.infoviews;
import java.io.Reader;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTError;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocAccess;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.text.HTMLPrinter;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.javadoc.JavaDoc2HTMLTextReader;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* View which shows Javadoc for a given Java element.
*
* @since 3.0
*/
public class JavadocView extends AbstractInfoView {
/** Flags used to render a label in the text widget. */
private static final int LABEL_FLAGS= JavaElementLabels.ALL_FULLY_QUALIFIED
| JavaElementLabels.M_PRE_RETURNTYPE | JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_EXCEPTIONS
| JavaElementLabels.F_PRE_TYPE_SIGNATURE;
/** The HTML widget. */
private Browser fBrowser;
/** The text widget. */
private StyledText fText;
/** The information presenter. */
private DefaultInformationControl.IInformationPresenter fPresenter;
/** The text presentation. */
private TextPresentation fPresentation= new TextPresentation();
/** The select all action */
private SelectAllAction fSelectAllAction;
private boolean fIsUsingBrowserWidget;
/**
* The Javadoc view's select all action.
*/
private static class SelectAllAction extends Action {
/** The control. */
private Control fControl;
/** The selection provider. */
private SelectionProvider fSelectionProvider;
/**
* Creates the action.
*
* @param control the widget
* @param selectionProvider the selection provider
*/
public SelectAllAction(Control control, SelectionProvider selectionProvider) {
super("selectAll"); //$NON-NLS-1$
Assert.isNotNull(control);
Assert.isNotNull(selectionProvider);
fControl= control;
fSelectionProvider= selectionProvider;
setText(InfoViewMessages.getString("SelectAllAction.label")); //$NON-NLS-1$
setToolTipText(InfoViewMessages.getString("SelectAllAction.tooltip")); //$NON-NLS-1$
setDescription(InfoViewMessages.getString("SelectAllAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IAbstractTextEditorHelpContextIds.SELECT_ALL_ACTION);
}
/**
* Selects all in the view.
*/
public void run() {
if (fControl instanceof StyledText)
((StyledText)fControl).selectAll();
else {
// FIXME, see
// ((Browser)fControl).selectAll();
fSelectionProvider.fireSelectionChanged();
}
}
}
/**
* The Javadoc view's selection provider.
*/
private static class SelectionProvider implements ISelectionProvider {
/** The selection changed listeners. */
private ListenerList fListeners= new ListenerList();
/** The widget. */
private Control fControl;
/**
* Creates a new selection provider.
*
* @param control the widget
*/
public SelectionProvider(Control control) {
Assert.isNotNull(control);
fControl= control;
if (fControl instanceof StyledText) {
((StyledText)fControl).addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fireSelectionChanged();
}
});
} else {
// FIXME, see bug
// ((Browser)fControl).addSelectionListener(new SelectionAdapter() {
// public void widgetSelected(SelectionEvent e) {
// fireSelectionChanged();
// }
// });
}
}
/**
* Sends a selection changed event to all listeners.
*/
public void fireSelectionChanged() {
ISelection selection= getSelection();
SelectionChangedEvent event= new SelectionChangedEvent(this, selection);
Object[] selectionChangedListeners= fListeners.getListeners();
for (int i= 0; i < selectionChangedListeners.length; i++)
((ISelectionChangedListener)selectionChangedListeners[i]).selectionChanged(event);
}
/*
* @see org.eclipse.jface.viewers.ISelectionProvider#addSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
fListeners.add(listener);
}
/*
* @see org.eclipse.jface.viewers.ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fControl instanceof StyledText) {
IDocument document= new Document(((StyledText)fControl).getSelectionText());
return new TextSelection(document, 0, document.getLength());
} else {
// FIXME, see bug
return StructuredSelection.EMPTY;
}
}
/*
* @see org.eclipse.jface.viewers.ISelectionProvider#removeSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
fListeners.remove(listener);
}
/*
* @see org.eclipse.jface.viewers.ISelectionProvider#setSelection(org.eclipse.jface.viewers.ISelection)
*/
public void setSelection(ISelection selection) {
// not supported
}
}
/*
* @see AbstractInfoView#internalCreatePartControl(Composite)
*/
protected void internalCreatePartControl(Composite parent) {
try {
fBrowser= new Browser(parent, SWT.NONE);
fIsUsingBrowserWidget= true;
} catch (SWTError er) {
/* The Browser widget throws an SWTError if it fails to
* instantiate properly. Application code should catch
* this SWTError and disable any feature requiring the
* Browser widget.
* Platform requirements for the SWT Browser widget are available
* from the SWT FAQ web site.
*/
String title= InfoViewMessages.getString("JavadocView.error.noBrowser.title"); //$NON-NLS-1$
String message= InfoViewMessages.getString("JavadocView.error.noBrowser.message"); //$NON-NLS-1$
MessageDialog.openError(parent.getShell(), title, message);
fText= new StyledText(parent, SWT.V_SCROLL | SWT.H_SCROLL);
fIsUsingBrowserWidget= false;
fText.setEditable(false);
fPresenter= new HTMLTextPresenter(false);
fText.addControlListener(new ControlAdapter() {
/*
* @see org.eclipse.swt.events.ControlAdapter#controlResized(org.eclipse.swt.events.ControlEvent)
*/
public void controlResized(ControlEvent e) {
setInput(fText.getText());
}
});
}
getViewSite().setSelectionProvider(new SelectionProvider(getControl()));
}
/*
* @see AbstractInfoView#createActions()
*/
protected void createActions() {
super.createActions();
fSelectAllAction= new SelectAllAction(getControl(), (SelectionProvider)getSelectionProvider());
}
/*
* @see AbstractInfoView#setForeground(Color)
*/
protected void setForeground(Color color) {
getControl().setForeground(color);
}
/*
* @see AbstractInfoView#setBackground(Color)
*/
protected void setBackground(Color color) {
getControl().setBackground(color);
}
/*
* @see AbstractInfoView#internalDispose()
*/
protected void internalDispose() {
fText= null;
fBrowser= null;
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
getControl().setFocus();
}
/*
* @see AbstractInfoView#computeInput(Object)
*/
protected Object computeInput(Object input) {
if (getControl() == null || ! (input instanceof IJavaElement))
return null;
IJavaElement je= (IJavaElement)input;
String javadocHtml= null;
if (je.getElementType() == IJavaElement.COMPILATION_UNIT) {
try {
javadocHtml= getJavadocHtml(((ICompilationUnit)je).getTypes());
} catch (JavaModelException ex) {
return null;
}
} else
javadocHtml= getJavadocHtml(new IJavaElement[] { je });
return javadocHtml;
}
/*
* @see AbstractInfoView#setInput(Object)
*/
protected void setInput(Object input) {
String javadocHtml= (String)input;
if (fIsUsingBrowserWidget) {
fBrowser.setText(javadocHtml);
} else {
fPresentation.clear();
Rectangle size= fText.getClientArea();
try {
javadocHtml= fPresenter.updatePresentation(getSite().getShell().getDisplay(), javadocHtml, fPresentation, size.width, size.height);
} catch (IllegalArgumentException ex) {
// the javadoc might no longer be valid
return;
}
fText.setText(javadocHtml);
TextPresentation.applyTextPresentation(fPresentation, fText);
}
}
/**
* Returns the Javadoc in HTML format.
*
* @param result the Java elements for which to get the Javadoc
* @return a string with the Javadoc in HTML format.
*/
private String getJavadocHtml(IJavaElement[] result) {
StringBuffer buffer= new StringBuffer();
int nResults= result.length;
if (nResults == 0)
return null;
if (nResults > 1) {
for (int i= 0; i < result.length; i++) {
HTMLPrinter.startBulletList(buffer);
IJavaElement curr= result[i];
if (curr instanceof IMember)
HTMLPrinter.addBullet(buffer, getInfoText((IMember) curr));
HTMLPrinter.endBulletList(buffer);
}
} else {
IJavaElement curr= result[0];
if (curr instanceof IMember) {
IMember member= (IMember) curr;
// HTMLPrinter.addSmallHeader(buffer, getInfoText(member));
Reader reader;
try {
reader= JavaDocAccess.getJavaDoc(member, true);
} catch (JavaModelException ex) {
return null;
}
if (reader != null) {
HTMLPrinter.addParagraph(buffer, new JavaDoc2HTMLTextReader(reader));
}
}
}
if (buffer.length() > 0) {
HTMLPrinter.insertPageProlog(buffer, 0);
HTMLPrinter.addPageEpilog(buffer);
return buffer.toString();
}
return null;
}
/**
* Gets the label for the given member.
*
* @param member the Java member
* @return a string containing the member's label
*/
private String getInfoText(IMember member) {
return JavaElementLabels.getElementLabel(member, LABEL_FLAGS);
}
/*
* @see org.eclipse.jdt.internal.ui.infoviews.AbstractInfoView#isIgnoringEqualInput()
* @since 3.0
*/
protected boolean isIgnoringEqualInput() {
return false;
}
/*
* @see AbstractInfoView#findSelectedJavaElement(IWorkbenchPart)
*/
protected IJavaElement findSelectedJavaElement(IWorkbenchPart part, ISelection selection) {
IJavaElement element;
try {
element= super.findSelectedJavaElement(part, selection);
if (element == null && part instanceof JavaEditor && selection instanceof ITextSelection) {
JavaEditor editor= (JavaEditor)part;
ITextSelection textSelection= (ITextSelection)selection;
IDocumentProvider documentProvider= editor.getDocumentProvider();
if (documentProvider == null)
return null;
IDocument document= documentProvider.getDocument(editor.getEditorInput());
if (document == null)
return null;
ITypedRegion typedRegion= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, textSelection.getOffset(), false);
if (IJavaPartitions.JAVA_DOC.equals(typedRegion.getType()))
return TextSelectionConverter.getElementAtOffset((JavaEditor)part, textSelection);
else
return null;
} else
return element;
} catch (JavaModelException e) {
return null;
} catch (BadLocationException e) {
return null;
}
}
/*
* @see org.eclipse.jface.action.IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
public void menuAboutToShow(IMenuManager menu) {
super.menuAboutToShow(menu);
menu.add(fSelectAllAction);
}
/*
* @see AbstractInfoView#fillActionBars(IActionBars)
*/
protected void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction);
}
/*
* @see AbstractInfoView#getControl()
*/
protected Control getControl() {
if (fIsUsingBrowserWidget)
return fBrowser;
else
return fText;
}
}
|
61,866
|
Bug 61866 ConcurrentModificationException in UndoCollector/AbstractDocument
|
I20040511 (4pm) I found this in the log allthough I didn't notice any problems during editing Java files. I'm not sure if jface.text is Text or UI component. Please reassign if necessary. !ENTRY org.eclipse.ui 4 4 Mai 12, 2004 10:52:27.500 !MESSAGE Unhandled event loop exception !ENTRY org.eclipse.ui 4 0 Mai 12, 2004 10:52:27.500 !MESSAGE java.util.ConcurrentModificationException !STACK 0 java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification (AbstractList.java:448) at java.util.AbstractList$Itr.next(AbstractList.java:419) at java.util.AbstractCollection.remove(AbstractCollection.java:254) at org.eclipse.jface.text.AbstractDocument.removeDocumentListener (AbstractDocument.java:264) at org.eclipse.text.edits.UndoCollector.disconnect (UndoCollector.java:38) at org.eclipse.text.edits.TextEditProcessor.executeDo (TextEditProcessor.java:167) at org.eclipse.text.edits.TextEdit.dispatchPerformEdits (TextEdit.java:664) at org.eclipse.text.edits.TextEditProcessor.performEdits (TextEditProcessor.java:130) at org.eclipse.ltk.core.refactoring.TextChange.perform (TextChange.java:334) at org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal.performCha nge(ChangeCorrectionProposal.java:101) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.performChange (CUCorrectionProposal.java:259) at org.eclipse.jdt.internal.ui.text.correction.LinkedCorrectionProposal.performCha nge(LinkedCorrectionProposal.java:195) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.apply (CUCorrectionProposal.java:289) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:398) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWith Mask(CompletionProposalPopup.java:361) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$19 (CompletionProposalPopup.java:357) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$3.widgetDefaultSel ected(CompletionProposalPopup.java:322) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:96) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:796) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2725) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2390) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1353) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1324) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:243) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:90) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:298) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:249) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:126) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:269) at org.eclipse.core.launcher.Main.run(Main.java:722) at org.eclipse.core.launcher.Main.main(Main.java:706)
|
verified fixed
|
5f84213
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T13:42:25Z
| 2004-05-12T08:20:00Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.CollationElementIterator;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ISelectionValidator;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.link.LinkedModeModel;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension2;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextNavigationAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.util.IModifierConstants;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.ui.text.folding.IJavaFoldingStructureProvider;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.FoldingActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
import org.eclipse.jdt.internal.ui.search.MethodExitsFinder;
import org.eclipse.jdt.internal.ui.search.OccurrencesFinder;
import org.eclipse.jdt.internal.ui.text.CustomSourceInformationControl;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.JavaPresentationReconciler;
import org.eclipse.jdt.internal.ui.text.PreferencesAdapter;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaExpandHover;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider the selection provider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
// XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
JavaEditor.this.selectionChanged();
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/**
* Adapts an options {@link java.util.Map} to {@link org.eclipse.jface.preference.IPreferenceStore}.
* <p>
* This preference store is read-only i.e. write access
* throws an {@link java.lang.UnsupportedOperationException}.
* </p>
*
* @since 3.0
*/
private static class OptionsAdapter implements IPreferenceStore {
/**
* A property change event filter.
*/
public interface IPropertyChangeEventFilter {
/**
* Should the given event be filtered?
* @param event The property change event.
* @return <code>true</code> iff the given event should be filtered.
*/
public boolean isFiltered(PropertyChangeEvent event);
}
/**
* Property change listener. Listens for events in the options Map and
* fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
* on this adapter with arguments from the received event.
*/
private class PropertyChangeListener implements IPropertyChangeListener {
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent event) {
if (getFilter().isFiltered(event))
return;
if (event.getNewValue() == null)
fOptions.remove(event.getProperty());
else
fOptions.put(event.getProperty(), event.getNewValue());
firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
}
}
/** Listeners on this adapter */
private ListenerList fListeners= new ListenerList();
/** Listener on the adapted options Map */
private IPropertyChangeListener fListener= new PropertyChangeListener();
/** Adapted options Map */
private Map fOptions;
/** Preference store through which events are received. */
private IPreferenceStore fMockupPreferenceStore;
/** Property event filter. */
private IPropertyChangeEventFilter fFilter;
/**
* Initialize with the given options.
*
* @param options The options to wrap
* @param mockupPreferenceStore the mock-up preference store
* @param filter the property change filter
*/
public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
fMockupPreferenceStore= mockupPreferenceStore;
fOptions= options;
setFilter(filter);
}
/**
* {@inheritDoc}
*/
public void addPropertyChangeListener(IPropertyChangeListener listener) {
if (fListeners.size() == 0)
fMockupPreferenceStore.addPropertyChangeListener(fListener);
fListeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removePropertyChangeListener(IPropertyChangeListener listener) {
fListeners.remove(listener);
if (fListeners.size() == 0)
fMockupPreferenceStore.removePropertyChangeListener(fListener);
}
/**
* {@inheritDoc}
*/
public boolean contains(String name) {
return fOptions.containsKey(name);
}
/**
* {@inheritDoc}
*/
public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
((IPropertyChangeListener) listeners[i]).propertyChange(event);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(String name) {
boolean value= BOOLEAN_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null)
value= s.equals(TRUE);
return value;
}
/**
* {@inheritDoc}
*/
public boolean getDefaultBoolean(String name) {
return BOOLEAN_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDefaultDouble(String name) {
return DOUBLE_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public float getDefaultFloat(String name) {
return FLOAT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public int getDefaultInt(String name) {
return INT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public long getDefaultLong(String name) {
return LONG_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public String getDefaultString(String name) {
return STRING_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDouble(String name) {
double value= DOUBLE_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Double(s).doubleValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public float getFloat(String name) {
float value= FLOAT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Float(s).floatValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public int getInt(String name) {
int value= INT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Integer(s).intValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public long getLong(String name) {
long value= LONG_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Long(s).longValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public String getString(String name) {
String value= (String) fOptions.get(name);
if (value == null)
value= STRING_DEFAULT_DEFAULT;
return value;
}
/**
* {@inheritDoc}
*/
public boolean isDefault(String name) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean needsSaving() {
return !fOptions.isEmpty();
}
/**
* {@inheritDoc}
*/
public void putValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, String defaultObject) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setToDefault(String name) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* Returns the adapted options Map.
*
* @return Returns the adapted options Map.
*/
public Map getOptions() {
return fOptions;
}
/**
* Returns the mock-up preference store, events are received through this preference store.
* @return Returns the mock-up preference store.
*/
public IPreferenceStore getMockupPreferenceStore() {
return fMockupPreferenceStore;
}
/**
* Set the event filter to the given filter.
*
* @param filter The new filter.
*/
public void setFilter(IPropertyChangeEventFilter filter) {
fFilter= filter;
}
/**
* Returns the event filter.
*
* @return The event filter.
*/
public IPropertyChangeEventFilter getFilter() {
return fFilter;
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
((ITextViewerExtension4)sourceViewer).addTextPresentationListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fall back to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
*
* @param store the preference store
* @param key the key
* @param display the display
* @return the color or <code>null</code> if there is no such information available
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
fActiveRegion= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
// Invalidate ==> remove applied text presentation
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// Remove underline
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
try {
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, false);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
public void applyTextPresentation(TextPresentation textPresentation) {
if (fActiveRegion == null)
return;
IRegion region= textPresentation.getExtent();
if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// Underline
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
text.redrawRange(offset, length, false);
// Invalidate region ==> apply text presentation
fActiveRegion= region;
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
else
viewer.invalidateTextPresentation();
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != fKeyModifierMask) {
deactivate();
return;
}
fActive= true;
// removed for #25871
//
// ISourceViewer viewer= getSourceViewer();
// if (viewer == null)
// return;
//
// IRegion region= getCurrentTextRegion(viewer);
// if (region == null)
// return;
//
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != fKeyModifierMask) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
boolean wasActive= fCursor != null;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != fKeyModifierMask)
return;
// modifier was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fActive && fActiveRegion != null) {
fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
try {
event.getDocument().addPosition(fRememberedPosition);
} catch (BadLocationException x) {
fRememberedPosition= null;
}
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
if (fRememberedPosition != null) {
if (!fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
} else {
fActiveRegion= null;
fRememberedPosition= null;
deactivate();
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(fActiveRegion);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action behaves in two different ways: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*
* @param resourceBundle the resource bundle
* @param prefix the prefix
* @param textOperationAction the text operation action
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
if (extension4.moveFocusToWidgetToken())
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset, true);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
/**
* This action implements smart home.
*
* Instead of going to the start of a line it does the following:
*
* - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account.
* - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line
* - if the caret is at the beginning of the line see first case.
*
* @since 3.0
*/
protected class SmartLineStartAction extends LineStartAction {
/**
* Creates a new smart line start action
*
* @param textWidget the styled text widget
* @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected
*/
public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
super(textWidget, doSelect);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String)
*/
protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
String type= IDocument.DEFAULT_CONTENT_TYPE;
try {
type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
} catch (BadLocationException exception) {
// Should not happen
}
int index= super.getLineStartPosition(document, line, length, offset);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
} else {
if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
index++;
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
}
return index;
}
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected abstract class NextSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new next sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected NextSubWordAction(int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Check whether right hand character of caret is valid identifier start
if (Character.isJavaIdentifierStart(document.getChar(position))) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final String buffer= document.get(position, region.getOffset() + region.getLength() - position);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
do {
// Check whether we reached end of word
offset= iterator.getOffset();
if (!Character.isJavaIdentifierPart(document.getChar(position + offset)))
throw new BadLocationException();
// Test next characters
order= iterator.next();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check for leading underscores
position += offset;
if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) {
setCaretPosition(position);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected class NavigateNextSubWordAction extends NextSubWordAction {
/**
* Creates a new navigate next sub-word action.
*/
public NavigateNextSubWordAction() {
super(ST.WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the next sub-word.
*
* @since 3.0
*/
protected class DeleteNextSubWordAction extends NextSubWordAction {
/**
* Creates a new delete next sub-word action.
*/
public DeleteNextSubWordAction() {
super(ST.DELETE_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the next sub-word.
*
* @since 3.0
*/
protected class SelectNextSubWordAction extends NextSubWordAction {
/**
* Creates a new select next sub-word action.
*/
public SelectNextSubWordAction() {
super(ST.SELECT_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected abstract class PreviousSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new previous sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected PreviousSubWordAction(final int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1;
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Ignore trailing white spaces
char character= document.getChar(position);
while (position > 0 && Character.isWhitespace(character)) {
--position;
character= document.getChar(position);
}
// Check whether left hand character of caret is valid identifier part
if (Character.isJavaIdentifierPart(character)) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
iterator.setOffset(buffer.length() - 1);
do {
// Check whether we reached begin of word or single upper-case start
offset= iterator.getOffset();
character= document.getChar(region.getOffset() + offset);
if (!Character.isJavaIdentifierPart(character))
throw new BadLocationException();
else if (Character.isUpperCase(character)) {
++offset;
break;
}
// Test next characters
order= iterator.previous();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check left character for multiple upper-case characters
position= position - buffer.length() + offset - 1;
character= document.getChar(position);
while (position >= 0 && Character.isUpperCase(character))
character= document.getChar(--position);
setCaretPosition(position + 1);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new navigate previous sub-word action.
*/
public NavigatePreviousSubWordAction() {
super(ST.WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the previous sub-word.
*
* @since 3.0
*/
protected class DeletePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new delete previous sub-word action.
*/
public DeletePreviousSubWordAction() {
super(ST.DELETE_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the previous sub-word.
*
* @since 3.0
*/
protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new select previous sub-word action.
*/
public SelectPreviousSubWordAction() {
super(ST.SELECT_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Format element action to format the enclosing java element.
* <p>
* The format element action works as follows:
* <ul>
* <li>If there is no selection and the caret is positioned on a Java element,
* only this element is formatted. If the element has some accompanying comment,
* then the comment is formatted as well.</li>
* <li>If the selection spans one or more partitions of the document, then all
* partitions covered by the selection are entirely formatted.</li>
* <p>
* Partitions at the end of the selection are not completed, except for comments.
*
* @since 3.0
*/
protected class FormatElementAction extends Action {
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
if (viewer.isEditable()) {
final Point selection= viewer.rememberSelection();
try {
viewer.setRedraw(false);
final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x, true);
if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
try {
final IJavaElement element= getElementAt(selection.x, true);
if (element != null && element.exists()) {
final int kind= element.getElementType();
if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
final ISourceReference reference= (ISourceReference)element;
final ISourceRange range= reference.getSourceRange();
if (range != null) {
viewer.setSelectedRange(range.getOffset(), range.getLength());
viewer.doOperation(ISourceViewer.FORMAT);
}
}
}
} catch (JavaModelException exception) {
// Should not happen
}
} else {
viewer.setSelectedRange(selection.x, 1);
viewer.doOperation(ISourceViewer.FORMAT);
}
} catch (BadLocationException exception) {
// Can not happen
} finally {
viewer.setRedraw(true);
viewer.restoreSelection();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
if (fMarkOccurrenceAnnotations && isActivePart()) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/**
* Indicates whether this editor is about to update any annotation views.
* @since 3.0
*/
private boolean fIsUpdatingAnnotationViews= false;
/**
* The marker that served as last target for a goto marker request.
* @since 3.0
*/
private IMarker fLastMarkerTarget= null;
protected CompositeActionGroup fActionGroups;
/**
* The action group for folding.
*
* @since 3.0
*/
private FoldingActionGroup fFoldingGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Holds the current occurrence annotations.
* @since 3.0
*/
private Annotation[] fOccurrenceAnnotations= null;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* Tells whether the occurrence annotations are sticky
* i.e. whether they stay even if there's no valid Java
* element at the current caret position.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fStickyOccurrenceAnnotations;
/**
* Tells whether to mark type occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkTypeOccurrences;
/**
* Tells whether to mark method occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodOccurrences;
/**
* Tells whether to mark constant occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkConstantOccurrences;
/**
* Tells whether to mark field occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkFieldOccurrences;
/**
* Tells whether to mark local variable occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkLocalVariableypeOccurrences;
/**
* Tells whether to mark exception occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkExceptionOccurrences;
/**
* Tells whether to mark method exits in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodExitPoints;
/**
*
*/
private ISelection fForcedMarkOccurrencesSelection;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
private ISelectionListenerWithAST fPostSelectionListenerWithAST;
private OccurrencesFinderJob fOccurrencesFinderJob;
/**
* This editor's projection support
* @since 3.0
*/
private ProjectionSupport fProjectionSupport;
/**
* This editor's projection model updater
* @since 3.0
*/
private IJavaFoldingStructureProvider fProjectionModelUpdater;
/**
* The override and implements indicator manager for this editor.
* @since 3.0
*/
protected OverrideIndicatorManager fOverrideIndicatorManager;
/**
* Semantic highlighting manager
* @since 3.0
*/
private SemanticHighlightingManager fSemanticManager;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement.
*
* @param element the java element
* @return the corresponding Java element
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*
* @param page the Java outline page
* @param input the editor input
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
*/
protected void initializeKeyBindingScopes() {
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
*/
protected void initializeEditor() {
IPreferenceStore store= createCombinedPreferenceStore(null);
setPreferenceStore(store);
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
fMarkTypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
fMarkMethodOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
fMarkConstantOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
fMarkFieldOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
fMarkLocalVariableypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
fMarkExceptionOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
fMarkMethodExitPoints= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore());
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
return ((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
}
/**
* Creates and returns the preference store for this Java editor with the given input.
*
* @param input The editor input for which to create the preference store
* @return the preference store for this editor
*
* @since 3.0
*/
private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
List stores= new ArrayList(3);
IJavaProject project= EditorUtility.getJavaProject(input);
if (project != null)
stores.add(new OptionsAdapter(project.getOptions(false), JavaPlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() {
public boolean isFiltered(PropertyChangeEvent event) {
IJavaElement inputJavaElement= getInputJavaElement();
IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
if (javaProject == null)
return true;
return !javaProject.getProject().equals(event.getSource());
}
}));
stores.add(JavaPlugin.getDefault().getPreferenceStore());
stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
stores.add(EditorsUI.getPreferenceStore());
return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
}
/**
* Sets the outliner's context menu ID.
*
* @param menuId the menu ID
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*
* @return returns this editor's standard action group
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*
* @return the created Java outline page
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
if (fProjectionSupport != null) {
Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
if (adapter != null)
return adapter;
}
return super.getAdapter(required);
}
/**
* React to changed selection.
*
* @since 3.0
*/
protected void selectionChanged() {
if (getSelectionProvider() == null)
return;
ISourceReference element= computeHighlightRangeSourceReference();
if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
synchronizeOutlinePage(element);
setSelection(element, false);
updateStatusLine();
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
if (getSelectionProvider() == null)
return;
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
// PR 39995: [navigation] Forward history cleared after going back in navigation history:
// mark only in navigation history if the cursor is being moved (which it isn't if
// this is called from a PostSelectionEvent that should only update the magnet)
if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0))
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= null;
if (reference instanceof ILocalVariable) {
IJavaElement je= ((ILocalVariable)reference).getParent();
if (je instanceof ISourceReference)
range= ((ISourceReference)je).getSourceRange();
} else
range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof ILocalVariable) {
range= ((ILocalVariable)reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set highlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
}
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(offset, length));
} else {
resetHighlightRange();
}
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
*/
protected void handleElementContentReplaced() {
super.handleElementContentReplaced();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
ISourceViewer sourceViewer= getSourceViewer();
if (!(sourceViewer instanceof ISourceViewerExtension2)) {
setPreferenceStore(createCombinedPreferenceStore(input));
internalDoSetInput(input);
return;
}
// uninstall & unregister preference store listener
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
getSourceViewerDecorationSupport(sourceViewer).uninstall();
((ISourceViewerExtension2)sourceViewer).unconfigure();
setPreferenceStore(createCombinedPreferenceStore(input));
// install & register preference store listener
sourceViewer.configure(getSourceViewerConfiguration());
getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
internalDoSetInput(input);
}
private void internalDoSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
if (isShowingOverrideIndicators())
installOverrideIndicator(true);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
* @since 3.0
*/
protected void setPreferenceStore(IPreferenceStore store) {
super.setPreferenceStore(store);
if (getSourceViewerConfiguration() instanceof JavaSourceViewerConfiguration) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
}
if (getSourceViewer() instanceof JavaSourceViewer)
((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.uninstall();
fProjectionModelUpdater= null;
}
if (fProjectionSupport != null) {
fProjectionSupport.dispose();
fProjectionSupport= null;
}
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
uninstallOccurrencesFinder();
uninstallOverrideIndicator();
uninstallSemanticHighlighting();
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
fFoldingGroup= new FoldingActionGroup(this, getViewer());
ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
action= new FormatElementAction();
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
setAction("QuickFormat", action); //$NON-NLS-1$
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
// add annotation actions
action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", action); //$NON-NLS-1$
// replace cut/copy paste actions with a version that implement 'add imports on paste'
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$
setAction(ITextEditorActionConstants.CUT, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Copy.", this, ITextOperationTarget.COPY); //$NON-NLS-1$
setAction(ITextEditorActionConstants.COPY, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
setAction(ITextEditorActionConstants.PASTE, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue())
selectionChanged();
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
enableOverwriteMode(!disable.booleanValue());
}
return;
}
if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
if (!fMarkOccurrenceAnnotations)
uninstallOccurrencesFinder();
else
installOccurrencesFinder();
}
}
return;
}
if (PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkTypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkConstantOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkFieldOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkLocalVariableypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkExceptionOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodExitPoints= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fStickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED.equals(property)) {
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
else
uninstallSemanticHighlighting();
return;
}
((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
if (affectsOverrideIndicatorAnnotations(event)) {
if (isShowingOverrideIndicators()) {
if (fOverrideIndicatorManager == null)
installOverrideIndicator(false);
} else {
if (fOverrideIndicatorManager != null)
uninstallOverrideIndicator();
}
return;
}
if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
if (sourceViewer instanceof ProjectionViewer) {
ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.uninstall();
// either freshly enabled or provider changed
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.install(this, projectionViewer);
}
}
return;
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
* @since 3.0
*/
protected void initializeViewerColors(ISourceViewer viewer) {
// is handled by JavaSourceViewer
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength(), false);
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param widgetLineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
boolean isFoldingEnabled() {
return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
}
});
fProjectionSupport.install();
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.install(this, projectionViewer);
if (isFoldingEnabled())
projectionViewer.doOperation(ProjectionViewer.TOGGLE);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
enableOverwriteMode(false);
if (fMarkOccurrenceAnnotations)
installOccurrencesFinder();
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews) {
super.gotoMarker(marker);
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$
method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set status line
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinderJob extends Job implements IDocumentListener {
private IDocument fDocument;
private ISelection fSelection;
private ISelectionValidator fPostSelectionValidator;
private boolean fCancelled= false;
private IProgressMonitor fProgressMonitor;
private Position[] fPositions;
public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) {
super(JavaEditorMessages.getString("JavaEditor.markOccurrences.job.name")); //$NON-NLS-1$
fDocument= document;
fSelection= selection;
fPositions= positions;
fDocument.addDocumentListener(this);
if (getSelectionProvider() instanceof ISelectionValidator)
fPostSelectionValidator= (ISelectionValidator)getSelectionProvider();
}
private boolean isCancelled() {
return fCancelled || fProgressMonitor.isCanceled()
|| fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
|| LinkedModeModel.hasInstalledModel(fDocument);
}
/*
* @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus run(IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
try {
if (isCancelled())
return Status.CANCEL_STATUS;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return Status.CANCEL_STATUS;
IDocument document= textViewer.getDocument();
if (document == null)
return Status.CANCEL_STATUS;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return Status.CANCEL_STATUS;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return Status.CANCEL_STATUS;
// Add occurrence annotations
int length= fPositions.length;
Map annotationMap= new HashMap(length);
for (int i= 0; i < length; i++) {
if (isCancelled())
return Status.CANCEL_STATUS;
String message;
Position position= fPositions[i];
// Create & add annotation
try {
message= document.get(position.offset, position.length);
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
position);
}
if (isCancelled())
return Status.CANCEL_STATUS;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
} else {
removeOccurrenceAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
} finally {
fDocument.removeDocumentListener(this);
}
return Status.OK_STATUS;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fCancelled= true;
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @param selection the text selection
* @param astRoot the compilation unit AST
* @since 3.0
*/
protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) {
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.cancel();
if (!fMarkOccurrenceAnnotations)
return;
if (astRoot == null || selection == null)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
List matches= new ArrayList();
String message;
if (fMarkExceptionOccurrences || fMarkTypeOccurrences) {
ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= exceptionFinder.perform();
}
}
if (matches.size() == 0 && fMarkMethodExitPoints) {
MethodExitsFinder finder= new MethodExitsFinder();
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= finder.perform();
}
}
if (matches.size() == 0) {
ASTNode node= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
if (!(node instanceof Name)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
IBinding binding= ((Name)node).resolveBinding();
if (binding == null && fStickyOccurrenceAnnotations)
return;
if (!markOccurrencesOfType(binding)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
// Find the matches && extract positions so we can forget the AST
OccurrencesFinder finder = new OccurrencesFinder(binding);
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null)
matches= finder.perform();
} else if (!fMarkExceptionOccurrences) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
Position[] positions= new Position[matches.size()];
int i= 0;
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode currentNode= (ASTNode)each.next();
positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
}
fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions, selection);
//fOccurrencesFinderJob.setPriority(Job.DECORATE);
//fOccurrencesFinderJob.setSystem(true);
//fOccurrencesFinderJob.schedule();
fOccurrencesFinderJob.run(new NullProgressMonitor());
}
protected void installOccurrencesFinder() {
fMarkOccurrenceAnnotations= true;
fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
updateOccurrenceAnnotations(selection, astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
if (getSelectionProvider() != null) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
}
protected void uninstallOccurrencesFinder() {
fMarkOccurrenceAnnotations= false;
if (fOccurrencesFinderJob != null) {
fOccurrencesFinderJob.cancel();
fOccurrencesFinderJob= null;
}
if (fPostSelectionListenerWithAST != null) {
SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
fPostSelectionListenerWithAST= null;
}
removeOccurrenceAnnotations();
}
protected boolean isMarkingOccurrences() {
return fMarkOccurrenceAnnotations;
}
boolean markOccurrencesOfType(IBinding binding) {
if (binding == null)
return false;
int kind= binding.getKind();
if (fMarkTypeOccurrences && kind == IBinding.TYPE)
return true;
if (fMarkMethodOccurrences && kind == IBinding.METHOD)
return true;
if (kind == IBinding.VARIABLE) {
IVariableBinding variableBinding= (IVariableBinding)binding;
if (variableBinding.isField()) {
boolean isConstant= (variableBinding.getModifiers() & (IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL)) != 0;
if (isConstant)
return fMarkConstantOccurrences;
else
return fMarkFieldOccurrences;
}
return fMarkLocalVariableypeOccurrences;
}
return false;
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
protected void uninstallOverrideIndicator() {
if (fOverrideIndicatorManager != null) {
fOverrideIndicatorManager.removeAnnotations();
fOverrideIndicatorManager= null;
}
}
protected void installOverrideIndicator(boolean waitForReconcilation) {
uninstallOverrideIndicator();
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
IJavaElement inputElement= getInputJavaElement();
if (model == null || inputElement == null)
return;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast);
}
/**
* Tells whether override indicators are shown.
*
* @return <code>true</code> if the override indicators are shown
* @since 3.0
*/
protected boolean isShowingOverrideIndicators() {
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
IPreferenceStore store= getPreferenceStore();
return getBoolean(store, preference.getHighlightPreferenceKey())
|| getBoolean(store, preference.getVerticalRulerPreferenceKey())
|| getBoolean(store, preference.getOverviewRulerPreferenceKey())
|| getBoolean(store, preference.getTextPreferenceKey());
}
/**
* Returns the boolean preference for the given key.
*
* @param store the preference store
* @param key the preference key
* @return <code>true</code> if the key exists in the store and its value is <code>true</code>
* @since 3.0
*/
private boolean getBoolean(IPreferenceStore store, String key) {
return key != null && store.getBoolean(key);
}
/**
* Determines whether the preference change encoded by the given event
* changes the override indication.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a change
* @since 3.0
*/
protected boolean affectsOverrideIndicatorAnnotations(PropertyChangeEvent event) {
String key= event.getProperty();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
if (key == null || preference == null)
return false;
return key.equals(preference.getHighlightPreferenceKey())
|| key.equals(preference.getVerticalRulerPreferenceKey())
|| key.equals(preference.getOverviewRulerPreferenceKey())
|| key.equals(preference.getTextPreferenceKey());
}
/**
* @return <code>true</code> if Semantic Highlighting is enabled.
*
* @since 3.0
*/
private boolean isSemanticHighlightingEnabled() {
return getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED);
}
/**
* Install Semantic Highlighting.
*
* @since 3.0
*/
private void installSemanticHighlighting() {
if (fSemanticManager == null) {
fSemanticManager= new SemanticHighlightingManager();
JavaPresentationReconciler backgroundPresentationReconciler= (JavaPresentationReconciler) getSourceViewerConfiguration().getPresentationReconciler(getSourceViewer());
fSemanticManager.install(this, (JavaSourceViewer) getSourceViewer(), JavaPlugin.getDefault().getJavaTextTools().getColorManager(), getPreferenceStore(), backgroundPresentationReconciler);
}
}
/**
* Uninstall Semantic Highlighting.
*
* @since 3.0
*/
private void uninstallSemanticHighlighting() {
if (fSemanticManager != null) {
fSemanticManager.uninstall();
fSemanticManager= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
/**
* Returns the signed current selection.
* The length will be negative if the resulting selection
* is right-to-left (RtoL).
* <p>
* The selection offset is model based.
* </p>
*
* @param sourceViewer the source viewer
* @return a region denoting the current signed selection, for a resulting RtoL selections length is < 0
*/
protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
StyledText text= sourceViewer.getTextWidget();
Point selection= text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
selection.x= selection.x + selection.y;
selection.y= -selection.y;
}
selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x);
return new Region(selection.x, selection.y);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= EditorsUI.getPluginPreferences();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
*/
protected void createNavigationActions() {
super.createNavigationActions();
final StyledText textWidget= getSourceViewer().getTextWidget();
IAction action= new SmartLineStartAction(textWidget, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
setAction(ITextEditorActionDefinitionIds.LINE_START, action);
action= new SmartLineStartAction(textWidget, true);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
action= new NavigatePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
action= new NavigateNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
action= new DeletePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
action= new DeleteNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
action= new SelectPreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
action= new SelectNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
*/
protected CompositeRuler createCompositeRuler() {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
return super.createCompositeRuler();
CompositeRuler ruler= new CompositeRuler();
AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
// for now: just invoke ruler double click action
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
}
private void triggerAction(String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
// hack to propagate line change
if (action instanceof ISelectionListener) {
((ISelectionListener)action).selectionChanged(null, null);
}
if (action.isEnabled())
action.run();
}
}
}));
ruler.addDecorator(0, column);
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isPrefQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/**
* Returns the folding action group, or <code>null</code> if there is none.
*
* @return the folding action group, or <code>null</code> if there is none
* @since 3.0
*/
protected FoldingActionGroup getFoldingActionGroup() {
return fFoldingGroup;
}
}
|
62,508
|
Bug 62508 [Externalize] Edit fails when key or value is null [nls] [refactoring]
|
N20040517 on WXP Externalize any source which can be externalized, e.g. ExternalizeWizardPage.java Select a row which has a null key and/or value. This is common when you have asked to ignore/skip these items. You will get the following: java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at java.util.StringTokenizer.<init>(StringTokenizer.java) at java.util.StringTokenizer.<init>(StringTokenizer.java) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$NLSInputDialo g.getTokens(ExternalizeWizardPage.java:395) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$NLSInputDialo g.dialogFieldChanged(ExternalizeWizardPage.java:388) at org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField.dialogFieldChanged (DialogField.java:70) at org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField.setText (StringDialogField.java:162) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$NLSInputDialo g.<init>(ExternalizeWizardPage.java:347) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage.openEditButto n(ExternalizeWizardPage.java:953) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage.handleButtonP ressed(ExternalizeWizardPage.java:905) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$10.widgetSele cted(ExternalizeWizardPage.java:875) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java) at org.eclipse.jface.window.Window.open(Window.java:648) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run (RefactoringWizardOpenOperation.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.openExternalizeStringsWizar d(ExternalizeStringsAction.java:157) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction$1.run (ExternalizeStringsAction.java:126) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.run (ExternalizeStringsAction.java:123) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.run (ExternalizeStringsAction.java:105) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:899) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:850) at org.eclipse.jface.action.ActionContributionItem$7.handleEvent (ActionContributionItem.java:769) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1363) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1334) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:253) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:97) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:299) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:256) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:84) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:59) at java.lang.reflect.Method.invoke(Method.java:390) at org.eclipse.core.launcher.Main.basicRun(Main.java:184) at org.eclipse.core.launcher.Main.run(Main.java:637) at org.eclipse.core.launcher.Main.main(Main.java:621)
|
resolved fixed
|
50390a3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T16:00:15Z
| 2004-05-17T18:53:20Z
|
org.eclipse.jdt.ui/ui
| |
62,508
|
Bug 62508 [Externalize] Edit fails when key or value is null [nls] [refactoring]
|
N20040517 on WXP Externalize any source which can be externalized, e.g. ExternalizeWizardPage.java Select a row which has a null key and/or value. This is common when you have asked to ignore/skip these items. You will get the following: java.lang.NullPointerException at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at java.lang.NullPointerException.<init>(NullPointerException.java:60) at java.util.StringTokenizer.<init>(StringTokenizer.java) at java.util.StringTokenizer.<init>(StringTokenizer.java) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$NLSInputDialo g.getTokens(ExternalizeWizardPage.java:395) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$NLSInputDialo g.dialogFieldChanged(ExternalizeWizardPage.java:388) at org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField.dialogFieldChanged (DialogField.java:70) at org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField.setText (StringDialogField.java:162) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$NLSInputDialo g.<init>(ExternalizeWizardPage.java:347) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage.openEditButto n(ExternalizeWizardPage.java:953) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage.handleButtonP ressed(ExternalizeWizardPage.java:905) at org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizardPage$10.widgetSele cted(ExternalizeWizardPage.java:875) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Window.java) at org.eclipse.jface.window.Window.open(Window.java:648) at org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation.run (RefactoringWizardOpenOperation.java:121) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:40) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.openExternalizeStringsWizar d(ExternalizeStringsAction.java:157) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction$1.run (ExternalizeStringsAction.java:126) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.run (ExternalizeStringsAction.java:123) at org.eclipse.jdt.ui.actions.ExternalizeStringsAction.run (ExternalizeStringsAction.java:105) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:216) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:188) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:899) at org.eclipse.jface.action.ActionContributionItem.access$2 (ActionContributionItem.java:850) at org.eclipse.jface.action.ActionContributionItem$7.handleEvent (ActionContributionItem.java:769) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1363) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1334) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:253) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:97) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:299) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:256) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:84) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:59) at java.lang.reflect.Method.invoke(Method.java:390) at org.eclipse.core.launcher.Main.basicRun(Main.java:184) at org.eclipse.core.launcher.Main.run(Main.java:637) at org.eclipse.core.launcher.Main.main(Main.java:621)
|
resolved fixed
|
50390a3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T16:00:15Z
| 2004-05-17T18:53:20Z
|
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage.java
| |
62,686
|
Bug 62686 Missing classes in hierarchy [type hierarchy]
|
I200405180816 Open type hierarchy on IWorkbench. The implementing class Workbench is not shown. You have to press 'Show subtype hierarchy' to see it.
|
verified fixed
|
3444b32
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T18:25:18Z
| 2004-05-18T17:06:40Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TraditionalHierarchyViewer.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.Arrays;
import java.util.List;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
/**
* A TypeHierarchyViewer that looks like the type hierarchy view of VA/Java:
* Starting form Object down to the element in focus, then all subclasses from
* this element.
* Used by the TypeHierarchyViewPart which has to provide a TypeHierarchyLifeCycle
* on construction (shared type hierarchy)
*/
public class TraditionalHierarchyViewer extends TypeHierarchyViewer {
public TraditionalHierarchyViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
super(parent, new TraditionalHierarchyContentProvider(lifeCycle), lifeCycle, part);
}
/*
* @see TypeHierarchyViewer#getTitle
*/
public String getTitle() {
if (isMethodFiltering()) {
return TypeHierarchyMessages.getString("TraditionalHierarchyViewer.filtered.title"); //$NON-NLS-1$
} else {
return TypeHierarchyMessages.getString("TraditionalHierarchyViewer.title"); //$NON-NLS-1$
}
}
/*
* @see TypeHierarchyViewer#updateContent
*/
public void updateContent(boolean expand) {
getTree().setRedraw(false);
refresh();
if (expand) {
TraditionalHierarchyContentProvider contentProvider= (TraditionalHierarchyContentProvider) getContentProvider();
int expandLevel= contentProvider.getExpandLevel();
if (isMethodFiltering()) {
expandLevel++;
}
expandToLevel(expandLevel);
}
getTree().setRedraw(true);
}
/**
* Content provider for the 'traditional' type hierarchy.
*/
public static class TraditionalHierarchyContentProvider extends TypeHierarchyContentProvider {
public TraditionalHierarchyContentProvider(TypeHierarchyLifeCycle provider) {
super(provider);
}
public int getExpandLevel() {
ITypeHierarchy hierarchy= getHierarchy();
if (hierarchy != null) {
IType input= hierarchy.getType();
if (input != null) {
return getDepth(hierarchy, input) + 2;
} else {
return 5;
}
}
return 2;
}
private int getDepth(ITypeHierarchy hierarchy, IType input) {
int count= 0;
IType superType= hierarchy.getSuperclass(input);
while (superType != null) {
count++;
superType= hierarchy.getSuperclass(superType);
}
return count;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyContentProvider#getRootTypes(java.util.List)
*/
protected final void getRootTypes(List res) {
ITypeHierarchy hierarchy= getHierarchy();
if (hierarchy != null) {
IType input= hierarchy.getType();
if (input == null) {
IType[] classes= hierarchy.getRootClasses();
for (int i= 0; i < classes.length; i++) {
res.add(classes[i]);
}
IType[] interfaces= hierarchy.getRootInterfaces();
for (int i= 0; i < interfaces.length; i++) {
res.add(interfaces[i]);
}
} else {
if (Flags.isInterface(hierarchy.getCachedFlags(input))) {
res.add(input);
} else {
IType[] roots= hierarchy.getRootClasses();
for (int i= 0; i < roots.length; i++) {
if (isObject(roots[i])) {
res.add(roots[i]);
return;
}
}
res.addAll(Arrays.asList(roots)); // something wrong with the hierarchy
}
}
}
}
/*
* @see TypeHierarchyContentProvider.getTypesInHierarchy
*/
protected final void getTypesInHierarchy(IType type, List res) {
ITypeHierarchy hierarchy= getHierarchy();
if (hierarchy != null) {
IType[] types= hierarchy.getSubtypes(type);
if (isObject(type)) {
for (int i= 0; i < types.length; i++) {
IType curr= types[i];
if (!isAnonymous(curr)) { // no anonyous classes on 'Object' -> will be children of interface
res.add(curr);
}
}
} else {
boolean isClass= !Flags.isInterface(hierarchy.getCachedFlags(type));
if (isClass) {
for (int i= 0; i < types.length; i++) {
res.add(types[i]);
}
} else {
for (int i= 0; i < types.length; i++) {
IType curr= types[i];
// no classes implementing inetrfaces, only if anonymous
if (Flags.isInterface(hierarchy.getCachedFlags(curr)) || isAnonymous(curr)) {
res.add(curr);
}
}
}
}
}
}
protected IType getParentType(IType type) {
ITypeHierarchy hierarchy= getHierarchy();
if (hierarchy != null) {
return hierarchy.getSuperclass(type);
// dont handle interfaces
}
return null;
}
}
}
|
62,747
|
Bug 62747 CCE in UnresolvedElementsSubProcessor
|
20040518 java.lang.ClassCastException at org.eclipse.jdt.internal.ui.text.correction.UnresolvedElementsSubProcessor.addSimilarVariableProposals(UnresolvedElementsSubProcessor.java:296) at org.eclipse.jdt.internal.ui.text.correction.UnresolvedElementsSubProcessor.getVariableProposals(UnresolvedElementsSubProcessor.java:165) at org.eclipse.jdt.internal.ui.text.correction.QuickFixProcessor.process(QuickFixProcessor.java:244) at org.eclipse.jdt.internal.ui.text.correction.QuickFixProcessor.getCorrections(QuickFixProcessor.java:202) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.collectCorrections(JavaCorrectionProcessor.java:261) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.processAnnotations(JavaCorrectionProcessor.java:229) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor.computeCompletionProposals(JavaCorrectionProcessor.java:198) at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1457) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:244) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$7(CompletionProposalPopup.java:240) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:199) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.showProposals(CompletionProposalPopup.java:194) at org.eclipse.jface.text.contentassist.ContentAssistant.showPossibleCompletions(ContentAssistant.java:1308) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant.showPossibleCompletions(JavaCorrectionAssistant.java:158) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewer.doOperation(CompilationUnitEditor.java:183) at org.eclipse.ui.texteditor.TextOperationAction$1.run(TextOperationAction.java:122) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:69) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:120) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute(ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:886) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2(WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:712) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:795) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:820) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:805) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1724) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1720) at org.eclipse.swt.widgets.Control.WM_KEYDOWN(Control.java:3499) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2978) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3282) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1475) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2380) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1363) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1334) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:253) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:97) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:299) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:256) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:184) at org.eclipse.core.launcher.Main.run(Main.java:637) at org.eclipse.core.launcher.Main.main(Main.java:621)
|
verified fixed
|
12ea3ef
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T18:53:35Z
| 2004-05-18T19:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <renaud+eclipse@waldura.com> - New class/interface with wizard
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.ISharedImages;
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.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.ui.text.java.IProblemLocation;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeFilter;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription;
import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
public class UnresolvedElementsSubProcessor {
public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveredNode(astRoot);
if (selectedNode == null) {
return;
}
// type that defines the variable
ITypeBinding binding= null;
ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode);
if (declaringTypeBinding == null) {
return;
}
// possible type kind of the node
boolean suggestVariableProposals= true;
int typeKind= 0;
while (selectedNode instanceof ParenthesizedExpression) {
selectedNode= ((ParenthesizedExpression) selectedNode).getExpression();
}
Name node= null;
switch (selectedNode.getNodeType()) {
case ASTNode.SIMPLE_NAME:
node= (SimpleName) selectedNode;
ASTNode parent= node.getParent();
if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) {
typeKind= SimilarElementsRequestor.CLASSES;
} else if (parent instanceof SimpleType) {
suggestVariableProposals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
} else if (parent instanceof QualifiedName) {
Name qualifier= ((QualifiedName) parent).getQualifier();
if (qualifier != node) {
binding= qualifier.resolveTypeBinding();
} else {
typeKind= SimilarElementsRequestor.REF_TYPES;
}
ASTNode outerParent= parent.getParent();
while (outerParent instanceof QualifiedName) {
outerParent= outerParent.getParent();
}
if (outerParent instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= false;
}
}
break;
case ASTNode.QUALIFIED_NAME:
QualifiedName qualifierName= (QualifiedName) selectedNode;
ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
if (qualifierBinding != null) {
node= qualifierName.getName();
binding= qualifierBinding;
} else {
node= qualifierName.getQualifier();
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariableProposals= false;
}
break;
case ASTNode.FIELD_ACCESS:
FieldAccess access= (FieldAccess) selectedNode;
Expression expression= access.getExpression();
if (expression != null) {
binding= expression.resolveTypeBinding();
if (binding != null) {
node= access.getName();
}
}
break;
case ASTNode.SUPER_FIELD_ACCESS:
binding= declaringTypeBinding.getSuperclass();
node= ((SuperFieldAccess) selectedNode).getName();
break;
default:
}
if (node == null) {
return;
}
// add type proposals
if (typeKind != 0) {
int relevance= Character.isUpperCase(ASTNodes.getSimpleNameIdentifier(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if (!suggestVariableProposals) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
boolean isWriteAccess= ASTResolving.isWriteAccess(node);
// similar variables
addSimilarVariableProposals(cu, astRoot, binding, simpleName, isWriteAccess, proposals);
// new fields
addNewFieldProposals(cu, astRoot, binding, declaringTypeBinding, simpleName, isWriteAccess, proposals);
// new parameters and local variables
if (binding == null) {
addNewVariableProposals(cu, node, simpleName, proposals);
}
}
private static void addNewVariableProposals(ICompilationUnit cu, Name node, SimpleName simpleName, Collection proposals) {
String name= simpleName.getIdentifier();
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
int relevance= StubUtility.hasParameterName(cu.getJavaProject(), name) ? 8 : 5;
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, relevance, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
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, relevance, image));
}
if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) {
Assignment assignment= (Assignment) node.getParent();
if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
ASTNode statement= assignment.getParent();
ASTRewrite rewrite= ASTRewrite.create(statement.getAST());
rewrite.remove(statement, null);
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$
Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image);
proposals.add(proposal);
}
}
}
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection proposals) throws JavaModelException {
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (!senderBinding.isFromSource() || targetCU == null || !JavaModelUtil.isEditable(targetCU)) {
return;
}
ITypeBinding outsideAnonymous= null;
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!bind.isAnonymous()) {
outsideAnonymous= bind;
}
}
}
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasFieldName(cu.getJavaProject(), name) ? 9 : 6;
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", name); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, relevance, image));
// create field in outer class (if inside anonymous)
if (outsideAnonymous != null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { name, outsideAnonymous.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, outsideAnonymous, relevance + 1, image));
}
// create constant
if (!isWriteAccess) {
relevance= StubUtility.hasConstantName(name) ? 9 : 4;
ITypeBinding target= (outsideAnonymous != null) ? outsideAnonymous : senderBinding;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.description", name); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconst.other.description", new Object[] { name, binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.CONST_FIELD, simpleName, target, relevance, image));
}
}
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, SimpleName node, boolean isWriteAccess, Collection proposals) {
IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);
if (varsInScope.length > 0) {
// avoid corrections like int i= i;
String otherNameInAssign= null;
// help with x.getString() -> y.getString()
String methodSenderName= null;
String fieldSenderName= null;
ASTNode parent= node.getParent();
switch (parent.getNodeType()) {
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
// node must be initializer
otherNameInAssign= ((VariableDeclarationFragment) parent).getName().getIdentifier();
break;
case ASTNode.ASSIGNMENT:
Assignment assignment= (Assignment) parent;
if (isWriteAccess && assignment.getRightHandSide() instanceof SimpleName) {
otherNameInAssign= ((SimpleName) assignment.getRightHandSide()).getIdentifier();
} else if (!isWriteAccess && assignment.getLeftHandSide() instanceof SimpleName) {
otherNameInAssign= ((SimpleName) assignment.getLeftHandSide()).getIdentifier();
}
break;
case ASTNode.METHOD_INVOCATION:
MethodInvocation inv= (MethodInvocation) parent;
if (inv.getExpression() == node) {
methodSenderName= inv.getName().getIdentifier();
}
case ASTNode.QUALIFIED_NAME:
QualifiedName qualName= (QualifiedName) parent;
if (qualName.getQualifier() == node) {
fieldSenderName= qualName.getName().getIdentifier();
}
}
ITypeBinding guessedType= ASTResolving.guessBindingForReference(node);
if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$
guessedType= null; // too many suggestions
}
String identifier= node.getIdentifier();
for (int i= 0; i < varsInScope.length; i++) {
IVariableBinding curr= (IVariableBinding) varsInScope[i];
String currName= curr.getName();
boolean isFinal= Modifier.isFinal(curr.getModifiers());
if (!currName.equals(otherNameInAssign) && !(isFinal && curr.isField() && isWriteAccess)) {
int relevance= 0;
if (NameMatcher.isSimilarName(currName, identifier)) {
relevance += 3; // variable with a similar name than the unresolved variable
}
if (currName.equalsIgnoreCase(identifier)) {
relevance+= 5;
}
ITypeBinding varType= curr.getType();
if (varType != null) {
if (guessedType != null) {
// var type is compatible with the guessed type
if (!isWriteAccess && TypeRules.canAssign(varType, guessedType)
|| isWriteAccess && TypeRules.canAssign(guessedType, varType)) {
relevance += 2; // unresolved variable can be assign to this variable
}
}
if (methodSenderName != null && hasMethodWithName(varType, methodSenderName)) {
relevance += 2;
}
if (fieldSenderName != null && hasFieldWithName(varType, fieldSenderName)) {
relevance += 2;
}
}
if (relevance > 0) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
}
}
}
if (binding != null && binding.isArray()) {
String idLength= "length"; //$NON-NLS-1$
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", idLength); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), idLength, 8)); //$NON-NLS-1$
}
}
private static boolean hasMethodWithName(ITypeBinding typeBinding, String name) {
IVariableBinding[] fields= typeBinding.getDeclaredFields();
for (int i= 0; i < fields.length; i++) {
if (fields[i].getName().equals(name)) {
return true;
}
}
ITypeBinding superclass= typeBinding.getSuperclass();
if (superclass != null) {
return hasMethodWithName(superclass, name);
}
return false;
}
private static boolean hasFieldWithName(ITypeBinding typeBinding, String name) {
IMethodBinding[] methods= typeBinding.getDeclaredMethods();
for (int i= 0; i < methods.length; i++) {
if (methods[i].getName().equals(name)) {
return true;
}
}
ITypeBinding superclass= typeBinding.getSuperclass();
if (superclass != null) {
return hasMethodWithName(superclass, name);
}
return false;
}
public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
int kind= SimilarElementsRequestor.ALL_TYPES;
ASTNode parent= selectedNode.getParent();
while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variable fragment
parent= parent.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.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE;
}
break;
case ASTNode.INSTANCEOF_EXPRESSION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.THROW_STATEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.CLASS_INSTANCE_CREATION:
if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) {
kind= SimilarElementsRequestor.CLASSES;
} else {
kind= SimilarElementsRequestor.REF_TYPES;
}
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
int superParent= parent.getParent().getNodeType();
if (superParent == ASTNode.CATCH_CLAUSE) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.TAG_ELEMENT:
kind= SimilarElementsRequestor.REF_TYPES;
break;
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;
}
// change to similar type proposals
addSimilarTypeProposals(kind, cu, node, 3, proposals);
// add type
addNewTypeProposals(cu, node, kind, 0, proposals);
}
private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException {
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
// try to resolve type in context -> highest severity
String resolvedTypeName= null;
ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
if (binding != null) {
if (binding.isArray()) {
binding= binding.getElementType();
}
resolvedTypeName= binding.getQualifiedName();
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 CoreException {
ImportRewrite importRewrite= new ImportRewrite(cu);
importRewrite.setFindAmbiguosImports(true);
String simpleName= importRewrite.addImport(fullName);
String packName= Signature.getQualifier(fullName);
String[] arg= { simpleName, packName };
CUCorrectionProposal proposal;
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
// import only
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
proposal= new CUCorrectionProposal(label, cu, relevance + 100, image);
} else {
String label;
if (packName.length() == 0) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg); //$NON-NLS-1$
}
proposal= new RenameNodeCompletionProposal(label, cu, node.getStartPosition(), node.getLength(), simpleName, relevance); //$NON-NLS-1$
}
proposal.setImportRewrite(importRewrite);
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTNodes.getSimpleNameIdentifier(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't suggest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 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(IInvocationContext context, IProblemLocation problem, boolean isOnlyParameterMismatch, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName nameNode= (SimpleName) selectedNode;
List arguments;
Expression sender;
boolean isSuperInvocation;
ASTNode invocationNode= nameNode.getParent();
if (invocationNode instanceof 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();
int nArguments= arguments.size();
// corrections
IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
ArrayList parameterMismatchs= new ArrayList();
for (int i= 0; i < bindings.length; i++) {
IMethodBinding binding= (IMethodBinding) bindings[i];
String curr= binding.getName();
if (curr.equals(methodName) && isOnlyParameterMismatch) {
parameterMismatchs.add(binding);
} else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6));
}
}
addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals);
// new method
ITypeBinding binding= null;
if (sender != null) {
binding= sender.resolveTypeBinding();
} else {
binding= Bindings.getBindingOfParentType(invocationNode);
if (isSuperInvocation && binding != null) {
binding= binding.getSuperclass();
}
}
if (binding != null && binding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
if (targetCU != null) {
String label;
Image image;
String sig= getMethodSignature(methodName, arguments);
if (cu.equals(targetCU)) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
}
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image));
if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method
ASTNode anonymDecl= astRoot.findDeclaringNode(binding);
if (anonymDecl != null) {
binding= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!binding.isAnonymous()) {
String[] args= new String[] { sig, 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, 5, image));
}
}
}
}
}
if (!isOnlyParameterMismatch && !isSuperInvocation && sender != null) {
addMissingCastParentsProposal(cu, (MethodInvocation) invocationNode, proposals);
}
if (!isSuperInvocation && sender == null && invocationNode.getParent() instanceof ThrowStatement) {
String str= "new "; //$NON-NLS-1$ // do it the manual way, copting all the arguments is nasty
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.addnewkeyword.description"); //$NON-NLS-1$
int relevance= Character.isUpperCase(methodName.charAt(0)) ? 7 : 4;
ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, cu, invocationNode.getStartPosition(), 0, str, relevance);
proposals.add(proposal);
}
}
private static void addMissingCastParentsProposal(ICompilationUnit cu, MethodInvocation invocationNode, Collection proposals) {
Expression sender= invocationNode.getExpression();
if (sender instanceof ThisExpression) {
return;
}
ITypeBinding senderBinding= sender.resolveTypeBinding();
if (senderBinding == null || Modifier.isFinal(senderBinding.getModifiers())) {
return;
}
if (sender instanceof Name && ((Name) sender).resolveBinding() instanceof ITypeBinding) {
return; // static access
}
ASTNode parent= invocationNode.getParent();
while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) {
parent= parent.getParent();
}
boolean hasCastProposal= false;
if (parent instanceof CastExpression) {
// (TestCase) x.getName() -> ((TestCase) x).getName
hasCastProposal= useExistingParentCastProposal(cu, (CastExpression) parent, sender, invocationNode.getName(), getArgumentTypes(invocationNode.arguments()), proposals);
}
if (!hasCastProposal) {
// x.getName() -> ((TestCase) x).getName
Expression target= sender;
while (target instanceof ParenthesizedExpression) {
target= ((ParenthesizedExpression) target).getExpression();
}
String targetName= null;
if (target.getLength() <= 18) {
targetName= '\'' + ASTNodes.asString(target) + '\'';
}
String label;
if (invocationNode.getNodeType() == ASTNode.CAST_EXPRESSION) {
if (targetName == null) {
label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.methodtargetcast.description"); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.methodtargetcast2.description", targetName); //$NON-NLS-1$
}
} else {
if (targetName == null) {
label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.changemethodtargetcast.description"); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethodtargetcast2.description", targetName); //$NON-NLS-1$
}
}
proposals.add(new CastCompletionProposal(label, cu, sender, null, 3));
}
}
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection proposals) {
ITypeBinding castType= expression.getType().resolveBinding();
if (castType == null) {
return false;
}
if (paramTypes != null) {
if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
return false;
}
} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
return false;
}
ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
if (bindingToCast != null && !TypeRules.canCast(castType, bindingToCast)) {
return false;
}
IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
if (res != null) {
AST ast= expression.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
CastExpression newCast= ast.newCastExpression();
newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
ParenthesizedExpression parents= ast.newParenthesizedExpression();
parents.setExpression(newCast);
ASTNode node= rewrite.createCopyTarget(expression.getExpression());
rewrite.replace(expression, node, null);
rewrite.replace(accessExpression, parents, null);
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.missingcastbrackets.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image);
proposals.add(proposal);
return true;
}
return false;
}
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException {
int nSimilarElements= similarElements.size();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (argTypes == null || nSimilarElements == 0) {
return;
}
for (int i= 0; i < nSimilarElements; i++) {
IMethodBinding elem = (IMethodBinding) similarElements.get(i);
int diff= elem.getParameterTypes().length - argTypes.length;
if (diff == 0) {
int nProposals= proposals.size();
doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals);
if (nProposals != proposals.size()) {
return; // only suggest for one method (avoid duplicated proposals)
}
} else if (diff > 0) {
doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals);
} else {
doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals);
}
}
}
private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= paramTypes.length - argTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < paramTypes.length; i++) {
if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// add arguments
{
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$
}
AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8);
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD));
proposals.add(proposal);
}
// remove parameters
if (!declaringType.isFromSource()) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
ITypeBinding[] changedTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
changeDesc[idx]= new RemoveDescription();
changedTypes[i]= paramTypes[idx];
}
String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image);
proposals.add(proposal);
}
}
private static String getTypeNames(ITypeBinding[] types) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(types[i].getName());
}
return buf.toString();
}
private static String getArgumentName(ICompilationUnit cu, List arguments, int index) {
String def= String.valueOf(index + 1);
ASTNode expr= (ASTNode) arguments.get(index);
if (expr.getLength() > 18) {
return def;
}
ASTMatcher matcher= new ASTMatcher();
for (int i= 0; i < arguments.size(); i++) {
if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) {
return def;
}
}
return '\'' + ASTNodes.asString(expr) + '\'';
}
private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int k= 0, nSkipped= 0;
int diff= argTypes.length - paramTypes.length;
int[] indexSkipped= new int[diff];
for (int i= 0; i < argTypes.length; i++) {
if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) {
k++; // match
} else {
if (nSkipped >= diff) {
return; // too different
}
indexSkipped[nSkipped++]= i;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
// remove arguments
{
ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
for (int i= diff - 1; i >= 0; i--) {
rewrite.remove((Expression) arguments.get(indexSkipped[i]), null);
}
String[] arg= new String[] { getMethodSignature(methodBinding, false) };
String label;
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposals.add(proposal);
}
// add parameters
if (!declaringType.isFromSource()) {
return;
}
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
boolean isDifferentCU= !cu.equals(targetCU);
if (isImplicitConstructor(methodBinding, targetCU)) {
return;
}
ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length];
ITypeBinding[] changeTypes= new ITypeBinding[diff];
for (int i= diff - 1; i >= 0; i--) {
int idx= indexSkipped[i];
Expression arg= (Expression) arguments.get(idx);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]);
if (newType == null) {
newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
changeDesc[idx]= new InsertDescription(newType, name);
changeTypes[i]= newType;
}
String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) };
String label;
if (methodBinding.isConstructor()) {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$
}
} else {
if (diff == 1) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$
}
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image);
proposals.add(proposal);
}
}
private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) {
if (meth.isConstructor() && meth.getParameterTypes().length == 0) {
IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods();
// implicit constructors must be the only constructor
for (int i= 0; i < bindings.length; i++) {
IMethodBinding curr= bindings[i];
if (curr.isConstructor() && curr != meth) {
return false;
}
}
ASTParser parser= ASTParser.newParser(AST.JLS2);
parser.setSource(targetCU);
parser.setFocalPosition(0);
parser.setResolveBindings(true);
CompilationUnit unit= (CompilationUnit) parser.createAST(null);
return unit.findDeclaringNode(meth.getKey()) == null;
}
return false;
}
private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) {
StringBuffer buf= new StringBuffer();
if (inOtherCU && !binding.isConstructor()) {
buf.append(binding.getDeclaringClass().getName()).append('.');
}
buf.append(binding.getName());
return getMethodSignature(buf.toString(), binding.getParameterTypes());
}
private static String getMethodSignature(String name, List args) {
ITypeBinding[] params= new ITypeBinding[args.size()];
for (int i= 0; i < args.size(); i++) {
Expression expr= (Expression) args.get(i);
ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
if (curr == null) {
curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
params[i]= curr;
}
return getMethodSignature(name, params);
}
private static String getMethodSignature(String name, ITypeBinding[] params) {
StringBuffer buf= new StringBuffer();
buf.append(name).append('(');
for (int i= 0; i < params.length; i++) {
if (i > 0) {
buf.append(", "); //$NON-NLS-1$
}
buf.append(params[i].getName());
}
buf.append(')');
return buf.toString();
}
private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException {
ITypeBinding[] paramTypes= methodBinding.getParameterTypes();
int[] indexOfDiff= new int[paramTypes.length];
int nDiffs= 0;
for (int n= 0; n < argTypes.length; n++) {
if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) {
indexOfDiff[nDiffs++]= n;
}
}
ITypeBinding declaringType= methodBinding.getDeclaringClass();
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode nameNode= problem.getCoveringNode(astRoot);
if (nameNode == null) {
return;
}
if (nDiffs == 0) {
if (nameNode.getParent() instanceof MethodInvocation) {
MethodInvocation inv= (MethodInvocation) nameNode.getParent();
if (inv.getExpression() == null) {
addQualifierToOuterProposal(context, inv, methodBinding, proposals);
}
}
return;
}
if (nDiffs == 1) { // one argument mismatching: try to fix
int idx= indexOfDiff[0];
Expression nodeToCast= (Expression) arguments.get(idx);
ITypeBinding castType= paramTypes[idx];
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding == null || TypeRules.canCast(castType, binding)) {
String castTypeName= castType.getQualifiedName();
ASTRewriteCorrectionProposal proposal= TypeMismatchSubProcessor.createCastProposal(context, castTypeName, nodeToCast, 6);
String[] arg= new String[] { getArgumentName(cu, arguments, idx), castTypeName};
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$
proposals.add(proposal);
}
TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, nodeToCast, castType, false, 5, proposals);
}
if (nDiffs == 2) { // try to swap
int idx1= indexOfDiff[0];
int idx2= indexOfDiff[1];
boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]);
if (canSwap) {
Expression arg1= (Expression) arguments.get(idx1);
Expression arg2= (Expression) arguments.get(idx2);
ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
rewrite.replace(arg1, rewrite.createCopyTarget(arg2), null);
rewrite.replace(arg2, rewrite.createCopyTarget(arg1), null);
{
String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposals.add(proposal);
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
changeDesc[idx1]= new SwapDescription(idx2);
}
ITypeBinding[] swappedTypes= new ITypeBinding[] { paramTypes[idx1], paramTypes[idx2] };
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 5, image);
proposals.add(proposal);
}
}
return;
}
}
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length];
for (int i= 0; i < nDiffs; i++) {
int diffIndex= indexOfDiff[i];
Expression arg= (Expression) arguments.get(diffIndex);
String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null;
changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name);
}
ITypeBinding[] newParamTypes= new ITypeBinding[changeDesc.length];
for (int i= 0; i < newParamTypes.length; i++) {
newParamTypes[i]= changeDesc[i] == null ? paramTypes[i] : ((EditDescription) changeDesc[i]).type;
}
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), newParamTypes) };
String label;
if (methodBinding.isConstructor()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$
}
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, null, 7, image);
proposals.add(proposal);
}
}
}
private static ITypeBinding[] getArgumentTypes(List arguments) {
ITypeBinding[] res= new ITypeBinding[arguments.size()];
for (int i= 0; i < res.length; i++) {
Expression expression= (Expression) arguments.get(i);
ITypeBinding curr= expression.resolveTypeBinding();
if (curr == null) {
return null;
}
if (!curr.isNullType()) { // don't normalize null type
curr= Bindings.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
}
res[i]= curr;
}
return res;
}
private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException {
ITypeBinding declaringType= binding.getDeclaringClass();
ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode);
ITypeBinding currType= parentType;
boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers());
while (currType != null && !Bindings.isSuperType(declaringType, currType)) {
if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) {
return;
}
currType= currType.getDeclaringClass();
}
if (currType == null || currType == parentType) {
return;
}
ASTRewrite rewrite= ASTRewrite.create(invocationNode.getAST());
ImportRewrite imports= new ImportRewrite(context.getCompilationUnit());
AST ast= invocationNode.getAST();
String qualifier= imports.addImport(currType);
Name name= ASTNodeFactory.newName(ast, qualifier);
Expression newExpression;
if (isInstanceMethod) {
ThisExpression expr= ast.newThisExpression();
expr.setQualifier(name);
newExpression= expr;
} else {
newExpression= name;
}
rewrite.set(invocationNode, MethodInvocation.EXPRESSION_PROPERTY, newExpression, null);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image);
proposal.setImportRewrite(imports);
proposals.add(proposal);
}
public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding= null;
List arguments= null;
IMethodBinding recursiveConstructor= 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= Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding.getSuperclass();
arguments= ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding;
arguments= ((ConstructorInvocation) selectedNode).arguments();
recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding();
}
}
if (targetBinding == null) {
return;
}
IMethodBinding[] methods= targetBinding.getDeclaredMethods();
ArrayList similarElements= new ArrayList();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && recursiveConstructor != curr) {
similarElements.add(curr); // similar elements can contain a implicit default constructor
}
}
addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals);
if (targetBinding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding);
if (targetCU != null) {
String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) };
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$
Image image= JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image));
}
}
}
public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= problem.getOffset();
int len= problem.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType && !TypeFilter.isFiltered((IType) curr)) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
ImportRewrite imports= new ImportRewrite(cu);
imports.setFindAmbiguosImports(true);
imports.addImport(qualifiedTypeName);
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, 5, image);
proposal.setImportRewrite(imports);
proposals.add(proposal);
}
}
}
public static void getArrayAccessProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) {
CompilationUnit root= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(root);
if (!(selectedNode instanceof MethodInvocation)) {
return;
}
MethodInvocation decl= (MethodInvocation) selectedNode;
SimpleName nameNode= decl.getName();
String methodName= nameNode.getIdentifier();
IBinding[] bindings= (new ScopeAnalyzer(root)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS);
for (int i= 0; i < bindings.length; i++) {
String currName= bindings[i].getName();
if (NameMatcher.isSimilarName(methodName, currName)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.arraychangetomethod.description", currName); //$NON-NLS-1$
proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), nameNode.getStartPosition(), nameNode.getLength(), currName, 6));
}
}
// always suggest 'length'
String lengthId= "length"; //$NON-NLS-1$
String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.arraychangetolength.description"); //$NON-NLS-1$
int offset= nameNode.getStartPosition();
int length= decl.getStartPosition() + decl.getLength() - offset;
proposals.add(new RenameNodeCompletionProposal(label, context.getCompilationUnit(), offset, length, lengthId, 7));
}
}
|
62,794
|
Bug 62794 Stub on code assist: Should check if method name is valid Java id
|
20040518 - between two method, enter 'while' press code assist - proposal is to create method 'while' created method is of course invalid -> should check if method name is not a keyword
|
verified fixed
|
1a5349a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-18T20:36:43Z
| 2004-05-18T19:53:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/MethodCompletionProposal.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text.java;
import java.util.Collection;
import java.util.Set;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.formatter.CodeFormatter;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
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.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
public class MethodCompletionProposal extends JavaTypeCompletionProposal {
public static void evaluateProposals(IType type, String prefix, int offset, int length, int relevance, Set suggestedMethods, Collection result) throws CoreException {
IMethod[] methods= type.getMethods();
String constructorName= type.getElementName();
if (constructorName.length() > 0 && constructorName.startsWith(prefix) && !hasMethod(methods, constructorName) && suggestedMethods.add(constructorName)) {
result.add(new MethodCompletionProposal(type, constructorName, null, offset, length, relevance));
}
if (prefix.length() > 0 && !"main".equals(prefix) && !hasMethod(methods, prefix) && suggestedMethods.add(prefix)) { //$NON-NLS-1$
result.add(new MethodCompletionProposal(type, prefix, Signature.SIG_VOID, offset, length, relevance));
}
}
private static boolean hasMethod(IMethod[] methods, String name) {
for (int i= 0; i < methods.length; i++) {
IMethod curr= methods[i];
if (curr.getElementName().equals(name) && curr.getParameterTypes().length == 0) {
return true;
}
}
return false;
}
private final IType fType;
private final String fReturnTypeSig;
private final String fMethodName;
public MethodCompletionProposal(IType type, String methodName, String returnTypeSig, int start, int length, int relevance) {
super("", type.getCompilationUnit(), start, length, null, getDisplayName(methodName, returnTypeSig), relevance); //$NON-NLS-1$
Assert.isNotNull(type);
Assert.isNotNull(methodName);
fType= type;
fMethodName= methodName;
fReturnTypeSig= returnTypeSig;
if (returnTypeSig == null) {
setProposalInfo(new ProposalInfo(type));
ImageDescriptor desc= new JavaElementImageDescriptor(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
setImage(JavaPlugin.getImageDescriptorRegistry().get(desc));
} else {
setImage(JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE));
}
}
private static String getDisplayName(String methodName, String returnTypeSig) {
StringBuffer buf= new StringBuffer();
buf.append(methodName);
buf.append('(');
buf.append(')');
if (returnTypeSig != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(Signature.toString(returnTypeSig));
buf.append(" - "); //$NON-NLS-1$
buf.append(JavaTextMessages.getString("MethodCompletionProposal.method.label")); //$NON-NLS-1$
} else {
buf.append(" - "); //$NON-NLS-1$
buf.append(JavaTextMessages.getString("MethodCompletionProposal.constructor.label")); //$NON-NLS-1$
}
return buf.toString();
}
/* (non-Javadoc)
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument, char, int, ImportsStructure)
*/
protected boolean updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException {
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
boolean addComments= settings.createComments;
String[] empty= new String[0];
String lineDelim= StubUtility.getLineDelimiterFor(document);
String declTypeName= fType.getTypeQualifiedName('.');
StringBuffer buf= new StringBuffer();
if (addComments) {
String comment= CodeGeneration.getMethodComment(fType.getCompilationUnit(), declTypeName, fMethodName, empty, empty, fReturnTypeSig, null, String.valueOf('\n'));
if (comment != null) {
buf.append(comment);
buf.append('\n');
}
}
if (fReturnTypeSig != null) {
buf.append("private "); //$NON-NLS-1$
} else {
buf.append("public "); //$NON-NLS-1$
}
if (fReturnTypeSig != null) {
buf.append(Signature.toString(fReturnTypeSig));
}
buf.append(' ');
buf.append(fMethodName);
buf.append("() {\n"); //$NON-NLS-1$
String body= CodeGeneration.getMethodBodyContent(fType.getCompilationUnit(), declTypeName, fMethodName, fReturnTypeSig == null, "", String.valueOf('\n')); //$NON-NLS-1$
if (body != null) {
buf.append(body);
buf.append('\n');
}
buf.append("}\n"); //$NON-NLS-1$
String stub= buf.toString();
// use the code formatter
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int lineStart= region.getOffset();
int indent= Strings.computeIndent(document.get(lineStart, getReplacementOffset() - lineStart), settings.tabWidth);
String replacement= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, stub, indent, null, lineDelim, fType.getJavaProject());
if (replacement.endsWith(lineDelim)) {
replacement= replacement.substring(0, replacement.length() - lineDelim.length());
}
setReplacementString(Strings.trimLeadingTabsAndSpaces(replacement));
return true;
}
}
|
62,840
|
Bug 62840 NPE while pasting
|
Build: I-20040518-2000 I copied a line from a bugzilla report using Ctrl-C I tried to paste it into my Java file (Ctrl-V) and I kept getting the following NPE: Error May 18, 2004 23:52:48.859 The command for the key you pressed failed java.lang.NullPointerException at org.eclipse.jdt.internal.ui.javaeditor.JavaEditor$OccurrencesFinderJobCanceler. documentAboutToBeChanged(JavaEditor.java:1410) at org.eclipse.jface.text.AbstractDocument.fireDocumentAboutToBeChanged (AbstractDocument.java:577) at org.eclipse.jface.text.AbstractDocument.replace (AbstractDocument.java:984) at org.eclipse.jdt.internal.ui.javaeditor.PartiallySynchronizedDocument.replace (PartiallySynchronizedDocument.java:92) at org.eclipse.jface.text.DefaultDocumentAdapter.replaceTextRange (DefaultDocumentAdapter.java:208) at org.eclipse.swt.custom.StyledText.modifyContent (StyledText.java:5565) at org.eclipse.swt.custom.StyledText.sendKeyEvent(StyledText.java:6405) at org.eclipse.swt.custom.StyledText.paste(StyledText.java:5602) at org.eclipse.jface.text.TextViewer.doOperation(TextViewer.java:3387) at org.eclipse.jface.text.source.SourceViewer.doOperation (SourceViewer.java:744) at org.eclipse.jface.text.source.projection.ProjectionViewer.doOperation (ProjectionViewer.java:1044) at org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer.doOperation (JavaSourceViewer.java:151) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewe r.doOperation(CompilationUnitEditor.java:198) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.doPasteWithImpo rtsOperation(ClipboardOperationAction.java:406) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.internalDoOpera tion(ClipboardOperationAction.java:244) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction$1.run (ClipboardOperationAction.java:224) at org.eclipse.swt.custom.BusyIndicator.showWhile (BusyIndicator.java:69) at org.eclipse.jdt.internal.ui.javaeditor.ClipboardOperationAction.run (ClipboardOperationAction.java:222) at org.eclipse.jface.action.Action.runWithEvent(Action.java:881) at org.eclipse.ui.commands.ActionHandler.execute (ActionHandler.java:141) at org.eclipse.ui.internal.commands.Command.execute(Command.java:132) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand (WorkbenchKeyboard.java:468) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press (WorkbenchKeyboard.java:886) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent (WorkbenchKeyboard.java:927) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings (WorkbenchKeyboard.java:545) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$2 (WorkbenchKeyboard.java:493) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent (WorkbenchKeyboard.java:258) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:712) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:795) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:820) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:805) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1724) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1720) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3048) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2951) at org.eclipse.swt.widgets.Display.windowProc(Display.java:3282) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1475) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:2380) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1363) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1334) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:253) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:141) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:97) at org.eclipse.core.internal.runtime.PlatformActivator$1.run (PlatformActivator.java:305) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:256) at org.eclipse.core.runtime.adaptor.EclipseStarter.run (EclipseStarter.java:127) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:184) at org.eclipse.core.launcher.Main.run(Main.java:637) at org.eclipse.core.launcher.Main.main(Main.java:621)
|
verified fixed
|
12bb438
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T07:36:55Z
| 2004-05-19T04:13:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.CollationElementIterator;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ISelectionValidator;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.link.LinkedModeModel;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension2;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextNavigationAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.util.IModifierConstants;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.ui.text.folding.IJavaFoldingStructureProvider;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.FoldingActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
import org.eclipse.jdt.internal.ui.search.MethodExitsFinder;
import org.eclipse.jdt.internal.ui.search.OccurrencesFinder;
import org.eclipse.jdt.internal.ui.text.CustomSourceInformationControl;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.JavaPresentationReconciler;
import org.eclipse.jdt.internal.ui.text.PreferencesAdapter;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaExpandHover;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider the selection provider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
// XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
JavaEditor.this.selectionChanged();
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/**
* Adapts an options {@link java.util.Map} to {@link org.eclipse.jface.preference.IPreferenceStore}.
* <p>
* This preference store is read-only i.e. write access
* throws an {@link java.lang.UnsupportedOperationException}.
* </p>
*
* @since 3.0
*/
private static class OptionsAdapter implements IPreferenceStore {
/**
* A property change event filter.
*/
public interface IPropertyChangeEventFilter {
/**
* Should the given event be filtered?
* @param event The property change event.
* @return <code>true</code> iff the given event should be filtered.
*/
public boolean isFiltered(PropertyChangeEvent event);
}
/**
* Property change listener. Listens for events in the options Map and
* fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
* on this adapter with arguments from the received event.
*/
private class PropertyChangeListener implements IPropertyChangeListener {
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent event) {
if (getFilter().isFiltered(event))
return;
if (event.getNewValue() == null)
fOptions.remove(event.getProperty());
else
fOptions.put(event.getProperty(), event.getNewValue());
firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
}
}
/** Listeners on this adapter */
private ListenerList fListeners= new ListenerList();
/** Listener on the adapted options Map */
private IPropertyChangeListener fListener= new PropertyChangeListener();
/** Adapted options Map */
private Map fOptions;
/** Preference store through which events are received. */
private IPreferenceStore fMockupPreferenceStore;
/** Property event filter. */
private IPropertyChangeEventFilter fFilter;
/**
* Initialize with the given options.
*
* @param options The options to wrap
* @param mockupPreferenceStore the mock-up preference store
* @param filter the property change filter
*/
public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
fMockupPreferenceStore= mockupPreferenceStore;
fOptions= options;
setFilter(filter);
}
/**
* {@inheritDoc}
*/
public void addPropertyChangeListener(IPropertyChangeListener listener) {
if (fListeners.size() == 0)
fMockupPreferenceStore.addPropertyChangeListener(fListener);
fListeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removePropertyChangeListener(IPropertyChangeListener listener) {
fListeners.remove(listener);
if (fListeners.size() == 0)
fMockupPreferenceStore.removePropertyChangeListener(fListener);
}
/**
* {@inheritDoc}
*/
public boolean contains(String name) {
return fOptions.containsKey(name);
}
/**
* {@inheritDoc}
*/
public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
((IPropertyChangeListener) listeners[i]).propertyChange(event);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(String name) {
boolean value= BOOLEAN_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null)
value= s.equals(TRUE);
return value;
}
/**
* {@inheritDoc}
*/
public boolean getDefaultBoolean(String name) {
return BOOLEAN_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDefaultDouble(String name) {
return DOUBLE_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public float getDefaultFloat(String name) {
return FLOAT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public int getDefaultInt(String name) {
return INT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public long getDefaultLong(String name) {
return LONG_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public String getDefaultString(String name) {
return STRING_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDouble(String name) {
double value= DOUBLE_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Double(s).doubleValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public float getFloat(String name) {
float value= FLOAT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Float(s).floatValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public int getInt(String name) {
int value= INT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Integer(s).intValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public long getLong(String name) {
long value= LONG_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Long(s).longValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public String getString(String name) {
String value= (String) fOptions.get(name);
if (value == null)
value= STRING_DEFAULT_DEFAULT;
return value;
}
/**
* {@inheritDoc}
*/
public boolean isDefault(String name) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean needsSaving() {
return !fOptions.isEmpty();
}
/**
* {@inheritDoc}
*/
public void putValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, String defaultObject) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setToDefault(String name) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* Returns the adapted options Map.
*
* @return Returns the adapted options Map.
*/
public Map getOptions() {
return fOptions;
}
/**
* Returns the mock-up preference store, events are received through this preference store.
* @return Returns the mock-up preference store.
*/
public IPreferenceStore getMockupPreferenceStore() {
return fMockupPreferenceStore;
}
/**
* Set the event filter to the given filter.
*
* @param filter The new filter.
*/
public void setFilter(IPropertyChangeEventFilter filter) {
fFilter= filter;
}
/**
* Returns the event filter.
*
* @return The event filter.
*/
public IPropertyChangeEventFilter getFilter() {
return fFilter;
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
((ITextViewerExtension4)sourceViewer).addTextPresentationListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fall back to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
sourceViewer.removeTextInputListener(this);
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider != null) {
IDocument document= documentProvider.getDocument(getEditorInput());
if (document != null)
document.removeDocumentListener(this);
}
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
*
* @param store the preference store
* @param key the key
* @param display the display
* @return the color or <code>null</code> if there is no such information available
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
fActiveRegion= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
// Invalidate ==> remove applied text presentation
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// Remove underline
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
try {
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, false);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
public void applyTextPresentation(TextPresentation textPresentation) {
if (fActiveRegion == null)
return;
IRegion region= textPresentation.getExtent();
if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// Underline
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
text.redrawRange(offset, length, false);
// Invalidate region ==> apply text presentation
fActiveRegion= region;
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
else
viewer.invalidateTextPresentation();
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != fKeyModifierMask) {
deactivate();
return;
}
fActive= true;
// removed for #25871
//
// ISourceViewer viewer= getSourceViewer();
// if (viewer == null)
// return;
//
// IRegion region= getCurrentTextRegion(viewer);
// if (region == null)
// return;
//
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != fKeyModifierMask) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
boolean wasActive= fCursor != null;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != fKeyModifierMask)
return;
// modifier was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fActive && fActiveRegion != null) {
fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
try {
event.getDocument().addPosition(fRememberedPosition);
} catch (BadLocationException x) {
fRememberedPosition= null;
}
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
if (fRememberedPosition != null) {
if (!fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
} else {
fActiveRegion= null;
fRememberedPosition= null;
deactivate();
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(fActiveRegion);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* Cancels the occurrences finder job upon document changes.
*
* @since 3.0
*/
class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
}
public void uninstall() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
sourceViewer.removeTextInputListener(this);
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider != null) {
IDocument document= documentProvider.getDocument(getEditorInput());
if (document != null)
document.removeDocumentListener(this);
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
fOccurrencesFinderJob.doCancel();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
}
/**
* This action behaves in two different ways: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*
* @param resourceBundle the resource bundle
* @param prefix the prefix
* @param textOperationAction the text operation action
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
if (extension4.moveFocusToWidgetToken())
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset, true);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
/**
* This action implements smart home.
*
* Instead of going to the start of a line it does the following:
*
* - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account.
* - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line
* - if the caret is at the beginning of the line see first case.
*
* @since 3.0
*/
protected class SmartLineStartAction extends LineStartAction {
/**
* Creates a new smart line start action
*
* @param textWidget the styled text widget
* @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected
*/
public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
super(textWidget, doSelect);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String)
*/
protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
String type= IDocument.DEFAULT_CONTENT_TYPE;
try {
type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
} catch (BadLocationException exception) {
// Should not happen
}
int index= super.getLineStartPosition(document, line, length, offset);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
} else {
if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
index++;
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
}
return index;
}
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected abstract class NextSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new next sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected NextSubWordAction(int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Check whether right hand character of caret is valid identifier start
if (Character.isJavaIdentifierStart(document.getChar(position))) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final String buffer= document.get(position, region.getOffset() + region.getLength() - position);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
do {
// Check whether we reached end of word
offset= iterator.getOffset();
if (!Character.isJavaIdentifierPart(document.getChar(position + offset)))
throw new BadLocationException();
// Test next characters
order= iterator.next();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check for leading underscores
position += offset;
if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) {
setCaretPosition(position);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected class NavigateNextSubWordAction extends NextSubWordAction {
/**
* Creates a new navigate next sub-word action.
*/
public NavigateNextSubWordAction() {
super(ST.WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the next sub-word.
*
* @since 3.0
*/
protected class DeleteNextSubWordAction extends NextSubWordAction {
/**
* Creates a new delete next sub-word action.
*/
public DeleteNextSubWordAction() {
super(ST.DELETE_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the next sub-word.
*
* @since 3.0
*/
protected class SelectNextSubWordAction extends NextSubWordAction {
/**
* Creates a new select next sub-word action.
*/
public SelectNextSubWordAction() {
super(ST.SELECT_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected abstract class PreviousSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new previous sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected PreviousSubWordAction(final int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1;
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Ignore trailing white spaces
char character= document.getChar(position);
while (position > 0 && Character.isWhitespace(character)) {
--position;
character= document.getChar(position);
}
// Check whether left hand character of caret is valid identifier part
if (Character.isJavaIdentifierPart(character)) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
iterator.setOffset(buffer.length() - 1);
do {
// Check whether we reached begin of word or single upper-case start
offset= iterator.getOffset();
character= document.getChar(region.getOffset() + offset);
if (!Character.isJavaIdentifierPart(character))
throw new BadLocationException();
else if (Character.isUpperCase(character)) {
++offset;
break;
}
// Test next characters
order= iterator.previous();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check left character for multiple upper-case characters
position= position - buffer.length() + offset - 1;
character= document.getChar(position);
while (position >= 0 && Character.isUpperCase(character))
character= document.getChar(--position);
setCaretPosition(position + 1);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new navigate previous sub-word action.
*/
public NavigatePreviousSubWordAction() {
super(ST.WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the previous sub-word.
*
* @since 3.0
*/
protected class DeletePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new delete previous sub-word action.
*/
public DeletePreviousSubWordAction() {
super(ST.DELETE_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the previous sub-word.
*
* @since 3.0
*/
protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new select previous sub-word action.
*/
public SelectPreviousSubWordAction() {
super(ST.SELECT_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Format element action to format the enclosing java element.
* <p>
* The format element action works as follows:
* <ul>
* <li>If there is no selection and the caret is positioned on a Java element,
* only this element is formatted. If the element has some accompanying comment,
* then the comment is formatted as well.</li>
* <li>If the selection spans one or more partitions of the document, then all
* partitions covered by the selection are entirely formatted.</li>
* <p>
* Partitions at the end of the selection are not completed, except for comments.
*
* @since 3.0
*/
protected class FormatElementAction extends Action {
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
if (viewer.isEditable()) {
final Point selection= viewer.rememberSelection();
try {
viewer.setRedraw(false);
final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x, true);
if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
try {
final IJavaElement element= getElementAt(selection.x, true);
if (element != null && element.exists()) {
final int kind= element.getElementType();
if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
final ISourceReference reference= (ISourceReference)element;
final ISourceRange range= reference.getSourceRange();
if (range != null) {
viewer.setSelectedRange(range.getOffset(), range.getLength());
viewer.doOperation(ISourceViewer.FORMAT);
}
}
}
} catch (JavaModelException exception) {
// Should not happen
}
} else {
viewer.setSelectedRange(selection.x, 1);
viewer.doOperation(ISourceViewer.FORMAT);
}
} catch (BadLocationException exception) {
// Can not happen
} finally {
viewer.setRedraw(true);
viewer.restoreSelection();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
if (fMarkOccurrenceAnnotations && isActivePart()) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/**
* Indicates whether this editor is about to update any annotation views.
* @since 3.0
*/
private boolean fIsUpdatingAnnotationViews= false;
/**
* The marker that served as last target for a goto marker request.
* @since 3.0
*/
private IMarker fLastMarkerTarget= null;
protected CompositeActionGroup fActionGroups;
/**
* The action group for folding.
*
* @since 3.0
*/
private FoldingActionGroup fFoldingGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Holds the current occurrence annotations.
* @since 3.0
*/
private Annotation[] fOccurrenceAnnotations= null;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* Tells whether the occurrence annotations are sticky
* i.e. whether they stay even if there's no valid Java
* element at the current caret position.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fStickyOccurrenceAnnotations;
/**
* Tells whether to mark type occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkTypeOccurrences;
/**
* Tells whether to mark method occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodOccurrences;
/**
* Tells whether to mark constant occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkConstantOccurrences;
/**
* Tells whether to mark field occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkFieldOccurrences;
/**
* Tells whether to mark local variable occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkLocalVariableypeOccurrences;
/**
* Tells whether to mark exception occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkExceptionOccurrences;
/**
* Tells whether to mark method exits in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodExitPoints;
/**
*
*/
private ISelection fForcedMarkOccurrencesSelection;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
private ISelectionListenerWithAST fPostSelectionListenerWithAST;
private OccurrencesFinderJob fOccurrencesFinderJob;
/** The occcurrences finder job canceler */
private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
/**
* This editor's projection support
* @since 3.0
*/
private ProjectionSupport fProjectionSupport;
/**
* This editor's projection model updater
* @since 3.0
*/
private IJavaFoldingStructureProvider fProjectionModelUpdater;
/**
* The override and implements indicator manager for this editor.
* @since 3.0
*/
protected OverrideIndicatorManager fOverrideIndicatorManager;
/**
* Semantic highlighting manager
* @since 3.0
*/
private SemanticHighlightingManager fSemanticManager;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement.
*
* @param element the java element
* @return the corresponding Java element
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*
* @param page the Java outline page
* @param input the editor input
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
*/
protected void initializeKeyBindingScopes() {
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
*/
protected void initializeEditor() {
IPreferenceStore store= createCombinedPreferenceStore(null);
setPreferenceStore(store);
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
fMarkTypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
fMarkMethodOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
fMarkConstantOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
fMarkFieldOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
fMarkLocalVariableypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
fMarkExceptionOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
fMarkMethodExitPoints= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore());
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
return ((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
}
/**
* Creates and returns the preference store for this Java editor with the given input.
*
* @param input The editor input for which to create the preference store
* @return the preference store for this editor
*
* @since 3.0
*/
private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
List stores= new ArrayList(3);
IJavaProject project= EditorUtility.getJavaProject(input);
if (project != null)
stores.add(new OptionsAdapter(project.getOptions(false), JavaPlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() {
public boolean isFiltered(PropertyChangeEvent event) {
IJavaElement inputJavaElement= getInputJavaElement();
IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
if (javaProject == null)
return true;
return !javaProject.getProject().equals(event.getSource());
}
}));
stores.add(JavaPlugin.getDefault().getPreferenceStore());
stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
stores.add(EditorsUI.getPreferenceStore());
return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
}
/**
* Sets the outliner's context menu ID.
*
* @param menuId the menu ID
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*
* @return returns this editor's standard action group
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*
* @return the created Java outline page
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
if (fProjectionSupport != null) {
Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
if (adapter != null)
return adapter;
}
return super.getAdapter(required);
}
/**
* React to changed selection.
*
* @since 3.0
*/
protected void selectionChanged() {
if (getSelectionProvider() == null)
return;
ISourceReference element= computeHighlightRangeSourceReference();
if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
synchronizeOutlinePage(element);
setSelection(element, false);
updateStatusLine();
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
if (getSelectionProvider() == null)
return;
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
// PR 39995: [navigation] Forward history cleared after going back in navigation history:
// mark only in navigation history if the cursor is being moved (which it isn't if
// this is called from a PostSelectionEvent that should only update the magnet)
if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0))
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= null;
if (reference instanceof ILocalVariable) {
IJavaElement je= ((ILocalVariable)reference).getParent();
if (je instanceof ISourceReference)
range= ((ISourceReference)je).getSourceRange();
} else
range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof ILocalVariable) {
range= ((ILocalVariable)reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set highlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
}
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(offset, length));
} else {
resetHighlightRange();
}
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
*/
protected void handleElementContentReplaced() {
super.handleElementContentReplaced();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
ISourceViewer sourceViewer= getSourceViewer();
if (!(sourceViewer instanceof ISourceViewerExtension2)) {
setPreferenceStore(createCombinedPreferenceStore(input));
internalDoSetInput(input);
return;
}
// uninstall & unregister preference store listener
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
getSourceViewerDecorationSupport(sourceViewer).uninstall();
((ISourceViewerExtension2)sourceViewer).unconfigure();
setPreferenceStore(createCombinedPreferenceStore(input));
// install & register preference store listener
sourceViewer.configure(getSourceViewerConfiguration());
getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
internalDoSetInput(input);
}
private void internalDoSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
if (isShowingOverrideIndicators())
installOverrideIndicator(true);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
* @since 3.0
*/
protected void setPreferenceStore(IPreferenceStore store) {
super.setPreferenceStore(store);
if (getSourceViewerConfiguration() instanceof JavaSourceViewerConfiguration) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
}
if (getSourceViewer() instanceof JavaSourceViewer)
((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.uninstall();
fProjectionModelUpdater= null;
}
if (fProjectionSupport != null) {
fProjectionSupport.dispose();
fProjectionSupport= null;
}
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
uninstallOccurrencesFinder();
uninstallOverrideIndicator();
uninstallSemanticHighlighting();
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
fFoldingGroup= new FoldingActionGroup(this, getViewer());
ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
action= new FormatElementAction();
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
setAction("QuickFormat", action); //$NON-NLS-1$
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
// add annotation actions
action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", action); //$NON-NLS-1$
// replace cut/copy paste actions with a version that implement 'add imports on paste'
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$
setAction(ITextEditorActionConstants.CUT, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Copy.", this, ITextOperationTarget.COPY); //$NON-NLS-1$
setAction(ITextEditorActionConstants.COPY, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
setAction(ITextEditorActionConstants.PASTE, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue())
selectionChanged();
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
enableOverwriteMode(!disable.booleanValue());
}
return;
}
if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
if (!fMarkOccurrenceAnnotations)
uninstallOccurrencesFinder();
else
installOccurrencesFinder();
}
}
return;
}
if (PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkTypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkConstantOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkFieldOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkLocalVariableypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkExceptionOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodExitPoints= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fStickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED.equals(property)) {
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
else
uninstallSemanticHighlighting();
return;
}
((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
if (affectsOverrideIndicatorAnnotations(event)) {
if (isShowingOverrideIndicators()) {
if (fOverrideIndicatorManager == null)
installOverrideIndicator(false);
} else {
if (fOverrideIndicatorManager != null)
uninstallOverrideIndicator();
}
return;
}
if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
if (sourceViewer instanceof ProjectionViewer) {
ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.uninstall();
// either freshly enabled or provider changed
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.install(this, projectionViewer);
}
}
return;
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
* @since 3.0
*/
protected void initializeViewerColors(ISourceViewer viewer) {
// is handled by JavaSourceViewer
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength(), false);
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param widgetLineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
boolean isFoldingEnabled() {
return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
}
});
fProjectionSupport.install();
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.install(this, projectionViewer);
if (isFoldingEnabled())
projectionViewer.doOperation(ProjectionViewer.TOGGLE);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
enableOverwriteMode(false);
if (fMarkOccurrenceAnnotations)
installOccurrencesFinder();
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews) {
super.gotoMarker(marker);
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$
method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set status line
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinderJob extends Job {
private IDocument fDocument;
private ISelection fSelection;
private ISelectionValidator fPostSelectionValidator;
private boolean fCanceled= false;
private IProgressMonitor fProgressMonitor;
private Position[] fPositions;
public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) {
super(JavaEditorMessages.getString("JavaEditor.markOccurrences.job.name")); //$NON-NLS-1$
fDocument= document;
fSelection= selection;
fPositions= positions;
if (getSelectionProvider() instanceof ISelectionValidator)
fPostSelectionValidator= (ISelectionValidator)getSelectionProvider();
}
// cannot use cancel() because it is declared final
void doCancel() {
fCanceled= true;
cancel();
}
private boolean isCanceled() {
return fCanceled || fProgressMonitor.isCanceled()
|| fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
|| LinkedModeModel.hasInstalledModel(fDocument);
}
/*
* @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus run(IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
if (isCanceled())
return Status.CANCEL_STATUS;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return Status.CANCEL_STATUS;
IDocument document= textViewer.getDocument();
if (document == null)
return Status.CANCEL_STATUS;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return Status.CANCEL_STATUS;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return Status.CANCEL_STATUS;
// Add occurrence annotations
int length= fPositions.length;
Map annotationMap= new HashMap(length);
for (int i= 0; i < length; i++) {
if (isCanceled())
return Status.CANCEL_STATUS;
String message;
Position position= fPositions[i];
// Create & add annotation
try {
message= document.get(position.offset, position.length);
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
position);
}
if (isCanceled())
return Status.CANCEL_STATUS;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
} else {
removeOccurrenceAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
return Status.OK_STATUS;
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @param selection the text selection
* @param astRoot the compilation unit AST
* @since 3.0
*/
protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) {
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.cancel();
if (!fMarkOccurrenceAnnotations)
return;
if (astRoot == null || selection == null)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
List matches= new ArrayList();
String message;
if (fMarkExceptionOccurrences || fMarkTypeOccurrences) {
ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= exceptionFinder.perform();
}
}
if (matches.size() == 0 && fMarkMethodExitPoints) {
MethodExitsFinder finder= new MethodExitsFinder();
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= finder.perform();
}
}
if (matches.size() == 0) {
ASTNode node= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
if (!(node instanceof Name)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
IBinding binding= ((Name)node).resolveBinding();
if (binding == null && fStickyOccurrenceAnnotations)
return;
if (!markOccurrencesOfType(binding)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
// Find the matches && extract positions so we can forget the AST
OccurrencesFinder finder = new OccurrencesFinder(binding);
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null)
matches= finder.perform();
} else if (!fMarkExceptionOccurrences) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
Position[] positions= new Position[matches.size()];
int i= 0;
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode currentNode= (ASTNode)each.next();
positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
}
fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions, selection);
//fOccurrencesFinderJob.setPriority(Job.DECORATE);
//fOccurrencesFinderJob.setSystem(true);
//fOccurrencesFinderJob.schedule();
fOccurrencesFinderJob.run(new NullProgressMonitor());
}
protected void installOccurrencesFinder() {
fMarkOccurrenceAnnotations= true;
fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
updateOccurrenceAnnotations(selection, astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
if (getSelectionProvider() != null) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
if (fOccurrencesFinderJobCanceler == null) {
fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
fOccurrencesFinderJobCanceler.install();
}
}
protected void uninstallOccurrencesFinder() {
fMarkOccurrenceAnnotations= false;
if (fOccurrencesFinderJob != null) {
fOccurrencesFinderJob.cancel();
fOccurrencesFinderJob= null;
}
if (fOccurrencesFinderJobCanceler != null) {
fOccurrencesFinderJobCanceler.uninstall();
fOccurrencesFinderJobCanceler= null;
}
if (fPostSelectionListenerWithAST != null) {
SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
fPostSelectionListenerWithAST= null;
}
removeOccurrenceAnnotations();
}
protected boolean isMarkingOccurrences() {
return fMarkOccurrenceAnnotations;
}
boolean markOccurrencesOfType(IBinding binding) {
if (binding == null)
return false;
int kind= binding.getKind();
if (fMarkTypeOccurrences && kind == IBinding.TYPE)
return true;
if (fMarkMethodOccurrences && kind == IBinding.METHOD)
return true;
if (kind == IBinding.VARIABLE) {
IVariableBinding variableBinding= (IVariableBinding)binding;
if (variableBinding.isField()) {
boolean isConstant= (variableBinding.getModifiers() & (IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL)) != 0;
if (isConstant)
return fMarkConstantOccurrences;
else
return fMarkFieldOccurrences;
}
return fMarkLocalVariableypeOccurrences;
}
return false;
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
protected void uninstallOverrideIndicator() {
if (fOverrideIndicatorManager != null) {
fOverrideIndicatorManager.removeAnnotations();
fOverrideIndicatorManager= null;
}
}
protected void installOverrideIndicator(boolean waitForReconcilation) {
uninstallOverrideIndicator();
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
IJavaElement inputElement= getInputJavaElement();
if (model == null || inputElement == null)
return;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast);
}
/**
* Tells whether override indicators are shown.
*
* @return <code>true</code> if the override indicators are shown
* @since 3.0
*/
protected boolean isShowingOverrideIndicators() {
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
IPreferenceStore store= getPreferenceStore();
return getBoolean(store, preference.getHighlightPreferenceKey())
|| getBoolean(store, preference.getVerticalRulerPreferenceKey())
|| getBoolean(store, preference.getOverviewRulerPreferenceKey())
|| getBoolean(store, preference.getTextPreferenceKey());
}
/**
* Returns the boolean preference for the given key.
*
* @param store the preference store
* @param key the preference key
* @return <code>true</code> if the key exists in the store and its value is <code>true</code>
* @since 3.0
*/
private boolean getBoolean(IPreferenceStore store, String key) {
return key != null && store.getBoolean(key);
}
/**
* Determines whether the preference change encoded by the given event
* changes the override indication.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a change
* @since 3.0
*/
protected boolean affectsOverrideIndicatorAnnotations(PropertyChangeEvent event) {
String key= event.getProperty();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
if (key == null || preference == null)
return false;
return key.equals(preference.getHighlightPreferenceKey())
|| key.equals(preference.getVerticalRulerPreferenceKey())
|| key.equals(preference.getOverviewRulerPreferenceKey())
|| key.equals(preference.getTextPreferenceKey());
}
/**
* @return <code>true</code> if Semantic Highlighting is enabled.
*
* @since 3.0
*/
private boolean isSemanticHighlightingEnabled() {
return getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED);
}
/**
* Install Semantic Highlighting.
*
* @since 3.0
*/
private void installSemanticHighlighting() {
if (fSemanticManager == null) {
fSemanticManager= new SemanticHighlightingManager();
JavaPresentationReconciler backgroundPresentationReconciler= (JavaPresentationReconciler) getSourceViewerConfiguration().getPresentationReconciler(getSourceViewer());
fSemanticManager.install(this, (JavaSourceViewer) getSourceViewer(), JavaPlugin.getDefault().getJavaTextTools().getColorManager(), getPreferenceStore(), backgroundPresentationReconciler);
}
}
/**
* Uninstall Semantic Highlighting.
*
* @since 3.0
*/
private void uninstallSemanticHighlighting() {
if (fSemanticManager != null) {
fSemanticManager.uninstall();
fSemanticManager= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
/**
* Returns the signed current selection.
* The length will be negative if the resulting selection
* is right-to-left (RtoL).
* <p>
* The selection offset is model based.
* </p>
*
* @param sourceViewer the source viewer
* @return a region denoting the current signed selection, for a resulting RtoL selections length is < 0
*/
protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
StyledText text= sourceViewer.getTextWidget();
Point selection= text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
selection.x= selection.x + selection.y;
selection.y= -selection.y;
}
selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x);
return new Region(selection.x, selection.y);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= EditorsUI.getPluginPreferences();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
*/
protected void createNavigationActions() {
super.createNavigationActions();
final StyledText textWidget= getSourceViewer().getTextWidget();
IAction action= new SmartLineStartAction(textWidget, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
setAction(ITextEditorActionDefinitionIds.LINE_START, action);
action= new SmartLineStartAction(textWidget, true);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
action= new NavigatePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
action= new NavigateNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
action= new DeletePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
action= new DeleteNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
action= new SelectPreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
action= new SelectNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
*/
protected CompositeRuler createCompositeRuler() {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
return super.createCompositeRuler();
CompositeRuler ruler= new CompositeRuler();
AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
// for now: just invoke ruler double click action
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
}
private void triggerAction(String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
// hack to propagate line change
if (action instanceof ISelectionListener) {
((ISelectionListener)action).selectionChanged(null, null);
}
if (action.isEnabled())
action.run();
}
}
}));
ruler.addDecorator(0, column);
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isPrefQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/**
* Returns the folding action group, or <code>null</code> if there is none.
*
* @return the folding action group, or <code>null</code> if there is none
* @since 3.0
*/
protected FoldingActionGroup getFoldingActionGroup() {
return fFoldingGroup;
}
}
|
62,873
|
Bug 62873 [misc] Mark occurrences detects static fields as constants
|
I200405190010 - disable "Mark constants" - enable "Mark non-constant fields" - in TestCase change fName to be static -> fName is no longer marked
|
resolved fixed
|
38a9feb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T11:32:36Z
| 2004-05-19T12:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.CollationElementIterator;
import java.text.Collator;
import java.text.RuleBasedCollator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.ST;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ISelectionValidator;
import org.eclipse.jface.text.ISynchronizable;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextPresentationListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITextViewerExtension5;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextPresentation;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.link.LinkedModeModel;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension2;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.LineChangeHover;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.text.source.projection.ProjectionSupport;
import org.eclipse.jface.text.source.projection.ProjectionViewer;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.EditorsUI;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.ChainedPreferenceStore;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextNavigationAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.util.IModifierConstants;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.ShowActionGroup;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.ui.text.folding.IJavaFoldingStructureProvider;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.FoldingActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.search.ExceptionOccurrencesFinder;
import org.eclipse.jdt.internal.ui.search.MethodExitsFinder;
import org.eclipse.jdt.internal.ui.search.OccurrencesFinder;
import org.eclipse.jdt.internal.ui.text.CustomSourceInformationControl;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.JavaPresentationReconciler;
import org.eclipse.jdt.internal.ui.text.PreferencesAdapter;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaExpandHover;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ISelectionListenerWithAST;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.SelectionListenerWithASTManager;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends AbstractDecoratedTextEditor implements IViewPartInputProvider {
/**
* Internal implementation class for a change listener.
* @since 3.0
*/
protected abstract class AbstractSelectionChangedListener implements ISelectionChangedListener {
/**
* Installs this selection changed listener with the given selection provider. If
* the selection provider is a post selection provider, post selection changed
* events are the preferred choice, otherwise normal selection changed events
* are requested.
*
* @param selectionProvider
*/
public void install(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.addPostSelectionChangedListener(this);
} else {
selectionProvider.addSelectionChangedListener(this);
}
}
/**
* Removes this selection changed listener from the given selection provider.
*
* @param selectionProvider the selection provider
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
// XXX: see https://bugs.eclipse.org/bugs/show_bug.cgi?id=56161
JavaEditor.this.selectionChanged();
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/**
* Adapts an options {@link java.util.Map} to {@link org.eclipse.jface.preference.IPreferenceStore}.
* <p>
* This preference store is read-only i.e. write access
* throws an {@link java.lang.UnsupportedOperationException}.
* </p>
*
* @since 3.0
*/
private static class OptionsAdapter implements IPreferenceStore {
/**
* A property change event filter.
*/
public interface IPropertyChangeEventFilter {
/**
* Should the given event be filtered?
* @param event The property change event.
* @return <code>true</code> iff the given event should be filtered.
*/
public boolean isFiltered(PropertyChangeEvent event);
}
/**
* Property change listener. Listens for events in the options Map and
* fires a {@link org.eclipse.jface.util.PropertyChangeEvent}
* on this adapter with arguments from the received event.
*/
private class PropertyChangeListener implements IPropertyChangeListener {
/**
* {@inheritDoc}
*/
public void propertyChange(PropertyChangeEvent event) {
if (getFilter().isFiltered(event))
return;
if (event.getNewValue() == null)
fOptions.remove(event.getProperty());
else
fOptions.put(event.getProperty(), event.getNewValue());
firePropertyChangeEvent(event.getProperty(), event.getOldValue(), event.getNewValue());
}
}
/** Listeners on this adapter */
private ListenerList fListeners= new ListenerList();
/** Listener on the adapted options Map */
private IPropertyChangeListener fListener= new PropertyChangeListener();
/** Adapted options Map */
private Map fOptions;
/** Preference store through which events are received. */
private IPreferenceStore fMockupPreferenceStore;
/** Property event filter. */
private IPropertyChangeEventFilter fFilter;
/**
* Initialize with the given options.
*
* @param options The options to wrap
* @param mockupPreferenceStore the mock-up preference store
* @param filter the property change filter
*/
public OptionsAdapter(Map options, IPreferenceStore mockupPreferenceStore, IPropertyChangeEventFilter filter) {
fMockupPreferenceStore= mockupPreferenceStore;
fOptions= options;
setFilter(filter);
}
/**
* {@inheritDoc}
*/
public void addPropertyChangeListener(IPropertyChangeListener listener) {
if (fListeners.size() == 0)
fMockupPreferenceStore.addPropertyChangeListener(fListener);
fListeners.add(listener);
}
/**
* {@inheritDoc}
*/
public void removePropertyChangeListener(IPropertyChangeListener listener) {
fListeners.remove(listener);
if (fListeners.size() == 0)
fMockupPreferenceStore.removePropertyChangeListener(fListener);
}
/**
* {@inheritDoc}
*/
public boolean contains(String name) {
return fOptions.containsKey(name);
}
/**
* {@inheritDoc}
*/
public void firePropertyChangeEvent(String name, Object oldValue, Object newValue) {
PropertyChangeEvent event= new PropertyChangeEvent(this, name, oldValue, newValue);
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
((IPropertyChangeListener) listeners[i]).propertyChange(event);
}
/**
* {@inheritDoc}
*/
public boolean getBoolean(String name) {
boolean value= BOOLEAN_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null)
value= s.equals(TRUE);
return value;
}
/**
* {@inheritDoc}
*/
public boolean getDefaultBoolean(String name) {
return BOOLEAN_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDefaultDouble(String name) {
return DOUBLE_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public float getDefaultFloat(String name) {
return FLOAT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public int getDefaultInt(String name) {
return INT_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public long getDefaultLong(String name) {
return LONG_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public String getDefaultString(String name) {
return STRING_DEFAULT_DEFAULT;
}
/**
* {@inheritDoc}
*/
public double getDouble(String name) {
double value= DOUBLE_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Double(s).doubleValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public float getFloat(String name) {
float value= FLOAT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Float(s).floatValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public int getInt(String name) {
int value= INT_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Integer(s).intValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public long getLong(String name) {
long value= LONG_DEFAULT_DEFAULT;
String s= (String) fOptions.get(name);
if (s != null) {
try {
value= new Long(s).longValue();
} catch (NumberFormatException e) {
}
}
return value;
}
/**
* {@inheritDoc}
*/
public String getString(String name) {
String value= (String) fOptions.get(name);
if (value == null)
value= STRING_DEFAULT_DEFAULT;
return value;
}
/**
* {@inheritDoc}
*/
public boolean isDefault(String name) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean needsSaving() {
return !fOptions.isEmpty();
}
/**
* {@inheritDoc}
*/
public void putValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, String defaultObject) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setDefault(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setToDefault(String name) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, double value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, float value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, int value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, long value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, String value) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
public void setValue(String name, boolean value) {
throw new UnsupportedOperationException();
}
/**
* Returns the adapted options Map.
*
* @return Returns the adapted options Map.
*/
public Map getOptions() {
return fOptions;
}
/**
* Returns the mock-up preference store, events are received through this preference store.
* @return Returns the mock-up preference store.
*/
public IPreferenceStore getMockupPreferenceStore() {
return fMockupPreferenceStore;
}
/**
* Set the event filter to the given filter.
*
* @param filter The new filter.
*/
public void setFilter(IPropertyChangeEventFilter filter) {
fFilter= filter;
}
/**
* Returns the event filter.
*
* @return The event filter.
*/
public IPropertyChangeEventFilter getFilter() {
return fFilter;
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener, ITextPresentationListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
((ITextViewerExtension4)sourceViewer).addTextPresentationListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fall back to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
sourceViewer.removeTextInputListener(this);
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider != null) {
IDocument document= documentProvider.getDocument(getEditorInput());
if (document != null)
document.removeDocumentListener(this);
}
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
((ITextViewerExtension4)sourceViewer).removeTextPresentationListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
*
* @param store the preference store
* @param key the key
* @param display the display
* @return the color or <code>null</code> if there is no such information available
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
fActiveRegion= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
// Invalidate ==> remove applied text presentation
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// Remove underline
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
try {
StyledText text= viewer.getTextWidget();
text.redrawRange(offset, length, false);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
public void applyTextPresentation(TextPresentation textPresentation) {
if (fActiveRegion == null)
return;
IRegion region= textPresentation.getExtent();
if (fActiveRegion.getOffset() + fActiveRegion.getLength() >= region.getOffset() && region.getOffset() + region.getLength() > fActiveRegion.getOffset())
textPresentation.mergeStyleRange(new StyleRange(fActiveRegion.getOffset(), fActiveRegion.getLength(), fColor, null));
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// Underline
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
text.redrawRange(offset, length, false);
// Invalidate region ==> apply text presentation
fActiveRegion= region;
if (viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(region.getOffset(), region.getLength());
else
viewer.invalidateTextPresentation();
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != fKeyModifierMask) {
deactivate();
return;
}
fActive= true;
// removed for #25871
//
// ISourceViewer viewer= getSourceViewer();
// if (viewer == null)
// return;
//
// IRegion region= getCurrentTextRegion(viewer);
// if (region == null)
// return;
//
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != fKeyModifierMask) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
boolean wasActive= fCursor != null;
deactivate();
if (wasActive) {
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action != null)
action.run();
}
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != fKeyModifierMask)
return;
// modifier was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fActive && fActiveRegion != null) {
fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
try {
event.getDocument().addPosition(fRememberedPosition);
} catch (BadLocationException x) {
fRememberedPosition= null;
}
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
if (fRememberedPosition != null) {
if (!fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
} else {
fActiveRegion= null;
fRememberedPosition= null;
deactivate();
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(fActiveRegion);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* Cancels the occurrences finder job upon document changes.
*
* @since 3.0
*/
class OccurrencesFinderJobCanceler implements IDocumentListener, ITextInputListener {
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
}
public void uninstall() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
sourceViewer.removeTextInputListener(this);
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider != null) {
IDocument document= documentProvider.getDocument(getEditorInput());
if (document != null)
document.removeDocumentListener(this);
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.doCancel();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
}
/**
* This action behaves in two different ways: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*
* @param resourceBundle the resource bundle
* @param prefix the prefix
* @param textOperationAction the text operation action
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
if (extension4.moveFocusToWidgetToken())
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
String contentType= TextUtilities.getContentType(sourceViewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, offset, true);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setDocumentPartitioning(IJavaPartitions.JAVA_PARTITIONING);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
/**
* This action implements smart home.
*
* Instead of going to the start of a line it does the following:
*
* - if smart home/end is enabled and the caret is after the line's first non-whitespace then the caret is moved directly before it, taking JavaDoc and multi-line comments into account.
* - if the caret is before the line's first non-whitespace the caret is moved to the beginning of the line
* - if the caret is at the beginning of the line see first case.
*
* @since 3.0
*/
protected class SmartLineStartAction extends LineStartAction {
/**
* Creates a new smart line start action
*
* @param textWidget the styled text widget
* @param doSelect a boolean flag which tells if the text up to the beginning of the line should be selected
*/
public SmartLineStartAction(final StyledText textWidget, final boolean doSelect) {
super(textWidget, doSelect);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor.LineStartAction#getLineStartPosition(java.lang.String, int, java.lang.String)
*/
protected int getLineStartPosition(final IDocument document, final String line, final int length, final int offset) {
String type= IDocument.DEFAULT_CONTENT_TYPE;
try {
type= TextUtilities.getContentType(document, IJavaPartitions.JAVA_PARTITIONING, offset, true);
} catch (BadLocationException exception) {
// Should not happen
}
int index= super.getLineStartPosition(document, line, length, offset);
if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) {
if (index < length - 1 && line.charAt(index) == '*' && line.charAt(index + 1) != '/') {
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
} else {
if (index < length - 1 && line.charAt(index) == '/' && line.charAt(index + 1) == '/') {
index++;
do {
++index;
} while (index < length && Character.isWhitespace(line.charAt(index)));
}
}
return index;
}
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected abstract class NextSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new next sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected NextSubWordAction(int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Check whether right hand character of caret is valid identifier start
if (Character.isJavaIdentifierStart(document.getChar(position))) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final String buffer= document.get(position, region.getOffset() + region.getLength() - position);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
do {
// Check whether we reached end of word
offset= iterator.getOffset();
if (!Character.isJavaIdentifierPart(document.getChar(position + offset)))
throw new BadLocationException();
// Test next characters
order= iterator.next();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check for leading underscores
position += offset;
if (Character.getType(document.getChar(position - 1)) != Character.CONNECTOR_PUNCTUATION) {
setCaretPosition(position);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the next sub-word.
*
* @since 3.0
*/
protected class NavigateNextSubWordAction extends NextSubWordAction {
/**
* Creates a new navigate next sub-word action.
*/
public NavigateNextSubWordAction() {
super(ST.WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the next sub-word.
*
* @since 3.0
*/
protected class DeleteNextSubWordAction extends NextSubWordAction {
/**
* Creates a new delete next sub-word action.
*/
public DeleteNextSubWordAction() {
super(ST.DELETE_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(caret, position - caret, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the next sub-word.
*
* @since 3.0
*/
protected class SelectNextSubWordAction extends NextSubWordAction {
/**
* Creates a new select next sub-word action.
*/
public SelectNextSubWordAction() {
super(ST.SELECT_WORD_NEXT);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.NextSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected abstract class PreviousSubWordAction extends TextNavigationAction {
/** Collator to determine the sub-word boundaries */
private final RuleBasedCollator fCollator= (RuleBasedCollator)Collator.getInstance();
/**
* Creates a new previous sub-word action.
*
* @param code Action code for the default operation. Must be an action code from @see org.eclipse.swt.custom.ST.
*/
protected PreviousSubWordAction(final int code) {
super(getSourceViewer().getTextWidget(), code);
// Only compare upper-/lower case
fCollator.setStrength(Collator.TERTIARY);
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
try {
final ISourceViewer viewer= getSourceViewer();
final IDocument document= viewer.getDocument();
int position= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset()) - 1;
// Check whether we are in a java code partition and the preference is enabled
final IPreferenceStore store= getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION)) {
super.run();
return;
}
// Ignore trailing white spaces
char character= document.getChar(position);
while (position > 0 && Character.isWhitespace(character)) {
--position;
character= document.getChar(position);
}
// Check whether left hand character of caret is valid identifier part
if (Character.isJavaIdentifierPart(character)) {
int offset= 0;
int order= CollationElementIterator.NULLORDER;
short previous= Short.MAX_VALUE;
short next= Short.MAX_VALUE;
// Acquire collator for partition around caret
final ITypedRegion region= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, position, false);
final String buffer= document.get(region.getOffset(), position - region.getOffset() + 1);
final CollationElementIterator iterator= fCollator.getCollationElementIterator(buffer);
// Iterate to first upper-case character
iterator.setOffset(buffer.length() - 1);
do {
// Check whether we reached begin of word or single upper-case start
offset= iterator.getOffset();
character= document.getChar(region.getOffset() + offset);
if (!Character.isJavaIdentifierPart(character))
throw new BadLocationException();
else if (Character.isUpperCase(character)) {
++offset;
break;
}
// Test next characters
order= iterator.previous();
next= CollationElementIterator.tertiaryOrder(order);
if (next <= previous)
previous= next;
else
break;
} while (order != CollationElementIterator.NULLORDER);
// Check left character for multiple upper-case characters
position= position - buffer.length() + offset - 1;
character= document.getChar(position);
while (position >= 0 && Character.isUpperCase(character))
character= document.getChar(--position);
setCaretPosition(position + 1);
getTextWidget().showSelection();
fireSelectionChanged();
return;
}
} catch (BadLocationException exception) {
// Use default behavior
}
super.run();
}
/**
* Sets the caret position to the sub-word boundary given with <code>position</code>.
*
* @param position Position where the action should move the caret
*/
protected abstract void setCaretPosition(int position);
}
/**
* Text navigation action to navigate to the previous sub-word.
*
* @since 3.0
*/
protected class NavigatePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new navigate previous sub-word action.
*/
public NavigatePreviousSubWordAction() {
super(ST.WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
getTextWidget().setCaretOffset(modelOffset2WidgetOffset(getSourceViewer(), position));
}
}
/**
* Text operation action to delete the previous sub-word.
*
* @since 3.0
*/
protected class DeletePreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new delete previous sub-word action.
*/
public DeletePreviousSubWordAction() {
super(ST.DELETE_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final int caret= widgetOffset2ModelOffset(viewer, viewer.getTextWidget().getCaretOffset());
try {
viewer.getDocument().replace(position, caret - position, ""); //$NON-NLS-1$
} catch (BadLocationException exception) {
// Should not happen
}
}
}
/**
* Text operation action to select the previous sub-word.
*
* @since 3.0
*/
protected class SelectPreviousSubWordAction extends PreviousSubWordAction {
/**
* Creates a new select previous sub-word action.
*/
public SelectPreviousSubWordAction() {
super(ST.SELECT_WORD_PREVIOUS);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor.PreviousSubWordAction#setCaretPosition(int)
*/
protected void setCaretPosition(final int position) {
final ISourceViewer viewer= getSourceViewer();
final StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed()) {
final Point selection= text.getSelection();
final int caret= text.getCaretOffset();
final int offset= modelOffset2WidgetOffset(viewer, position);
if (caret == selection.x)
text.setSelectionRange(selection.y, offset - selection.y);
else
text.setSelectionRange(selection.x, offset - selection.x);
}
}
}
/**
* Format element action to format the enclosing java element.
* <p>
* The format element action works as follows:
* <ul>
* <li>If there is no selection and the caret is positioned on a Java element,
* only this element is formatted. If the element has some accompanying comment,
* then the comment is formatted as well.</li>
* <li>If the selection spans one or more partitions of the document, then all
* partitions covered by the selection are entirely formatted.</li>
* <p>
* Partitions at the end of the selection are not completed, except for comments.
*
* @since 3.0
*/
protected class FormatElementAction extends Action {
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
final JavaSourceViewer viewer= (JavaSourceViewer) getSourceViewer();
if (viewer.isEditable()) {
final Point selection= viewer.rememberSelection();
try {
viewer.setRedraw(false);
final String type= TextUtilities.getContentType(viewer.getDocument(), IJavaPartitions.JAVA_PARTITIONING, selection.x, true);
if (type.equals(IDocument.DEFAULT_CONTENT_TYPE) && selection.y == 0) {
try {
final IJavaElement element= getElementAt(selection.x, true);
if (element != null && element.exists()) {
final int kind= element.getElementType();
if (kind == IJavaElement.TYPE || kind == IJavaElement.METHOD || kind == IJavaElement.INITIALIZER) {
final ISourceReference reference= (ISourceReference)element;
final ISourceRange range= reference.getSourceRange();
if (range != null) {
viewer.setSelectedRange(range.getOffset(), range.getLength());
viewer.doOperation(ISourceViewer.FORMAT);
}
}
}
} catch (JavaModelException exception) {
// Should not happen
}
} else {
viewer.setSelectedRange(selection.x, 1);
viewer.doOperation(ISourceViewer.FORMAT);
}
} catch (BadLocationException exception) {
// Can not happen
} finally {
viewer.setRedraw(true);
viewer.restoreSelection();
}
}
}
}
/**
* Internal activation listener.
* @since 3.0
*/
private class ActivationListener extends ShellAdapter {
/*
* @see org.eclipse.swt.events.ShellAdapter#shellActivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellActivated(ShellEvent e) {
if (fMarkOccurrenceAnnotations && isActivePart()) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(JavaEditor.this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
}
/*
* @see org.eclipse.swt.events.ShellAdapter#shellDeactivated(org.eclipse.swt.events.ShellEvent)
*/
public void shellDeactivated(ShellEvent e) {
removeOccurrenceAnnotations();
}
}
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/**
* Indicates whether this editor is about to update any annotation views.
* @since 3.0
*/
private boolean fIsUpdatingAnnotationViews= false;
/**
* The marker that served as last target for a goto marker request.
* @since 3.0
*/
private IMarker fLastMarkerTarget= null;
protected CompositeActionGroup fActionGroups;
/**
* The action group for folding.
*
* @since 3.0
*/
private FoldingActionGroup fFoldingGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Holds the current occurrence annotations.
* @since 3.0
*/
private Annotation[] fOccurrenceAnnotations= null;
/**
* Tells whether all occurrences of the element at the
* current caret location are automatically marked in
* this editor.
* @since 3.0
*/
private boolean fMarkOccurrenceAnnotations;
/**
* Tells whether the occurrence annotations are sticky
* i.e. whether they stay even if there's no valid Java
* element at the current caret position.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fStickyOccurrenceAnnotations;
/**
* Tells whether to mark type occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkTypeOccurrences;
/**
* Tells whether to mark method occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodOccurrences;
/**
* Tells whether to mark constant occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkConstantOccurrences;
/**
* Tells whether to mark field occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkFieldOccurrences;
/**
* Tells whether to mark local variable occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkLocalVariableypeOccurrences;
/**
* Tells whether to mark exception occurrences in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkExceptionOccurrences;
/**
* Tells whether to mark method exits in this editor.
* Only valid if {@link #fMarkOccurrenceAnnotations} is <code>true</code>.
* @since 3.0
*/
private boolean fMarkMethodExitPoints;
/**
*
*/
private ISelection fForcedMarkOccurrencesSelection;
/**
* The internal shell activation listener for updating occurrences.
* @since 3.0
*/
private ActivationListener fActivationListener= new ActivationListener();
private ISelectionListenerWithAST fPostSelectionListenerWithAST;
private OccurrencesFinderJob fOccurrencesFinderJob;
/** The occcurrences finder job canceler */
private OccurrencesFinderJobCanceler fOccurrencesFinderJobCanceler;
/**
* This editor's projection support
* @since 3.0
*/
private ProjectionSupport fProjectionSupport;
/**
* This editor's projection model updater
* @since 3.0
*/
private IJavaFoldingStructureProvider fProjectionModelUpdater;
/**
* The override and implements indicator manager for this editor.
* @since 3.0
*/
protected OverrideIndicatorManager fOverrideIndicatorManager;
/**
* Semantic highlighting manager
* @since 3.0
*/
private SemanticHighlightingManager fSemanticManager;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement.
*
* @param element the java element
* @return the corresponding Java element
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*
* @param page the Java outline page
* @param input the editor input
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeKeyBindingScopes()
*/
protected void initializeKeyBindingScopes() {
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#initializeEditor()
*/
protected void initializeEditor() {
IPreferenceStore store= createCombinedPreferenceStore(null);
setPreferenceStore(store);
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
fMarkOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_MARK_OCCURRENCES);
fStickyOccurrenceAnnotations= store.getBoolean(PreferenceConstants.EDITOR_STICKY_OCCURRENCES);
fMarkTypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES);
fMarkMethodOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES);
fMarkConstantOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES);
fMarkFieldOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES);
fMarkLocalVariableypeOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES);
fMarkExceptionOccurrences= store.getBoolean(PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES);
fMarkMethodExitPoints= store.getBoolean(PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS);
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, getPreferenceStore());
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
// ensure source viewer decoration support has been created and configured
getSourceViewerDecorationSupport(viewer);
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles, IPreferenceStore store) {
return new JavaSourceViewer(parent, verticalRuler, getOverviewRuler(), isOverviewRulerVisible(), styles, store);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
return ((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).affectsTextPresentation(event) || super.affectsTextPresentation(event);
}
/**
* Creates and returns the preference store for this Java editor with the given input.
*
* @param input The editor input for which to create the preference store
* @return the preference store for this editor
*
* @since 3.0
*/
private IPreferenceStore createCombinedPreferenceStore(IEditorInput input) {
List stores= new ArrayList(3);
IJavaProject project= EditorUtility.getJavaProject(input);
if (project != null)
stores.add(new OptionsAdapter(project.getOptions(false), JavaPlugin.getDefault().getMockupPreferenceStore(), new OptionsAdapter.IPropertyChangeEventFilter() {
public boolean isFiltered(PropertyChangeEvent event) {
IJavaElement inputJavaElement= getInputJavaElement();
IJavaProject javaProject= inputJavaElement != null ? inputJavaElement.getJavaProject() : null;
if (javaProject == null)
return true;
return !javaProject.getProject().equals(event.getSource());
}
}));
stores.add(JavaPlugin.getDefault().getPreferenceStore());
stores.add(new PreferencesAdapter(JavaCore.getPlugin().getPluginPreferences()));
stores.add(EditorsUI.getPreferenceStore());
return new ChainedPreferenceStore((IPreferenceStore[]) stores.toArray(new IPreferenceStore[stores.size()]));
}
/**
* Sets the outliner's context menu ID.
*
* @param menuId the menu ID
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*
* @return returns this editor's standard action group
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*
* @return the created Java outline page
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
synchronizeOutlinePage(element, true);
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
* @param checkIfOutlinePageActive <code>true</code> if check for active outline page needs to be done
*/
protected void synchronizeOutlinePage(ISourceReference element, boolean checkIfOutlinePageActive) {
if (fOutlinePage != null && element != null && !(checkIfOutlinePageActive && isJavaOutlinePageActive())) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
if (fProjectionSupport != null) {
Object adapter= fProjectionSupport.getAdapter(getSourceViewer(), required);
if (adapter != null)
return adapter;
}
return super.getAdapter(required);
}
/**
* React to changed selection.
*
* @since 3.0
*/
protected void selectionChanged() {
if (getSelectionProvider() == null)
return;
ISourceReference element= computeHighlightRangeSourceReference();
if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
synchronizeOutlinePage(element);
setSelection(element, false);
updateStatusLine();
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
if (getSelectionProvider() == null)
return;
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
// PR 39995: [navigation] Forward history cleared after going back in navigation history:
// mark only in navigation history if the cursor is being moved (which it isn't if
// this is called from a PostSelectionEvent that should only update the magnet)
if (moveCursor && (textSelection.getOffset() != 0 || textSelection.getLength() != 0))
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= null;
if (reference instanceof ILocalVariable) {
IJavaElement je= ((ILocalVariable)reference).getParent();
if (je instanceof ISourceReference)
range= ((ISourceReference)je).getSourceRange();
} else
range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof ILocalVariable) {
range= ((ILocalVariable)reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set highlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(range.getOffset(), range.getLength()));
}
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
ISourceViewer viewer= getSourceViewer();
if (viewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) viewer;
extension.exposeModelRange(new Region(offset, length));
} else {
resetHighlightRange();
}
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#handleElementContentReplaced()
*/
protected void handleElementContentReplaced() {
super.handleElementContentReplaced();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
ISourceViewer sourceViewer= getSourceViewer();
if (!(sourceViewer instanceof ISourceViewerExtension2)) {
setPreferenceStore(createCombinedPreferenceStore(input));
internalDoSetInput(input);
return;
}
// uninstall & unregister preference store listener
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
getSourceViewerDecorationSupport(sourceViewer).uninstall();
((ISourceViewerExtension2)sourceViewer).unconfigure();
setPreferenceStore(createCombinedPreferenceStore(input));
// install & register preference store listener
sourceViewer.configure(getSourceViewerConfiguration());
getSourceViewerDecorationSupport(sourceViewer).install(getPreferenceStore());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
internalDoSetInput(input);
}
private void internalDoSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.initialize();
if (isShowingOverrideIndicators())
installOverrideIndicator(true);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#setPreferenceStore(org.eclipse.jface.preference.IPreferenceStore)
* @since 3.0
*/
protected void setPreferenceStore(IPreferenceStore store) {
super.setPreferenceStore(store);
if (getSourceViewerConfiguration() instanceof JavaSourceViewerConfiguration) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools.getColorManager(), store, this, IJavaPartitions.JAVA_PARTITIONING));
}
if (getSourceViewer() instanceof JavaSourceViewer)
((JavaSourceViewer)getSourceViewer()).setPreferenceStore(store);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.uninstall();
fProjectionModelUpdater= null;
}
if (fProjectionSupport != null) {
fProjectionSupport.dispose();
fProjectionSupport= null;
}
// cancel possible running computation
fMarkOccurrenceAnnotations= false;
uninstallOccurrencesFinder();
uninstallOverrideIndicator();
uninstallSemanticHighlighting();
if (fActivationListener != null) {
Shell shell= getEditorSite().getShell();
if (shell != null && !shell.isDisposed())
shell.removeShellListener(fActivationListener);
fActivationListener= null;
}
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
if (fEditorSelectionChangedListener != null) {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ActionGroup oeg, ovg, jsg, sg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
sg= new ShowActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, sg, jsg});
fFoldingGroup= new FoldingActionGroup(this, getViewer());
ResourceAction resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
WorkbenchHelp.setHelp(resAction, IJavaHelpContextIds.SHOW_JAVADOC_ACTION);
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.SHOW_OUTLINE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_STRUCTURE_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenHierarchy.", this, JavaSourceViewer.SHOW_HIERARCHY, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY);
setAction(IJavaEditorActionDefinitionIds.OPEN_HIERARCHY, action);
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.OPEN_HIERARCHY_ACTION);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
action= new FormatElementAction();
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.QUICK_FORMAT);
setAction("QuickFormat", action); //$NON-NLS-1$
action= new RemoveOccurrenceAnnotations(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_OCCURRENCE_ANNOTATIONS);
setAction("RemoveOccurrenceAnnotations", action); //$NON-NLS-1$
// add annotation actions
action= new JavaSelectMarkerRulerAction2(JavaEditorMessages.getResourceBundle(), "Editor.RulerAnnotationSelection.", this); //$NON-NLS-1$
setAction("AnnotationAction", action); //$NON-NLS-1$
// replace cut/copy paste actions with a version that implement 'add imports on paste'
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Cut.", this, ITextOperationTarget.CUT); //$NON-NLS-1$
setAction(ITextEditorActionConstants.CUT, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Copy.", this, ITextOperationTarget.COPY); //$NON-NLS-1$
setAction(ITextEditorActionConstants.COPY, action);
action= new ClipboardOperationAction(JavaEditorMessages.getResourceBundle(), "Editor.Paste.", this, ITextOperationTarget.PASTE); //$NON-NLS-1$
setAction(ITextEditorActionConstants.PASTE, action);
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue())
selectionChanged();
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
enableOverwriteMode(!disable.booleanValue());
}
return;
}
if (PreferenceConstants.EDITOR_MARK_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
boolean markOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
if (markOccurrenceAnnotations != fMarkOccurrenceAnnotations) {
fMarkOccurrenceAnnotations= markOccurrenceAnnotations;
if (!fMarkOccurrenceAnnotations)
uninstallOccurrencesFinder();
else
installOccurrencesFinder();
}
}
return;
}
if (PreferenceConstants.EDITOR_MARK_TYPE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkTypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_CONSTANT_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkConstantOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_FIELD_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkFieldOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_LOCAL_VARIABLE_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkLocalVariableypeOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_EXCEPTION_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkExceptionOccurrences= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_MARK_METHOD_EXIT_POINTS.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fMarkMethodExitPoints= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_STICKY_OCCURRENCES.equals(property)) {
if (event.getNewValue() instanceof Boolean)
fStickyOccurrenceAnnotations= ((Boolean)event.getNewValue()).booleanValue();
return;
}
if (PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED.equals(property)) {
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
else
uninstallSemanticHighlighting();
return;
}
((JavaSourceViewerConfiguration)getSourceViewerConfiguration()).handlePropertyChangeEvent(event);
if (affectsOverrideIndicatorAnnotations(event)) {
if (isShowingOverrideIndicators()) {
if (fOverrideIndicatorManager == null)
installOverrideIndicator(false);
} else {
if (fOverrideIndicatorManager != null)
uninstallOverrideIndicator();
}
return;
}
if (PreferenceConstants.EDITOR_FOLDING_PROVIDER.equals(property)) {
if (sourceViewer instanceof ProjectionViewer) {
ProjectionViewer projectionViewer= (ProjectionViewer) sourceViewer;
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.uninstall();
// either freshly enabled or provider changed
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null) {
fProjectionModelUpdater.install(this, projectionViewer);
}
}
return;
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/**
* Initializes the given viewer's colors.
*
* @param viewer the viewer to be initialized
* @since 3.0
*/
protected void initializeViewerColors(ISourceViewer viewer) {
// is handled by JavaSourceViewer
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Returns a segmentation of the line of the given viewer's input document appropriate for
* bidi rendering. The default implementation returns only the string literals of a java code
* line as segments.
*
* @param viewer the text viewer
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(ITextViewer viewer, int lineOffset) throws BadLocationException {
IDocument document= viewer.getDocument();
if (document == null)
return null;
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= TextUtilities.computePartitioning(document, IJavaPartitions.JAVA_PARTITIONING, lineOffset, line.getLength(), false);
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param widgetLineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
if (line != null && line.length() > 0) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null) {
int lineOffset;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
try {
return getBidiLineSegments(sourceViewer, lineOffset);
} catch (BadLocationException x) {
// don't segment line in this case
}
}
}
return null;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
boolean isFoldingEnabled() {
return JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FOLDING_ENABLED);
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
ProjectionViewer projectionViewer= (ProjectionViewer) getSourceViewer();
fProjectionSupport= new ProjectionSupport(projectionViewer, getAnnotationAccess(), getSharedColors());
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.error"); //$NON-NLS-1$
fProjectionSupport.addSummarizableAnnotationType("org.eclipse.ui.workbench.texteditor.warning"); //$NON-NLS-1$
fProjectionSupport.setHoverControlCreator(new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
return new CustomSourceInformationControl(shell, IDocument.DEFAULT_CONTENT_TYPE);
}
});
fProjectionSupport.install();
fProjectionModelUpdater= JavaPlugin.getDefault().getFoldingStructureProviderRegistry().getCurrentFoldingProvider();
if (fProjectionModelUpdater != null)
fProjectionModelUpdater.install(this, projectionViewer);
if (isFoldingEnabled())
projectionViewer.doOperation(ProjectionViewer.TOGGLE);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
enableOverwriteMode(false);
if (fMarkOccurrenceAnnotations)
installOccurrencesFinder();
if (isSemanticHighlightingEnabled())
installSemanticHighlighting();
getEditorSite().getShell().addShellListener(fActivationListener);
}
protected void configureSourceViewerDecorationSupport(SourceViewerDecorationSupport support) {
support.setCharacterPairMatcher(fBracketMatcher);
support.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
super.configureSourceViewerDecorationSupport(support);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#gotoMarker(org.eclipse.core.resources.IMarker)
*/
public void gotoMarker(IMarker marker) {
fLastMarkerTarget= marker;
if (!fIsUpdatingAnnotationViews) {
super.gotoMarker(marker);
}
}
/**
* Jumps to the next enabled annotation according to the given direction.
* An annotation type is enabled if it is configured to be in the
* Next/Previous tool bar drop down menu and if it is checked.
*
* @param forward <code>true</code> if search direction is forward, <code>false</code> if backward
*/
public void gotoAnnotation(boolean forward) {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Position position= new Position(0, 0);
if (false /* delayed - see bug 18316 */) {
getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
selectAndReveal(position.getOffset(), position.getLength());
} else /* no delay - see bug 18316 */ {
Annotation annotation= getNextAnnotation(selection.getOffset(), selection.getLength(), forward, position);
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
updateAnnotationViews(annotation);
selectAndReveal(position.getOffset(), position.getLength());
setStatusLineMessage(annotation.getText());
}
}
}
/**
* Returns the lock object for the given annotation model.
*
* @param annotationModel the annotation model
* @return the annotation model's lock object
* @since 3.0
*/
private Object getLockObject(IAnnotationModel annotationModel) {
if (annotationModel instanceof ISynchronizable)
return ((ISynchronizable)annotationModel).getLockObject();
else
return annotationModel;
}
/**
* Updates the annotation views that show the given annotation.
*
* @param annotation the annotation
*/
private void updateAnnotationViews(Annotation annotation) {
IMarker marker= null;
if (annotation instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) annotation).getMarker();
else if (annotation instanceof IJavaAnnotation) {
Iterator e= ((IJavaAnnotation) annotation).getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null && !marker.equals(fLastMarkerTarget)) {
try {
boolean isProblem= marker.isSubtypeOf(IMarker.PROBLEM);
IWorkbenchPage page= getSite().getPage();
IViewPart view= page.findView(isProblem ? IPageLayout.ID_PROBLEM_VIEW: IPageLayout.ID_TASK_LIST); //$NON-NLS-1$ //$NON-NLS-2$
if (view != null) {
Method method= view.getClass().getMethod("setSelection", new Class[] { IStructuredSelection.class, boolean.class}); //$NON-NLS-1$
method.invoke(view, new Object[] {new StructuredSelection(marker), Boolean.TRUE });
}
} catch (CoreException x) {
} catch (NoSuchMethodException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
}
// ignore exceptions, don't update any of the lists, just set status line
}
}
/**
* Finds and marks occurrence annotations.
*
* @since 3.0
*/
class OccurrencesFinderJob extends Job {
private IDocument fDocument;
private ISelection fSelection;
private ISelectionValidator fPostSelectionValidator;
private boolean fCanceled= false;
private IProgressMonitor fProgressMonitor;
private Position[] fPositions;
public OccurrencesFinderJob(IDocument document, Position[] positions, ISelection selection) {
super(JavaEditorMessages.getString("JavaEditor.markOccurrences.job.name")); //$NON-NLS-1$
fDocument= document;
fSelection= selection;
fPositions= positions;
if (getSelectionProvider() instanceof ISelectionValidator)
fPostSelectionValidator= (ISelectionValidator)getSelectionProvider();
}
// cannot use cancel() because it is declared final
void doCancel() {
fCanceled= true;
cancel();
}
private boolean isCanceled() {
return fCanceled || fProgressMonitor.isCanceled()
|| fPostSelectionValidator != null && !(fPostSelectionValidator.isValid(fSelection) || fForcedMarkOccurrencesSelection == fSelection)
|| LinkedModeModel.hasInstalledModel(fDocument);
}
/*
* @see Job#run(org.eclipse.core.runtime.IProgressMonitor)
*/
public IStatus run(IProgressMonitor progressMonitor) {
fProgressMonitor= progressMonitor;
if (isCanceled())
return Status.CANCEL_STATUS;
ITextViewer textViewer= getViewer();
if (textViewer == null)
return Status.CANCEL_STATUS;
IDocument document= textViewer.getDocument();
if (document == null)
return Status.CANCEL_STATUS;
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return Status.CANCEL_STATUS;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null)
return Status.CANCEL_STATUS;
// Add occurrence annotations
int length= fPositions.length;
Map annotationMap= new HashMap(length);
for (int i= 0; i < length; i++) {
if (isCanceled())
return Status.CANCEL_STATUS;
String message;
Position position= fPositions[i];
// Create & add annotation
try {
message= document.get(position.offset, position.length);
} catch (BadLocationException ex) {
// Skip this match
continue;
}
annotationMap.put(
new Annotation("org.eclipse.jdt.ui.occurrences", false, message), //$NON-NLS-1$
position);
}
if (isCanceled())
return Status.CANCEL_STATUS;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, annotationMap);
} else {
removeOccurrenceAnnotations();
Iterator iter= annotationMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry mapEntry= (Map.Entry)iter.next();
annotationModel.addAnnotation((Annotation)mapEntry.getKey(), (Position)mapEntry.getValue());
}
}
fOccurrenceAnnotations= (Annotation[])annotationMap.keySet().toArray(new Annotation[annotationMap.keySet().size()]);
}
return Status.OK_STATUS;
}
}
/**
* Updates the occurrences annotations based
* on the current selection.
*
* @param selection the text selection
* @param astRoot the compilation unit AST
* @since 3.0
*/
protected void updateOccurrenceAnnotations(ITextSelection selection, CompilationUnit astRoot) {
if (fOccurrencesFinderJob != null)
fOccurrencesFinderJob.cancel();
if (!fMarkOccurrenceAnnotations)
return;
if (astRoot == null || selection == null)
return;
IDocument document= getSourceViewer().getDocument();
if (document == null)
return;
List matches= new ArrayList();
String message;
if (fMarkExceptionOccurrences || fMarkTypeOccurrences) {
ExceptionOccurrencesFinder exceptionFinder= new ExceptionOccurrencesFinder();
message= exceptionFinder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= exceptionFinder.perform();
}
}
if (matches.size() == 0 && fMarkMethodExitPoints) {
MethodExitsFinder finder= new MethodExitsFinder();
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null) {
matches= finder.perform();
}
}
if (matches.size() == 0) {
ASTNode node= NodeFinder.perform(astRoot, selection.getOffset(), selection.getLength());
if (!(node instanceof Name)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
IBinding binding= ((Name)node).resolveBinding();
if (binding == null && fStickyOccurrenceAnnotations)
return;
if (!markOccurrencesOfType(binding)) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
// Find the matches && extract positions so we can forget the AST
OccurrencesFinder finder = new OccurrencesFinder(binding);
message= finder.initialize(astRoot, selection.getOffset(), selection.getLength());
if (message == null)
matches= finder.perform();
} else if (!fMarkExceptionOccurrences) {
if (!fStickyOccurrenceAnnotations)
removeOccurrenceAnnotations();
return;
}
Position[] positions= new Position[matches.size()];
int i= 0;
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode currentNode= (ASTNode)each.next();
positions[i++]= new Position(currentNode.getStartPosition(), currentNode.getLength());
}
fOccurrencesFinderJob= new OccurrencesFinderJob(document, positions, selection);
//fOccurrencesFinderJob.setPriority(Job.DECORATE);
//fOccurrencesFinderJob.setSystem(true);
//fOccurrencesFinderJob.schedule();
fOccurrencesFinderJob.run(new NullProgressMonitor());
}
protected void installOccurrencesFinder() {
fMarkOccurrenceAnnotations= true;
fPostSelectionListenerWithAST= new ISelectionListenerWithAST() {
public void selectionChanged(IEditorPart part, ITextSelection selection, CompilationUnit astRoot) {
updateOccurrenceAnnotations(selection, astRoot);
}
};
SelectionListenerWithASTManager.getDefault().addListener(this, fPostSelectionListenerWithAST);
if (getSelectionProvider() != null) {
fForcedMarkOccurrencesSelection= getSelectionProvider().getSelection();
SelectionListenerWithASTManager.getDefault().forceSelectionChange(this, (ITextSelection)fForcedMarkOccurrencesSelection);
}
if (fOccurrencesFinderJobCanceler == null) {
fOccurrencesFinderJobCanceler= new OccurrencesFinderJobCanceler();
fOccurrencesFinderJobCanceler.install();
}
}
protected void uninstallOccurrencesFinder() {
fMarkOccurrenceAnnotations= false;
if (fOccurrencesFinderJob != null) {
fOccurrencesFinderJob.cancel();
fOccurrencesFinderJob= null;
}
if (fOccurrencesFinderJobCanceler != null) {
fOccurrencesFinderJobCanceler.uninstall();
fOccurrencesFinderJobCanceler= null;
}
if (fPostSelectionListenerWithAST != null) {
SelectionListenerWithASTManager.getDefault().removeListener(this, fPostSelectionListenerWithAST);
fPostSelectionListenerWithAST= null;
}
removeOccurrenceAnnotations();
}
protected boolean isMarkingOccurrences() {
return fMarkOccurrenceAnnotations;
}
boolean markOccurrencesOfType(IBinding binding) {
if (binding == null)
return false;
int kind= binding.getKind();
if (fMarkTypeOccurrences && kind == IBinding.TYPE)
return true;
if (fMarkMethodOccurrences && kind == IBinding.METHOD)
return true;
if (kind == IBinding.VARIABLE) {
IVariableBinding variableBinding= (IVariableBinding)binding;
if (variableBinding.isField()) {
boolean isConstant= (variableBinding.getModifiers() & (IModifierConstants.ACC_STATIC | IModifierConstants.ACC_FINAL)) != 0;
if (isConstant)
return fMarkConstantOccurrences;
else
return fMarkFieldOccurrences;
}
return fMarkLocalVariableypeOccurrences;
}
return false;
}
void removeOccurrenceAnnotations() {
IDocumentProvider documentProvider= getDocumentProvider();
if (documentProvider == null)
return;
IAnnotationModel annotationModel= documentProvider.getAnnotationModel(getEditorInput());
if (annotationModel == null || fOccurrenceAnnotations == null)
return;
synchronized (getLockObject(annotationModel)) {
if (annotationModel instanceof IAnnotationModelExtension) {
((IAnnotationModelExtension)annotationModel).replaceAnnotations(fOccurrenceAnnotations, null);
} else {
for (int i= 0, length= fOccurrenceAnnotations.length; i < length; i++)
annotationModel.removeAnnotation(fOccurrenceAnnotations[i]);
}
fOccurrenceAnnotations= null;
}
}
protected void uninstallOverrideIndicator() {
if (fOverrideIndicatorManager != null) {
fOverrideIndicatorManager.removeAnnotations();
fOverrideIndicatorManager= null;
}
}
protected void installOverrideIndicator(boolean waitForReconcilation) {
uninstallOverrideIndicator();
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
IJavaElement inputElement= getInputJavaElement();
if (model == null || inputElement == null)
return;
CompilationUnit ast= JavaPlugin.getDefault().getASTProvider().getAST(inputElement, true, null);
fOverrideIndicatorManager= new OverrideIndicatorManager(model, inputElement, ast);
}
/**
* Tells whether override indicators are shown.
*
* @return <code>true</code> if the override indicators are shown
* @since 3.0
*/
protected boolean isShowingOverrideIndicators() {
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
IPreferenceStore store= getPreferenceStore();
return getBoolean(store, preference.getHighlightPreferenceKey())
|| getBoolean(store, preference.getVerticalRulerPreferenceKey())
|| getBoolean(store, preference.getOverviewRulerPreferenceKey())
|| getBoolean(store, preference.getTextPreferenceKey());
}
/**
* Returns the boolean preference for the given key.
*
* @param store the preference store
* @param key the preference key
* @return <code>true</code> if the key exists in the store and its value is <code>true</code>
* @since 3.0
*/
private boolean getBoolean(IPreferenceStore store, String key) {
return key != null && store.getBoolean(key);
}
/**
* Determines whether the preference change encoded by the given event
* changes the override indication.
*
* @param event the event to be investigated
* @return <code>true</code> if event causes a change
* @since 3.0
*/
protected boolean affectsOverrideIndicatorAnnotations(PropertyChangeEvent event) {
String key= event.getProperty();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(OverrideIndicatorManager.ANNOTATION_TYPE);
if (key == null || preference == null)
return false;
return key.equals(preference.getHighlightPreferenceKey())
|| key.equals(preference.getVerticalRulerPreferenceKey())
|| key.equals(preference.getOverviewRulerPreferenceKey())
|| key.equals(preference.getTextPreferenceKey());
}
/**
* @return <code>true</code> if Semantic Highlighting is enabled.
*
* @since 3.0
*/
private boolean isSemanticHighlightingEnabled() {
return getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SEMANTIC_HIGHLIGHTING_ENABLED);
}
/**
* Install Semantic Highlighting.
*
* @since 3.0
*/
private void installSemanticHighlighting() {
if (fSemanticManager == null) {
fSemanticManager= new SemanticHighlightingManager();
JavaPresentationReconciler backgroundPresentationReconciler= (JavaPresentationReconciler) getSourceViewerConfiguration().getPresentationReconciler(getSourceViewer());
fSemanticManager.install(this, (JavaSourceViewer) getSourceViewer(), JavaPlugin.getDefault().getJavaTextTools().getColorManager(), getPreferenceStore(), backgroundPresentationReconciler);
}
}
/**
* Uninstall Semantic Highlighting.
*
* @since 3.0
*/
private void uninstallSemanticHighlighting() {
if (fSemanticManager != null) {
fSemanticManager.uninstall();
fSemanticManager= null;
}
}
/**
* Returns the Java element wrapped by this editors input.
*
* @return the Java element wrapped by this editors input.
* @since 3.0
*/
abstract protected IJavaElement getInputJavaElement();
protected void updateStatusLine() {
ITextSelection selection= (ITextSelection) getSelectionProvider().getSelection();
Annotation annotation= getAnnotation(selection.getOffset(), selection.getLength());
setStatusLineErrorMessage(null);
setStatusLineMessage(null);
if (annotation != null) {
try {
fIsUpdatingAnnotationViews= true;
updateAnnotationViews(annotation);
} finally {
fIsUpdatingAnnotationViews= false;
}
if (annotation instanceof IJavaAnnotation && ((IJavaAnnotation) annotation).isProblem())
setStatusLineMessage(annotation.getText());
}
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Sets the given message as error message to this editor's status line.
*
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
/**
* Sets the given message as message to this editor's status line.
*
* @param msg message to be set
* @since 3.0
*/
protected void setStatusLineMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(false, msg, null);
}
/**
* Returns the signed current selection.
* The length will be negative if the resulting selection
* is right-to-left (RtoL).
* <p>
* The selection offset is model based.
* </p>
*
* @param sourceViewer the source viewer
* @return a region denoting the current signed selection, for a resulting RtoL selections length is < 0
*/
protected IRegion getSignedSelection(ISourceViewer sourceViewer) {
StyledText text= sourceViewer.getTextWidget();
Point selection= text.getSelectionRange();
if (text.getCaretOffset() == selection.x) {
selection.x= selection.x + selection.y;
selection.y= -selection.y;
}
selection.x= widgetOffset2ModelOffset(sourceViewer, selection.x);
return new Region(selection.x, selection.y);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Returns the annotation closest to the given range respecting the given
* direction. If an annotation is found, the annotations current position
* is copied into the provided annotation position.
*
* @param offset the region offset
* @param length the region length
* @param forward <code>true</code> for forwards, <code>false</code> for backward
* @param annotationPosition the position of the found annotation
* @return the found annotation
*/
private Annotation getNextAnnotation(final int offset, final int length, boolean forward, Position annotationPosition) {
Annotation nextAnnotation= null;
Position nextAnnotationPosition= null;
Annotation containingAnnotation= null;
Position containingAnnotationPosition= null;
boolean currentAnnotation= false;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= Integer.MAX_VALUE;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if ((a instanceof IJavaAnnotation) && ((IJavaAnnotation)a).hasOverlay() || !isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p == null)
continue;
if (forward && p.offset == offset || !forward && p.offset + p.getLength() == offset + length) {// || p.includes(offset)) {
if (containingAnnotation == null || (forward && p.length >= containingAnnotationPosition.length || !forward && p.length >= containingAnnotationPosition.length)) {
containingAnnotation= a;
containingAnnotationPosition= p;
currentAnnotation= p.length == length;
}
} else {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
} else {
currentDistance= offset + length - (p.getOffset() + p.length);
if (currentDistance < 0)
currentDistance= endOfDocument + currentDistance;
if (currentDistance < distance || currentDistance == distance && p.length < nextAnnotationPosition.length) {
distance= currentDistance;
nextAnnotation= a;
nextAnnotationPosition= p;
}
}
}
}
if (containingAnnotationPosition != null && (!currentAnnotation || nextAnnotation == null)) {
annotationPosition.setOffset(containingAnnotationPosition.getOffset());
annotationPosition.setLength(containingAnnotationPosition.getLength());
return containingAnnotation;
}
if (nextAnnotationPosition != null) {
annotationPosition.setOffset(nextAnnotationPosition.getOffset());
annotationPosition.setLength(nextAnnotationPosition.getLength());
}
return nextAnnotation;
}
/**
* Returns the annotation overlapping with the given range or <code>null</code>.
*
* @param offset the region offset
* @param length the region length
* @return the found annotation or <code>null</code>
* @since 3.0
*/
private Annotation getAnnotation(int offset, int length) {
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true, true);
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (!isNavigationTarget(a))
continue;
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(offset, length))
return a;
}
return null;
}
/**
* Returns whether the given annotation is configured as a target for the
* "Go to Next/Previous Annotation" actions
*
* @param annotation the annotation
* @return <code>true</code> if this is a target, <code>false</code>
* otherwise
* @since 3.0
*/
private boolean isNavigationTarget(Annotation annotation) {
Preferences preferences= EditorsUI.getPluginPreferences();
AnnotationPreference preference= getAnnotationPreferenceLookup().getAnnotationPreference(annotation);
// See bug 41689
// String key= forward ? preference.getIsGoToNextNavigationTargetKey() : preference.getIsGoToPreviousNavigationTargetKey();
String key= preference == null ? null : preference.getIsGoToNextNavigationTargetKey();
return (key != null && preferences.getBoolean(key));
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension5) {
ITextViewerExtension5 extension= (ITextViewerExtension5)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createChangeHover()
*/
protected LineChangeHover createChangeHover() {
return new JavaChangeHover(IJavaPartitions.JAVA_PARTITIONING);
}
protected boolean isPrefQuickDiffAlwaysOn() {
return false; // never show change ruler for the non-editable java editor. Overridden in subclasses like CompilationUnitEditor
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#createNavigationActions()
*/
protected void createNavigationActions() {
super.createNavigationActions();
final StyledText textWidget= getSourceViewer().getTextWidget();
IAction action= new SmartLineStartAction(textWidget, false);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.LINE_START);
setAction(ITextEditorActionDefinitionIds.LINE_START, action);
action= new SmartLineStartAction(textWidget, true);
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_LINE_START);
setAction(ITextEditorActionDefinitionIds.SELECT_LINE_START, action);
action= new NavigatePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_LEFT, SWT.NULL);
action= new NavigateNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.ARROW_RIGHT, SWT.NULL);
action= new DeletePreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_PREVIOUS_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.BS, SWT.NULL);
action= new DeleteNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD);
setAction(ITextEditorActionDefinitionIds.DELETE_NEXT_WORD, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.DEL, SWT.NULL);
action= new SelectPreviousSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_PREVIOUS, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_LEFT, SWT.NULL);
action= new SelectNextSubWordAction();
action.setActionDefinitionId(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT);
setAction(ITextEditorActionDefinitionIds.SELECT_WORD_NEXT, action);
textWidget.setKeyBinding(SWT.CTRL | SWT.SHIFT | SWT.ARROW_RIGHT, SWT.NULL);
}
/*
* @see org.eclipse.ui.texteditor.AbstractDecoratedTextEditor#createCompositeRuler()
*/
protected CompositeRuler createCompositeRuler() {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ANNOTATION_ROLL_OVER))
return super.createCompositeRuler();
CompositeRuler ruler= new CompositeRuler();
AnnotationRulerColumn column= new AnnotationRulerColumn(VERTICAL_RULER_WIDTH, getAnnotationAccess());
column.setHover(new JavaExpandHover(ruler, getAnnotationAccess(), new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
// for now: just invoke ruler double click action
triggerAction(ITextEditorActionConstants.RULER_DOUBLE_CLICK);
}
private void triggerAction(String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
// hack to propagate line change
if (action instanceof ISelectionListener) {
((ISelectionListener)action).selectionChanged(null, null);
}
if (action.isEnabled())
action.run();
}
}
}));
ruler.addDecorator(0, column);
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isPrefQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/**
* Returns the folding action group, or <code>null</code> if there is none.
*
* @return the folding action group, or <code>null</code> if there is none
* @since 3.0
*/
protected FoldingActionGroup getFoldingActionGroup() {
return fFoldingGroup;
}
}
|
62,878
|
Bug 62878 [misc] Mark Occurrences of exceptions/types inconsistent
|
I200405190010 - disable Mark Exceptions - enable Mark Types - in TestCase: - position cursor on Throwable of runBare() declaration -> type Throwable is marked - posititon cursor on Throwable of runTest() delcaration -> type Throwable is not marked This is inconsistent.
|
resolved fixed
|
37b90cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T12:38:28Z
| 2004-05-19T12:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/ExceptionOccurrencesFinder.java
|
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* 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.search;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.CastExpression;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ConstructorInvocation;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Javadoc;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.SuperConstructorInvocation;
import org.eclipse.jdt.core.dom.SuperMethodInvocation;
import org.eclipse.jdt.core.dom.ThrowStatement;
import org.eclipse.jdt.core.dom.TryStatement;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.TypeDeclarationStatement;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.search.ui.ISearchResultView;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.search.ui.text.Match;
import org.eclipse.ui.texteditor.MarkerUtilities;
public class ExceptionOccurrencesFinder extends ASTVisitor implements IOccurrencesFinder {
public static final String IS_EXCEPTION= "isException"; //$NON-NLS-1$
private AST fAST;
private Name fSelectedName;
private ITypeBinding fException;
private ASTNode fStart;
private List fResult;
public ExceptionOccurrencesFinder() {
fResult= new ArrayList();
}
public String initialize(CompilationUnit root, int offset, int length) {
fAST= root.getAST();
ASTNode node= NodeFinder.perform(root, offset, length);
if (!(node instanceof Name)) {
return SearchMessages.getString("ExceptionOccurrencesFinder.no_exception"); //$NON-NLS-1$
}
fSelectedName= ASTNodes.getTopMostName((Name)node);
ASTNode parent= fSelectedName.getParent();
MethodDeclaration decl= resolveMethodDeclaration(parent);
if (decl != null && methodThrowsException(decl, fSelectedName)) {
fException= fSelectedName.resolveTypeBinding();
fStart= decl.getBody();
} else if (parent instanceof Type) {
parent= parent.getParent();
if (parent instanceof SingleVariableDeclaration && parent.getParent() instanceof CatchClause) {
CatchClause catchClause= (CatchClause)parent.getParent();
TryStatement tryStatement= (TryStatement)catchClause.getParent();
if (tryStatement != null) {
IVariableBinding var= catchClause.getException().resolveBinding();
if (var != null && var.getType() != null) {
fException= var.getType();
fStart= tryStatement.getBody();
}
}
}
}
if (fException == null || fStart == null)
return SearchMessages.getString("ExceptionOccurrencesFinder.no_exception"); //$NON-NLS-1$
return null;
}
private MethodDeclaration resolveMethodDeclaration(ASTNode node) {
if (node instanceof MethodDeclaration)
return (MethodDeclaration)node;
Javadoc doc= (Javadoc) ASTNodes.getParent(node, ASTNode.JAVADOC);
if (doc == null)
return null;
if (doc.getParent() instanceof MethodDeclaration)
return (MethodDeclaration) doc.getParent();
return null;
}
private boolean methodThrowsException(MethodDeclaration method, Name exception) {
ASTMatcher matcher = new ASTMatcher();
for (Iterator iter = method.thrownExceptions().iterator(); iter.hasNext();) {
Name thrown = (Name)iter.next();
if (exception.subtreeMatch(matcher, thrown))
return true;
}
return false;
}
public List perform() {
fStart.accept(this);
if (fResult.size() > 0 && fSelectedName != null) {
fResult.add(fSelectedName);
}
return fResult;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.search.IPositionFinder#createMarkers(org.eclipse.core.resources.IResource, org.eclipse.jface.text.IDocument)
*/
public IMarker[] createMarkers(IResource file, IDocument document) throws CoreException {
List result= new ArrayList();
for (Iterator iter = fResult.iterator(); iter.hasNext();) {
ASTNode node = (ASTNode) iter.next();
result.add(createMarker(file, document, node));
}
return (IMarker[]) result.toArray(new IMarker[result.size()]);
}
private IMarker createMarker(IResource file, IDocument document, ASTNode node) throws CoreException {
Map attributes= new HashMap(10);
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
int startPosition= node.getStartPosition();
MarkerUtilities.setCharStart(attributes, startPosition);
MarkerUtilities.setCharEnd(attributes, startPosition + node.getLength());
if (node == fSelectedName) {
attributes.put(IS_EXCEPTION, Boolean.TRUE);
}
try {
int line= document.getLineOfOffset(startPosition);
MarkerUtilities.setLineNumber(attributes, line);
IRegion region= document.getLineInformation(line);
String lineContents= document.get(region.getOffset(), region.getLength());
MarkerUtilities.setMessage(attributes, lineContents.trim());
throw new BadLocationException();
} catch (BadLocationException e) {
}
marker.setAttributes(attributes);
return marker;
}
public void searchStarted(ISearchResultView view, String inputName) {
String elementName= ASTNodes.asString(fSelectedName);
view.searchStarted(
null,
getSingularLabel(elementName, inputName),
getPluralLabelPattern(elementName, inputName),
JavaPluginImages.DESC_OBJS_SEARCH_REF,
"org.eclipse.jdt.ui.JavaFileSearch", //$NON-NLS-1$
new ExceptionOccurrencesLabelProvider(),
new GotoMarkerAction(),
new SearchGroupByKeyComputer(),
null
);
}
public Match[] getOccurrenceMatches(IJavaElement element, IDocument document) {
ArrayList matches= new ArrayList(fResult.size());
HashMap lineToLineElement= new HashMap();
for (Iterator iter= fResult.iterator(); iter.hasNext();) {
ASTNode node= (ASTNode) iter.next();
int startPosition= node.getStartPosition();
int length= node.getLength();
try {
boolean isException= node == fSelectedName;
int line= document.getLineOfOffset(startPosition);
Integer lineInteger= new Integer(line);
ExceptionOccurrencesGroupKey groupKey= (ExceptionOccurrencesGroupKey) lineToLineElement.get(lineInteger);
if (groupKey == null) {
IRegion region= document.getLineInformation(line);
String lineContents= document.get(region.getOffset(), region.getLength()).trim();
groupKey= new ExceptionOccurrencesGroupKey(element, line, lineContents, isException);
lineToLineElement.put(lineInteger, groupKey);
} else if (isException) {
// the line with the target exception always has the exception icon:
groupKey.setException(true);
}
Match match= new Match(groupKey, startPosition, length);
matches.add(match);
} catch (BadLocationException e) {
//nothing
}
}
return (Match[]) matches.toArray(new Match[matches.size()]);
}
public String getJobLabel() {
return SearchMessages.getString("ExceptionOccurrencesFinder.searchfor") ; //$NON-NLS-1$
}
public String getPluralLabelPattern(String documentName) {
return getPluralLabelPattern(ASTNodes.asString(fSelectedName), documentName);
}
public String getSingularLabel(String documentName) {
return getSingularLabel(ASTNodes.asString(fSelectedName), documentName);
}
private String getPluralLabelPattern(String nodeContents, String elementName) {
String[] args= new String[] {nodeContents, "{0}", elementName}; //$NON-NLS-1$
return SearchMessages.getFormattedString("ExceptionOccurrencesFinder.label.plural", args); //$NON-NLS-1$
}
private String getSingularLabel(String nodeContents, String elementName) {
String[] args= new String[] {nodeContents, elementName}; //$NON-NLS-1$
return SearchMessages.getFormattedString("ExceptionOccurrencesFinder.label.singular", args); //$NON-NLS-1$
}
public boolean visit(AnonymousClassDeclaration node) {
return false;
}
public boolean visit(CastExpression node) {
if ("java.lang.ClassCastException".equals(fException.getQualifiedName())) //$NON-NLS-1$
fResult.add(node.getType());
return super.visit(node);
}
public boolean visit(ClassInstanceCreation node) {
if (matches(node.resolveConstructorBinding())) {
fResult.add(node.getName());
}
return super.visit(node);
}
public boolean visit(ConstructorInvocation node) {
if (matches(node.resolveConstructorBinding())) {
// mark this
SimpleName name= fAST.newSimpleName("xxxx"); //$NON-NLS-1$
name.setSourceRange(node.getStartPosition(), 4);
fResult.add(name);
}
return super.visit(node);
}
public boolean visit(MethodInvocation node) {
if (matches(node.resolveMethodBinding()))
fResult.add(node.getName());
return super.visit(node);
}
public boolean visit(SuperConstructorInvocation node) {
if (matches(node.resolveConstructorBinding())) {
SimpleName name= fAST.newSimpleName("xxxxx"); //$NON-NLS-1$
name.setSourceRange(node.getStartPosition(), 5);
fResult.add(name);
}
return super.visit(node);
}
public boolean visit(SuperMethodInvocation node) {
if (matches(node.resolveMethodBinding())) {
fResult.add(node.getName());
}
return super.visit(node);
}
public boolean visit(ThrowStatement node) {
if (matches(node.getExpression().resolveTypeBinding())) {
SimpleName name= fAST.newSimpleName("xxxxx"); //$NON-NLS-1$
name.setSourceRange(node.getStartPosition(), 5);
fResult.add(name);
}
return super.visit(node);
}
public boolean visit(TypeDeclarationStatement node) {
// don't dive into local type declarations.
return false;
}
private boolean matches(IMethodBinding binding) {
if (binding == null)
return false;
ITypeBinding[] exceptions= binding.getExceptionTypes();
for (int i = 0; i < exceptions.length; i++) {
ITypeBinding exception= exceptions[i];
if(matches(exception))
return true;
}
return false;
}
private boolean matches(ITypeBinding exception) {
if (exception == null)
return false;
while (exception != null) {
if (Bindings.equals(fException, exception))
return true;
exception= exception.getSuperclass();
}
return false;
}
}
|
62,896
|
Bug 62896 [misc] Quick Outline should not show override indicators if decorator disabled
|
I20040519 The quick outline shows override indicators no matter whether the Override indicator decorator is enabled in the prefs or not. We should only install the decorator if the prefs says so since this is a performance saver.
|
resolved fixed
|
9745e6f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T13:41:16Z
| 2004-05-19T12:33:20Z
|
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/JavaOutlineInformationControl.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.keys.KeySequence;
import org.eclipse.ui.keys.SWTKeySupport;
import org.eclipse.jdt.core.Flags;
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.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator;
import org.eclipse.jdt.ui.ProblemsLabelDecorator;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilter;
/**
* Show outline in light-weight control.
*
* @since 2.1
*/
public class JavaOutlineInformationControl extends AbstractInformationControl {
private KeyAdapter fKeyAdapter;
private OutlineContentProvider fOutlineContentProvider;
private IJavaElement fInput= null;
private OutlineSorter fOutlineSorter;
private OutlineLabelProvider fInnerLabelProvider;
protected Color fForegroundColor;
private boolean fShowOnlyMainType;
private LexicalSortingAction fLexicalSortingAction;
private SortByDefiningTypeAction fSortByDefiningTypeAction;
private ShowOnlyMainTypeAction fShowOnlyMainTypeAction;
private Map fTypeHierarchies= new HashMap();
private class OutlineLabelProvider extends AppearanceAwareLabelProvider {
private boolean fShowDefiningType;
private OutlineLabelProvider() {
super(AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS);
}
/*
* @see ILabelProvider#getText
*/
public String getText(Object element) {
String text= super.getText(element);
if (fShowDefiningType) {
try {
IType type= getDefiningType(element);
if (type != null) {
StringBuffer buf= new StringBuffer(super.getText(type));
buf.append(JavaElementLabels.CONCAT_STRING);
buf.append(text);
return buf.toString();
}
} catch (JavaModelException e) {
}
}
return text;
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider#getForeground(java.lang.Object)
*/
public Color getForeground(Object element) {
if (fOutlineContentProvider.isShowingInheritedMembers()) {
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
if (fInput.getElementType() == IJavaElement.CLASS_FILE)
je= je.getAncestor(IJavaElement.CLASS_FILE);
else
je= je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (fInput.equals(je)) {
return null;
}
}
return fForegroundColor;
}
return null;
}
public void setShowDefiningType(boolean showDefiningType) {
fShowDefiningType= showDefiningType;
}
public boolean isShowDefiningType() {
return fShowDefiningType;
}
private IType getDefiningType(Object element) throws JavaModelException {
int kind= ((IJavaElement) element).getElementType();
if (kind != IJavaElement.METHOD && kind != IJavaElement.FIELD && kind != IJavaElement.INITIALIZER) {
return null;
}
IType declaringType= ((IMember) element).getDeclaringType();
if (kind != IJavaElement.METHOD) {
return declaringType;
}
ITypeHierarchy hierarchy= getSuperTypeHierarchy(declaringType);
if (hierarchy == null) {
return declaringType;
}
IMethod method= (IMethod) element;
int flags= method.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || method.isConstructor()) {
return declaringType;
}
IMethod res= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, declaringType, method.getElementName(), method.getParameterTypes(), false);
if (res == null || method.equals(res)) {
return declaringType;
}
return res.getDeclaringType();
}
}
private class OutlineTreeViewer extends TreeViewer {
private boolean fIsFiltering= false;
private OutlineTreeViewer(Tree tree) {
super(tree);
}
/**
* {@inheritDoc}
*/
protected Object[] getFilteredChildren(Object parent) {
Object[] result = getRawChildren(parent);
int unfilteredChildren= result.length;
ViewerFilter[] filters = getFilters();
if (filters != null) {
for (int i= 0; i < filters.length; i++)
result = filters[i].filter(this, parent, result);
}
fIsFiltering= unfilteredChildren != result.length;
return result;
}
/**
* {@inheritDoc}
*/
protected void internalExpandToLevel(Widget node, int level) {
if (!fIsFiltering && node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
setExpanded(i, false);
return;
}
}
}
super.internalExpandToLevel(node, level);
}
private boolean isInnerType(IJavaElement element) {
if (element != null && element.getElementType() == IJavaElement.TYPE) {
IType type= (IType)element;
try {
return type.isMember();
} catch (JavaModelException e) {
IJavaElement parent= type.getParent();
if (parent != null) {
int parentElementType= parent.getElementType();
return (parentElementType != IJavaElement.COMPILATION_UNIT && parentElementType != IJavaElement.CLASS_FILE);
}
}
}
return false;
}
}
private class OutlineContentProvider extends StandardJavaElementContentProvider {
private boolean fShowInheritedMembers;
/**
* Creates a new Outline content provider.
*
* @param showInheritedMembers <code>true</code> iff inherited members are shown
*/
private OutlineContentProvider(boolean showInheritedMembers) {
super(true);
fShowInheritedMembers= showInheritedMembers;
}
public boolean isShowingInheritedMembers() {
return fShowInheritedMembers;
}
public void toggleShowInheritedMembers() {
Tree tree= getTreeViewer().getTree();
tree.setRedraw(false);
fShowInheritedMembers= !fShowInheritedMembers;
getTreeViewer().refresh();
getTreeViewer().expandToLevel(2);
// reveal selection
Object selectedElement= getSelectedElement();
if (selectedElement != null)
getTreeViewer().reveal(selectedElement);
tree.setRedraw(true);
}
/**
* {@inheritDoc}
*/
public Object[] getChildren(Object element) {
if (fShowOnlyMainType) {
if (element instanceof ICompilationUnit) {
element= getMainType((ICompilationUnit)element);
} else if (element instanceof IClassFile) {
element= getMainType((IClassFile)element);
}
if (element == null)
return NO_CHILDREN;
}
if (fShowInheritedMembers && element instanceof IType) {
IType type= (IType)element;
if (type.getDeclaringType() == null) {
ITypeHierarchy th= getSuperTypeHierarchy(type);
if (th != null) {
List children= new ArrayList();
IType[] superClasses= th.getAllSupertypes(type);
children.addAll(Arrays.asList(super.getChildren(type)));
for (int i= 0, scLength= superClasses.length; i < scLength; i++)
children.addAll(Arrays.asList(super.getChildren(superClasses[i])));
return children.toArray();
}
}
}
return super.getChildren(element);
}
/**
* {@inheritDoc}
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
fTypeHierarchies.clear();
}
/**
* {@inheritDoc}
*/
public void dispose() {
super.dispose();
fTypeHierarchies.clear();
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
private IType getMainType(ICompilationUnit compilationUnit) {
if (compilationUnit == null)
return null;
String name= compilationUnit.getElementName();
int index= name.indexOf('.');
if (index != -1)
name= name.substring(0, index);
IType type= compilationUnit.getType(name);
return type.exists() ? type : null;
}
/**
* Returns the primary type of a class file.
*
* @param classFile the class file
* @return returns the primary type of the class file, or <code>null</code>
* if is does not have one
*/
private IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type != null && type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
}
private class ShowOnlyMainTypeAction extends Action {
private static final String STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED= "GoIntoTopLevelTypeAction.isChecked"; //$NON-NLS-1$
private TreeViewer fOutlineViewer;
private ShowOnlyMainTypeAction(TreeViewer outlineViewer) {
super(TextMessages.getString("JavaOutlineInformationControl.GoIntoTopLevelType.label"), IAction.AS_CHECK_BOX); //$NON-NLS-1$
setToolTipText(TextMessages.getString("JavaOutlineInformationControl.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(TextMessages.getString("JavaOutlineInformationControl.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
fOutlineViewer= outlineViewer;
boolean showclass= getDialogSettings().getBoolean(STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED);
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fShowOnlyMainType);
}
private void setTopLevelTypeOnly(boolean show) {
fShowOnlyMainType= show;
setChecked(show);
Tree tree= fOutlineViewer.getTree();
tree.setRedraw(false);
fOutlineViewer.refresh(false);
if (!fShowOnlyMainType)
fOutlineViewer.expandToLevel(2);
// reveal selection
Object selectedElement= getSelectedElement();
if (selectedElement != null)
fOutlineViewer.reveal(selectedElement);
tree.setRedraw(true);
getDialogSettings().put(STORE_GO_INTO_TOP_LEVEL_TYPE_CHECKED, show);
}
}
private class OutlineSorter extends ViewerSorter {
private static final int OTHER= 1;
private static final int CLASS= 2;
private static final int INTERFACE= 3;
private static final int ANONYM= 4;
private JavaElementSorter fJavaElementSorter= new JavaElementSorter();
/*
* @see org.eclipse.jface.viewers.ViewerSorter#sort(org.eclipse.jface.viewers.Viewer, java.lang.Object[])
*/
public void sort(Viewer viewer, Object[] elements) {
if (!fLexicalSortingAction.isChecked() && !fSortByDefiningTypeAction.isChecked())
return;
super.sort(viewer, elements);
}
/*
* @see org.eclipse.jface.viewers.ViewerSorter#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
*/
public int compare(Viewer viewer, Object e1, Object e2) {
int cat1= category(e1);
int cat2= category(e2);
if (cat1 != cat2)
return cat1 - cat2;
if (cat1 == OTHER) { // method or field
if (fSortByDefiningTypeAction.isChecked()) {
try {
IType def1= (e1 instanceof IMethod) ? getDefiningType((IMethod) e1) : null;
IType def2= (e2 instanceof IMethod) ? getDefiningType((IMethod) e2) : null;
if (def1 != null) {
if (def2 != null) {
if (!def2.equals(def1)) {
return compareInHierarchy(getSuperTypeHierarchy(def1), def1, def2);
}
} else {
return -1;
}
} else {
if (def2 != null) {
return 1;
}
}
} catch (JavaModelException e) {
// ignore, default to normal comparison
}
}
} else if (cat1 == ANONYM) {
return 0;
}
if (fLexicalSortingAction.isChecked())
return fJavaElementSorter.compare(viewer, e1, e2); // use appearance preference page settings
else
return 0;
}
private IType getDefiningType(IMethod method) throws JavaModelException {
IType declaringType= method.getDeclaringType();
int flags= method.getFlags();
if (Flags.isPrivate(flags) || Flags.isStatic(flags) || method.isConstructor()) {
return null;
}
IMethod res= JavaModelUtil.findMethodDeclarationInHierarchy(getSuperTypeHierarchy(declaringType), declaringType, method.getElementName(), method.getParameterTypes(), false);
if (res == null || method.equals(res)) {
return null;
}
return res.getDeclaringType();
}
/*
* @see org.eclipse.jface.viewers.ViewerSorter#category(java.lang.Object)
*/
public int category(Object element) {
if (element instanceof IType) {
IType type= (IType) element;
if (type.getElementName().length() == 0) {
return ANONYM;
}
ITypeHierarchy hierarchy= getSuperTypeHierarchy(type);
if (hierarchy != null) {
if (Flags.isInterface(hierarchy.getCachedFlags((IType) element))) {
return INTERFACE;
} else {
return CLASS;
}
}
}
return OTHER;
}
private int compareInHierarchy(ITypeHierarchy hierarchy, IType def1, IType def2) {
if (isSuperType(hierarchy, def1, def2)) {
return 1;
} else if (isSuperType(hierarchy, def2, def1)) {
return -1;
}
// interfaces after classes
int flags1= hierarchy.getCachedFlags(def1);
int flags2= hierarchy.getCachedFlags(def2);
if (Flags.isInterface(flags1)) {
if (!Flags.isInterface(flags2)) {
return 1;
}
} else if (Flags.isInterface(flags2)) {
return -1;
}
String name1= def1.getElementName();
String name2= def2.getElementName();
return getCollator().compare(name1, name2);
}
private boolean isSuperType(ITypeHierarchy hierarchy, IType def1, IType def2) {
IType superType= hierarchy.getSuperclass(def1);
if (superType != null) {
if (superType.equals(def2) || isSuperType(hierarchy, superType, def2)) {
return true;
}
}
IType[] superInterfaces= hierarchy.getAllSuperInterfaces(def1);
for (int i= 0; i < superInterfaces.length; i++) {
IType curr= superInterfaces[i];
if (curr.equals(def2) || isSuperType(hierarchy, curr, def2)) {
return true;
}
}
return false;
}
}
private class LexicalSortingAction extends Action {
private static final String STORE_LEXICAL_SORTING_CHECKED= "LexicalSortingAction.isChecked"; //$NON-NLS-1$
private TreeViewer fOutlineViewer;
private LexicalSortingAction(TreeViewer outlineViewer) {
super(TextMessages.getString("JavaOutlineInformationControl.LexicalSortingAction.label"), IAction.AS_CHECK_BOX); //$NON-NLS-1$
setToolTipText(TextMessages.getString("JavaOutlineInformationControl.LexicalSortingAction.tooltip")); //$NON-NLS-1$
setDescription(TextMessages.getString("JavaOutlineInformationControl.LexicalSortingAction.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
fOutlineViewer= outlineViewer;
boolean checked=getDialogSettings().getBoolean(STORE_LEXICAL_SORTING_CHECKED);
setChecked(checked);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_BROWSING_ACTION);
}
public void run() {
valueChanged(isChecked(), true);
}
private void valueChanged(final boolean on, boolean store) {
setChecked(on);
BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
public void run() {
fOutlineViewer.refresh(false);
}
});
if (store)
getDialogSettings().put(STORE_LEXICAL_SORTING_CHECKED, on);
}
}
private class SortByDefiningTypeAction extends Action {
private static final String STORE_SORT_BY_DEFINING_TYPE_CHECKED= "SortByDefiningType.isChecked"; //$NON-NLS-1$
private TreeViewer fOutlineViewer;
/**
* Creates the action.
*
* @param outlineViewer the outline viewer
*/
private SortByDefiningTypeAction(TreeViewer outlineViewer) {
super(TextMessages.getString("JavaOutlineInformationControl.SortByDefiningTypeAction.label")); //$NON-NLS-1$
setDescription(TextMessages.getString("JavaOutlineInformationControl.SortByDefiningTypeAction.description")); //$NON-NLS-1$
setToolTipText(TextMessages.getString("JavaOutlineInformationControl.SortByDefiningTypeAction.tooltip")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "definingtype_sort_co.gif"); //$NON-NLS-1$
fOutlineViewer= outlineViewer;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.SORT_BY_DEFINING_TYPE_ACTION);
boolean state= getDialogSettings().getBoolean(STORE_SORT_BY_DEFINING_TYPE_CHECKED);
setChecked(state);
fInnerLabelProvider.setShowDefiningType(state);
}
/*
* @see Action#actionPerformed
*/
public void run() {
BusyIndicator.showWhile(fOutlineViewer.getControl().getDisplay(), new Runnable() {
public void run() {
fInnerLabelProvider.setShowDefiningType(isChecked());
getDialogSettings().put(STORE_SORT_BY_DEFINING_TYPE_CHECKED, isChecked());
fOutlineViewer.refresh(true);
// reveal selection
Object selectedElement= getSelectedElement();
if (selectedElement != null)
fOutlineViewer.reveal(selectedElement);
}
});
}
}
/**
* Creates a new Java outline information control.
*
* @param parent
* @param shellStyle
* @param treeStyle
* @param commandId
*/
public JavaOutlineInformationControl(Shell parent, int shellStyle, int treeStyle, String commandId) {
super(parent, shellStyle, treeStyle, commandId, true);
}
/**
* {@inheritDoc}
*/
protected Text createFilterText(Composite parent) {
Text text= super.createFilterText(parent);
text.addKeyListener(getKeyAdapter());
return text;
}
/**
* {@inheritDoc}
*/
protected TreeViewer createTreeViewer(Composite parent, int style) {
Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
final TreeViewer treeViewer= new OutlineTreeViewer(tree);
// Hard-coded filters
treeViewer.addFilter(new NamePatternFilter());
treeViewer.addFilter(new MemberFilter());
fForegroundColor= parent.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY);
fInnerLabelProvider= new OutlineLabelProvider();
fInnerLabelProvider.addLabelDecorator(new ProblemsLabelDecorator(null));
fInnerLabelProvider.addLabelDecorator(new OverrideIndicatorLabelDecorator(null));
treeViewer.setLabelProvider(fInnerLabelProvider);
fLexicalSortingAction= new LexicalSortingAction(treeViewer);
fSortByDefiningTypeAction= new SortByDefiningTypeAction(treeViewer);
fShowOnlyMainTypeAction= new ShowOnlyMainTypeAction(treeViewer);
fOutlineContentProvider= new OutlineContentProvider(false);
treeViewer.setContentProvider(fOutlineContentProvider);
fOutlineSorter= new OutlineSorter();
treeViewer.setSorter(fOutlineSorter);
treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
treeViewer.getTree().addKeyListener(getKeyAdapter());
return treeViewer;
}
/**
* {@inheritDoc}
*/
protected String getStatusFieldText() {
KeySequence[] sequences= getInvokingCommandKeySequences();
if (sequences == null || sequences.length == 0)
return ""; //$NON-NLS-1$
String keySequence= sequences[0].format();
if (fOutlineContentProvider.isShowingInheritedMembers())
return JavaUIMessages.getFormattedString("JavaOutlineControl.statusFieldText.hideInheritedMembers", keySequence); //$NON-NLS-1$
else
return JavaUIMessages.getFormattedString("JavaOutlineControl.statusFieldText.showInheritedMembers", keySequence); //$NON-NLS-1$
}
/*
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#getId()
* @since 3.0
*/
protected String getId() {
return "org.eclipse.jdt.internal.ui.text.QuickOutline"; //$NON-NLS-1$
}
/**
* {@inheritDoc}
*/
public void setInput(Object information) {
if (information == null || information instanceof String) {
inputChanged(null, null);
return;
}
IJavaElement je= (IJavaElement)information;
ICompilationUnit cu= (ICompilationUnit)je.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
fInput= cu;
else
fInput= je.getAncestor(IJavaElement.CLASS_FILE);
inputChanged(fInput, information);
}
private KeyAdapter getKeyAdapter() {
if (fKeyAdapter == null) {
fKeyAdapter= new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int accelerator = SWTKeySupport.convertEventToUnmodifiedAccelerator(e);
KeySequence keySequence = KeySequence.getInstance(SWTKeySupport.convertAcceleratorToKeyStroke(accelerator));
KeySequence[] sequences= getInvokingCommandKeySequences();
if (sequences == null)
return;
for (int i= 0; i < sequences.length; i++) {
if (sequences[i].equals(keySequence)) {
e.doit= false;
toggleShowInheritedMembers();
return;
}
}
}
};
}
return fKeyAdapter;
}
/**
* {@inheritDoc}
*/
protected void handleStatusFieldClicked() {
toggleShowInheritedMembers();
}
protected void toggleShowInheritedMembers() {
int flags= AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE;
if (!fOutlineContentProvider.isShowingInheritedMembers())
flags |= JavaElementLabels.ALL_POST_QUALIFIED;
fInnerLabelProvider.setTextFlags(flags);
fOutlineContentProvider.toggleShowInheritedMembers();
updateStatusFieldText();
}
/*
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#fillViewMenu(org.eclipse.jface.action.IMenuManager)
*/
protected void fillViewMenu(IMenuManager viewMenu) {
super.fillViewMenu(viewMenu);
viewMenu.add(fShowOnlyMainTypeAction); //$NON-NLS-1$
viewMenu.add(new Separator("Sorters")); //$NON-NLS-1$
viewMenu.add(fLexicalSortingAction);
viewMenu.add(fSortByDefiningTypeAction);
}
private ITypeHierarchy getSuperTypeHierarchy(IType type) {
ITypeHierarchy th= (ITypeHierarchy)fTypeHierarchies.get(type);
if (th == null) {
try {
th= SuperTypeHierarchyCache.getTypeHierarchy(type, getProgressMonitor());
} catch (JavaModelException e) {
return null;
}
fTypeHierarchies.put(type, th);
}
return th;
}
private IProgressMonitor getProgressMonitor() {
IWorkbenchPage wbPage= JavaPlugin.getActivePage();
if (wbPage == null)
return null;
IEditorPart editor= wbPage.getActiveEditor();
if (editor == null)
return null;
return editor.getEditorSite().getActionBars().getStatusLineManager().getProgressMonitor();
}
}
|
62,437
|
Bug 62437 Hang on 0506 build related to indexing?
|
My development environment "hung". I did ctrl-break and will attache stack dumps. I can't read these (easily) in detail, but looked related to JDT indexing, so thought I'd route to JDT first. The only thing "unusuall" I was doing in IDE was that I'd just copied a java source file form one plugin/package to another plugin/package. The first was open in an editor before the copy, after the copy I opened the second one, then closed the first one. Then it hung. Hopefully the stack traces will be more revealing. This was with 0506 I-build, using following VM: java version "1.4.2" J9 - VM for the Java(TM) platform (build 2.1) IBM J9SE VM (build 2.1, J2RE 1.4.2 IBM J9 build 20040422 (JIT enabled))
|
verified fixed
|
18a4b60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T13:51:11Z
| 2004-05-17T05:00:00Z
|
org.eclipse.jdt.ui/core
| |
62,437
|
Bug 62437 Hang on 0506 build related to indexing?
|
My development environment "hung". I did ctrl-break and will attache stack dumps. I can't read these (easily) in detail, but looked related to JDT indexing, so thought I'd route to JDT first. The only thing "unusuall" I was doing in IDE was that I'd just copied a java source file form one plugin/package to another plugin/package. The first was open in an editor before the copy, after the copy I opened the second one, then closed the first one. Then it hung. Hopefully the stack traces will be more revealing. This was with 0506 I-build, using following VM: java version "1.4.2" J9 - VM for the Java(TM) platform (build 2.1) IBM J9SE VM (build 2.1, J2RE 1.4.2 IBM J9 build 20040422 (JIT enabled))
|
verified fixed
|
18a4b60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T13:51:11Z
| 2004-05-17T05:00:00Z
|
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportRewrite.java
| |
62,437
|
Bug 62437 Hang on 0506 build related to indexing?
|
My development environment "hung". I did ctrl-break and will attache stack dumps. I can't read these (easily) in detail, but looked related to JDT indexing, so thought I'd route to JDT first. The only thing "unusuall" I was doing in IDE was that I'd just copied a java source file form one plugin/package to another plugin/package. The first was open in an editor before the copy, after the copy I opened the second one, then closed the first one. Then it hung. Hopefully the stack traces will be more revealing. This was with 0506 I-build, using following VM: java version "1.4.2" J9 - VM for the Java(TM) platform (build 2.1) IBM J9SE VM (build 2.1, J2RE 1.4.2 IBM J9 build 20040422 (JIT enabled))
|
verified fixed
|
18a4b60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T13:51:11Z
| 2004-05-17T05:00:00Z
|
org.eclipse.jdt.ui/core
| |
62,437
|
Bug 62437 Hang on 0506 build related to indexing?
|
My development environment "hung". I did ctrl-break and will attache stack dumps. I can't read these (easily) in detail, but looked related to JDT indexing, so thought I'd route to JDT first. The only thing "unusuall" I was doing in IDE was that I'd just copied a java source file form one plugin/package to another plugin/package. The first was open in an editor before the copy, after the copy I opened the second one, then closed the first one. Then it hung. Hopefully the stack traces will be more revealing. This was with 0506 I-build, using following VM: java version "1.4.2" J9 - VM for the Java(TM) platform (build 2.1) IBM J9SE VM (build 2.1, J2RE 1.4.2 IBM J9 build 20040422 (JIT enabled))
|
verified fixed
|
18a4b60
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2004-05-19T13:51:11Z
| 2004-05-17T05:00:00Z
|
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.