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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
37,127 |
Bug 37127 add checkbox for "public abstract" in Extract Interface [refactoring]
|
Interface methods that are automatically generated, such as by the "Extract Interface," contain "public abstract" modifiers. This is obsolete and some compilers and style checkers complain about this.
|
resolved fixed
|
4926549
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T12:32:20Z | 2003-05-01T09:06:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceRefactoring.java
| |
37,127 |
Bug 37127 add checkbox for "public abstract" in Extract Interface [refactoring]
|
Interface methods that are automatically generated, such as by the "Extract Interface," contain "public abstract" modifiers. This is obsolete and some compilers and style checkers complain about this.
|
resolved fixed
|
4926549
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T12:32:20Z | 2003-05-01T09:06:40Z |
org.eclipse.jdt.ui/ui
| |
37,127 |
Bug 37127 add checkbox for "public abstract" in Extract Interface [refactoring]
|
Interface methods that are automatically generated, such as by the "Extract Interface," contain "public abstract" modifiers. This is obsolete and some compilers and style checkers complain about this.
|
resolved fixed
|
4926549
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T12:32:20Z | 2003-05-01T09:06:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractInterfaceWizard.java
| |
40,409 |
Bug 40409 quick fix: nonsensical proposal [quick fix]
|
20030716 void f(){ int i= f(); } the proposal you get is: 'change variable type to void' which makes no sense
|
resolved fixed
|
06ab5b8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T13:40:01Z | 2003-07-17T16:40:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testUncaughtExceptionToSurroundingTry"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fJProject1= ProjectTestSetup.getProject();
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testThisAccessToStaticField() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" E.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionToSurroundingTry() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws ParseException {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (ParseException e1) {\n");
buf.append(" }\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testUncaughtExceptionOnSuper1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnSuper2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A() throws Exception {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() throws Exception {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) throws IOException {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public F(int i, Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(int i, Runnable runnable) {\n");
buf.append(" super(i, runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) throws IOException {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testNotVisibleConstructorInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private F() {\n");
buf.append(" }\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnhandledExceptionInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F() throws IOException{\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E() throws IOException {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount, fColor= fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount= 0;\n");
buf.append(" public void foo() {\n");
buf.append(" fCount= 1 + 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" boolean res= process();\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] i, j= new Object[0];\n");
buf.append(" i= j = null;\n");
buf.append(" i= (new Object[] { null, null });\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] j= new Object[0];\n");
buf.append(" j = null;\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int j= 0, i= 0; i < 3; i++) {\n");
buf.append(" j= i;\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int i= 0; i < 3; i++) {\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedParam() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo(Object str) {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateMethod() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append(" \n");
buf.append(" private void foo() {\n");
buf.append(" fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateConstructor() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" private E(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateType() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private class F {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
40,409 |
Bug 40409 quick fix: nonsensical proposal [quick fix]
|
20030716 void f(){ int i= f(); } the proposal you get is: 'change variable type to void' which makes no sense
|
resolved fixed
|
06ab5b8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T13:40:01Z | 2003-07-17T16:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.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 <[email protected]> - Access to static proposal
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.ui.text.java.*;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
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.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.dom.Selection;
import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil;
import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer;
import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter;
import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard;
/**
*/
public class LocalCorrectionsSubProcessor {
public static void addCastProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length != 2) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
String castType= args[1];
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveredNode(astRoot);
if (!(selectedNode instanceof Expression)) {
return;
}
Expression nodeToCast= (Expression) selectedNode;
int parentNodeType= selectedNode.getParent().getNodeType();
if (parentNodeType == ASTNode.ASSIGNMENT) {
Assignment assign= (Assignment) selectedNode.getParent();
if (selectedNode.equals(assign.getLeftHandSide())) {
nodeToCast= assign.getRightHandSide();
}
} else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent();
if (selectedNode.equals(frag.getName())) {
nodeToCast= frag.getInitializer();
}
}
ASTRewriteCorrectionProposal castProposal= getCastProposal(context, castType, nodeToCast, 5);
if (castProposal != null) {
proposals.add(castProposal);
}
if ("void".equals(args[1])) { //$NON-NLS-1$
return;
}
// change method return statement to actual type
if (parentNodeType == ASTNode.RETURN_STATEMENT) {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (binding != null && decl instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration= (MethodDeclaration) decl;
binding= Bindings.normalizeTypeBinding(binding);
if (binding == null) {
binding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
ASTRewrite rewrite= new ASTRewrite(methodDeclaration);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", binding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
String returnTypeName= proposal.addImport(binding);
Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName);
rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType);
String returnKey= "return"; //$NON-NLS-1$
proposal.markAsLinked(rewrite, newReturnType, true, returnKey);
ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(astRoot.getAST(), binding);
for (int i= 0; i < typeSuggestions.length; i++) {
proposal.addLinkedModeProposal(returnKey, typeSuggestions[i]);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent();
ASTNode parent= fragment.getParent();
Type typeNode= null;
if (parent instanceof VariableDeclarationStatement) {
VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent;
if (stmt.fragments().size() == 1) {
typeNode= stmt.getType();
}
} else if (parent instanceof FieldDeclaration) {
FieldDeclaration decl= (FieldDeclaration) parent;
if (decl.fragments().size() == 1) {
typeNode= decl.getType();
}
}
if (typeNode != null) {
ImportEdit edit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String typeName= edit.addImport(args[0]);
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changevartype.description", typeName); //$NON-NLS-1$
ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, typeNode.getStartPosition(), typeNode.getLength(), typeName, 5);
varProposal.getRootTextEdit().add(edit);
proposals.add(varProposal);
}
}
}
private static boolean canCast(String castTarget, ITypeBinding 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;
}
}
public static ASTRewriteCorrectionProposal getCastProposal(IInvocationContext context, String castType, Expression nodeToCast, int relevance) throws CoreException {
ITypeBinding binding= nodeToCast.resolveTypeBinding();
if (binding != null && !canCast(castType, binding)) {
return null;
}
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent());
String label;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, relevance, image); //$NON-NLS-1$
String simpleCastType= proposal.addImport(castType);
if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$
CastExpression expression= (CastExpression) nodeToCast;
rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE));
} else {
label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$
Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast);
int nodeType= nodeToCast.getNodeType();
if (nodeType == ASTNode.INFIX_EXPRESSION || nodeType == ASTNode.CONDITIONAL_EXPRESSION
|| nodeType == ASTNode.ASSIGNMENT || nodeType == ASTNode.INSTANCEOF_EXPRESSION) {
// nodes have weaker precedence than cast
ParenthesizedExpression parenthesizedExpression= astRoot.getAST().newParenthesizedExpression();
parenthesizedExpression.setExpression(expressionCopy);
expressionCopy= parenthesizedExpression;
}
Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, ASTRewrite.TYPE);
CastExpression castExpression= astRoot.getAST().newCastExpression();
castExpression.setExpression(expressionCopy);
castExpression.setType(typeCopy);
rewrite.markAsReplaced(nodeToCast, castExpression);
}
proposal.setDisplayName(label);
proposal.ensureNoModifications();
return proposal;
}
public static void addUncaughtExceptionProposals(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;
}
while (selectedNode != null && !(selectedNode instanceof Statement)) {
selectedNode= selectedNode.getParent();
}
if (selectedNode == null) {
return;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null);
if (refactoring == null)
return;
refactoring.setSaveChanges(false);
if (refactoring.checkActivationBasics(astRoot, null).isOK()) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image);
proposals.add(proposal);
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl == null) {
return;
}
ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength()));
if (uncaughtExceptions.length == 0) {
return;
}
TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode);
if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) {
ASTRewrite rewrite= new ASTRewrite(surroundingTry);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 5, image);
AST ast= astRoot.getAST();
List catchClauses= surroundingTry.catchClauses();
for (int i= 0; i < uncaughtExceptions.length; i++) {
ITypeBinding excBinding= uncaughtExceptions[i];
String varName= "e"; //$NON-NLS-1$
String imp= proposal.addImport(excBinding);
Name name= ASTNodeFactory.newName(ast, imp);
SingleVariableDeclaration var= ast.newSingleVariableDeclaration();
var.setName(ast.newSimpleName(varName));
var.setType(ast.newSimpleType(name));
CatchClause newClause= ast.newCatchClause();
newClause.setException(var);
String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, String.valueOf('\n'));
if (catchBody != null) {
ASTNode node= rewrite.createPlaceholder(catchBody, ASTRewrite.STATEMENT);
newClause.getBody().statements().add(node);
}
rewrite.markAsInserted(newClause);
catchClauses.add(newClause);
String typeKey= "type" + i; //$NON-NLS-1$
String nameKey= "name" + i; //$NON-NLS-1$
proposal.markAsLinked(rewrite, var.getType(), false, typeKey); //$NON-NLS-1$
proposal.markAsLinked(rewrite, var.getName(), false, nameKey); //$NON-NLS-1$
addExceptionTypeLinkProposals(proposal, excBinding, typeKey);
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
if (decl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
AST ast= astRoot.getAST();
MethodDeclaration methodDecl= (MethodDeclaration) decl;
List exceptions= methodDecl.thrownExceptions();
for (int i= 0; i < uncaughtExceptions.length; i++) {
String imp= proposal.addImport(uncaughtExceptions[i]);
Name name= ASTNodeFactory.newName(ast, imp);
rewrite.markAsInserted(name);
exceptions.add(name);
String typeKey= "type" + i; //$NON-NLS-1$
proposal.markAsLinked(rewrite, name, false, typeKey); //$NON-NLS-1$
addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], typeKey);
}
for (int i= 0; i < exceptions.size(); i++) {
Name elem= (Name) exceptions.get(i);
if (canRemoveException(elem.resolveTypeBinding(), uncaughtExceptions)) {
rewrite.markAsRemoved(elem);
}
}
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String key) {
// all superclasses except Object
while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$
proposal.addLinkedModeProposal(key, exc);
exc= exc.getSuperclass();
}
}
private static boolean canRemoveException(ITypeBinding curr, ITypeBinding[] addedExceptions) {
while (curr != null) {
for (int i= 0; i < addedExceptions.length; i++) {
if (curr == addedExceptions[i]) {
return true;
}
}
curr= curr.getSuperclass();
}
return false;
}
public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
if (selectedNode.getNodeType() == ASTNode.BLOCK && selectedNode.getParent().getNodeType() == ASTNode.CATCH_CLAUSE ) {
CatchClause clause= (CatchClause) selectedNode.getParent();
TryStatement tryStatement= (TryStatement) clause.getParent();
ASTRewrite rewrite= new ASTRewrite(tryStatement.getParent());
if (tryStatement.catchClauses().size() > 1 || tryStatement.getFinally() != null) {
rewrite.markAsRemoved(clause);
} else {
List statements= tryStatement.getBody().statements();
if (statements.size() > 0) {
ASTNode placeholder= rewrite.collapseNodes(statements, 0, statements.size());
rewrite.markAsReplaced(tryStatement, rewrite.createCopy(placeholder));
} else {
rewrite.markAsRemoved(tryStatement);
}
}
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removecatchclause.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addNLSProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
if (! NLSRefactoring.isAvailable(cu)){
return;
}
String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5) {
public void apply(IDocument document) {
try {
NLSRefactoring refactoring= NLSRefactoring.create(cu, JavaPreferencesSettings.getCodeGenerationSettings());
if (refactoring == null)
return;
ExternalizeWizard wizard= new ExternalizeWizard(refactoring);
String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$
new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
};
proposals.add(proposal);
TextEdit edit= NLSUtil.createNLSEdit(cu, problem.getOffset());
if (edit != null) {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE);
CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image);
nlsProposal.getRootTextEdit().add(edit);
proposals.add(nlsProposal);
}
}
/**
* A static field or method is accessed using a non-static reference. E.g.
* <pre>
* File f = new File();
* f.pathSeparator;
* </pre>
* This correction changes <code>f</code> above to <code>File</code>.
*
* @param context
* @param proposals
*/
public static void addInstanceAccessToStaticProposals(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;
}
Expression qualifier= null;
IBinding accessBinding= null;
if (selectedNode instanceof QualifiedName) {
QualifiedName name= (QualifiedName) selectedNode;
qualifier= name.getQualifier();
accessBinding= name.resolveBinding();
} else if (selectedNode instanceof SimpleName) {
ASTNode parent= selectedNode.getParent();
if (parent instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) parent;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
} else if (selectedNode instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) selectedNode;
qualifier= methodInvocation.getExpression();
accessBinding= methodInvocation.getName().resolveBinding();
} else if (selectedNode instanceof FieldAccess) {
FieldAccess fieldAccess= (FieldAccess) selectedNode;
qualifier= fieldAccess.getExpression();
accessBinding= fieldAccess.getName().resolveBinding();
}
ITypeBinding declaringTypeBinding= null;
if (accessBinding != null) {
if (accessBinding instanceof IMethodBinding) {
declaringTypeBinding= ((IMethodBinding) accessBinding).getDeclaringClass();
} else if (accessBinding instanceof IVariableBinding) {
declaringTypeBinding= ((IVariableBinding) accessBinding).getDeclaringClass();
}
if (declaringTypeBinding != null) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
String typeName= proposal.addImport(declaringTypeBinding);
rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName));
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
if (qualifier != null) {
ITypeBinding instanceTypeBinding= Bindings.normalizeTypeBinding(qualifier.resolveTypeBinding());
if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image);
String typeName= proposal.addImport(instanceTypeBinding);
rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName));
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC, 4);
}
public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode == null) {
return;
}
ASTNode typeNode= null;
if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) {
typeNode= selectedNode.getParent();
} else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
typeNode= creation.getAnonymousClassDeclaration();
}
if (typeNode != null) {
UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10);
proposals.add(proposal);
}
if (typeNode instanceof TypeDeclaration) {
TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode;
ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration, 5);
proposals.add(proposal);
}
}
public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof Name)) {
return;
}
Name name= (Name) selectedNode;
IBinding binding= name.resolveBinding();
if (!(binding instanceof IVariableBinding)) {
return;
}
IVariableBinding varBinding= (IVariableBinding) binding;
CompilationUnit astRoot= context.getASTRoot();
ASTNode node= astRoot.findDeclaringNode(binding);
if (node instanceof VariableDeclarationFragment) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
VariableDeclarationFragment fragment= (VariableDeclarationFragment) node;
if (fragment.getInitializer() != null) {
return;
}
Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType());
if (expression == null) {
return;
}
fragment.setInitializer(expression);
rewrite.markAsInserted(expression);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image);
proposal.markAsLinked(rewrite, expression, false, "initializer"); //$NON-NLS-1$
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) {
return;
}
TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent();
ITypeBinding binding= typeDeclaration.resolveBinding();
if (binding == null || binding.getSuperclass() == null) {
return;
}
ICompilationUnit cu= context.getCompilationUnit();
IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods();
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) {
proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 5));
}
}
}
public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
SimpleName name= null;
if (selectedNode instanceof MethodDeclaration) {
name= ((MethodDeclaration) selectedNode).getName();
} else if (selectedNode instanceof SimpleName) {
name= (SimpleName) selectedNode;
}
if (name != null) {
IBinding binding= name.resolveBinding();
if (binding != null) {
proposals.add(new RemoveDeclarationCorrectionProposal(context.getCompilationUnit(), context.getASTRoot(), binding, 5));
}
}
}
public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removesemicolon.description"); //$NON-NLS-1$
ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", 6); //$NON-NLS-1$
proposals.add(proposal);
}
public static void addUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode instanceof CastExpression) {
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
CastExpression cast= (CastExpression) selectedNode;
ASTNode placeholder= rewrite.createCopy(cast.getExpression());
rewrite.markAsReplaced(selectedNode, placeholder);
String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarycast.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image);
proposals.add(proposal);
}
}
}
|
37,755 |
Bug 37755 Inner class not displayed in Outline view
|
I've defined 2 inner classes, but only 1 is shown in the Outline view. With the 2 nested classes shown below, only DBChoice is displayed under the HearingFeedback class in the Outline: public class HearingFeedback extends Action { class DbAnswer { int question_d; String answer_text; String answered; ArrayList choices; DbAnswer() { // no-arg constructor } DbAnswer(int question_id, String answer_text, String answered) { this.question_d = question_id; this.answer_text = answer_text; this.answered = answered; } } // End of DbAnswer class DbChoice { int choice_id; String selected; DbChoice() { // no-arg constructor } DbChoice(int choice_id, String selected) { this.choice_id = choice_id; this.selected = selected; } } // End of DbChoice ...
|
resolved fixed
|
688be63
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T14:42:55Z | 2003-05-16T13:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.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.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
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.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IPostSelectionProvider;
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.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.model.WorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.AbstractToggleLinkingAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The content outline page of the Java editor. The viewer implements a proprietary
* update mechanism based on Java model deltas. It does not react on domain changes.
* It is specified to show the content of ICompilationUnits and IClassFiles.
* Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>.
*/
public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider {
static Object[] NO_CHILDREN= new Object[0];
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
if (getControl() == null)
return;
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
ICompilationUnit cu= (ICompilationUnit) fInput;
IJavaElement base= cu;
if (fTopLevelTypeOnly) {
base= getMainType(cu);
if (base == null) {
if (fOutlineViewer != null)
fOutlineViewer.refresh(true);
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element))
return delta;
if (element.getElementType() > IJavaElement.CLASS_FILE)
return null;
IJavaElementDelta[] children= delta.getAffectedChildren();
if (children == null || children.length == 0)
return null;
for (int i= 0; i < children.length; i++) {
IJavaElementDelta d= findElement(unit, children[i]);
if (d != null)
return d;
}
return null;
}
};
static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class clas) {
if (clas == IWorkbenchAdapter.class)
return this;
return null;
}
}
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private Object[] NO_CLASS= new Object[] {new NoClassElement()};
private ElementChangedListener fListener;
protected boolean matches(IJavaElement element) {
if (element.getElementType() == IJavaElement.METHOD) {
String name= element.getElementName();
return (name != null && name.indexOf('<') >= 0);
}
return false;
}
protected IJavaElement[] filter(IJavaElement[] children) {
boolean initializers= false;
for (int i= 0; i < children.length; i++) {
if (matches(children[i])) {
initializers= true;
break;
}
}
if (!initializers)
return children;
Vector v= new Vector();
for (int i= 0; i < children.length; i++) {
if (matches(children[i]))
continue;
v.addElement(children[i]);
}
IJavaElement[] result= new IJavaElement[v.size()];
v.copyInto(result);
return result;
}
public Object[] getChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
return filter(c.getChildren());
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return NO_CHILDREN;
}
public Object[] getElements(Object parent) {
if (fTopLevelTypeOnly) {
if (parent instanceof ICompilationUnit) {
try {
IType type= getMainType((ICompilationUnit) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else if (parent instanceof IClassFile) {
try {
IType type= getMainType((IClassFile) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof IJavaElement) {
IJavaElement e= (IJavaElement) child;
return e.getParent();
}
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
IJavaElement[] children= filter(c.getChildren());
return (children != null && children.length > 0);
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
boolean isCU= (newInput instanceof ICompilationUnit);
if (isCU && fListener == null) {
fListener= new ElementChangedListener();
JavaCore.addElementChangedListener(fListener);
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
};
class JavaOutlineViewer extends TreeViewer {
/**
* Indicates an item which has been reused. At the point of
* its reuse it has been expanded. This field is used to
* communicate between <code>internalExpandToLevel</code> and
* <code>reuseTreeItem</code>.
*/
private Item fReusedExpandedItem;
private boolean fReorderedMembers;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
fReorderedMembers= false;
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh(true);
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
if (fReorderedMembers) {
refresh(false);
fReorderedMembers= false;
}
}
} else {
// just for now
refresh(true);
}
}
/*
* @see TreeViewer#internalExpandToLevel
*/
protected void internalExpandToLevel(Widget node, int level) {
if (node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
if (i != fReusedExpandedItem) {
setExpanded(i, false);
return;
}
}
}
}
super.internalExpandToLevel(node, level);
}
protected void reuseTreeItem(Item item, Object element) {
// remove children
Item[] c= getChildren(item);
if (c != null && c.length > 0) {
if (getExpanded(item))
fReusedExpandedItem= item;
for (int k= 0; k < c.length; k++) {
if (c[k].getData() != null)
disassociate(c[k]);
c[k].dispose();
}
}
updateItem(item, element);
updatePlus(item, element);
internalExpandToLevel(item, ALL_LEVELS);
fReusedExpandedItem= null;
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return ((IMethod)element).isMainMethod();
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
return "main".equals(element.getElementName()); //$NON-NLS-1$
}
return false;
}
protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException {
if (element instanceof IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
return null;
}
protected boolean overlaps(ISourceRange range, int start, int end) {
return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
}
protected boolean filtered(IJavaElement parent, IJavaElement child) {
Object[] result= new Object[] { child };
ViewerFilter[] filters= getFilters();
for (int i= 0; i < filters.length; i++) {
result= filters[i].filter(this, parent, result);
if (result.length == 0)
return true;
}
return false;
}
protected void update(Widget w, IJavaElementDelta delta) {
Item item;
IJavaElement parent= delta.getElement();
IJavaElementDelta[] affected= delta.getAffectedChildren();
Item[] children= getChildren(w);
boolean doUpdateParent= false;
Vector deletions= new Vector();
Vector additions= new Vector();
for (int i= 0; i < affected.length; i++) {
IJavaElementDelta affectedDelta= affected[i];
IJavaElement affectedElement= affectedDelta.getElement();
int status= affected[i].getKind();
// find tree item with affected element
int j;
for (j= 0; j < children.length; j++)
if (affectedElement.equals(children[j].getData()))
break;
if (j == children.length) {
// addition
if ((status & IJavaElementDelta.CHANGED) != 0 &&
(affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 &&
!filtered(parent, affectedElement))
{
additions.addElement(affectedDelta);
}
continue;
}
item= children[j];
// removed
if ((status & IJavaElementDelta.REMOVED) != 0) {
deletions.addElement(item);
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
// changed
} else if ((status & IJavaElementDelta.CHANGED) != 0) {
int change= affectedDelta.getFlags();
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
if ((change & IJavaElementDelta.F_MODIFIERS) != 0) {
if (filtered(parent, affectedElement))
deletions.addElement(item);
else
updateItem(item, affectedElement);
}
if ((change & IJavaElementDelta.F_CONTENT) != 0)
updateItem(item, affectedElement);
if ((change & IJavaElementDelta.F_CHILDREN) != 0)
update(item, affectedDelta);
if ((change & IJavaElementDelta.F_REORDER) != 0)
fReorderedMembers= true;
}
}
// find all elements to add
IJavaElementDelta[] add= delta.getAddedChildren();
if (additions.size() > 0) {
IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()];
System.arraycopy(add, 0, tmp, 0, add.length);
for (int i= 0; i < additions.size(); i++)
tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i);
add= tmp;
}
// add at the right position
go2: for (int i= 0; i < add.length; i++) {
try {
IJavaElement e= add[i].getElement();
if (filtered(parent, e))
continue go2;
doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
ISourceRange rng= getSourceRange(e);
int start= rng.getOffset();
int end= start + rng.getLength() - 1;
Item last= null;
item= null;
children= getChildren(w);
for (int j= 0; j < children.length; j++) {
item= children[j];
IJavaElement r= (IJavaElement) item.getData();
if (r == null) {
// parent node collapsed and not be opened before -> do nothing
continue go2;
}
try {
rng= getSourceRange(r);
if (overlaps(rng, start, end)) {
// be tolerant if the delta is not correct, or if
// the tree has been updated other than by a delta
reuseTreeItem(item, e);
continue go2;
} else if (rng.getOffset() > start) {
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, (Object) e);
} else {
// nothing to reuse
createTreeItem(w, (Object) e, j);
}
continue go2;
}
} catch (JavaModelException x) {
// stumbled over deleted element
}
last= item;
}
// add at the end of the list
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, -1);
}
} catch (JavaModelException x) {
// the element to be added is not present -> don't add it
}
}
// remove items which haven't been reused
Enumeration e= deletions.elements();
while (e.hasMoreElements()) {
item= (Item) e.nextElement();
disassociate(item);
item.dispose();
}
if (doUpdateParent)
updateItem(w, delta.getElement());
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object input= getInput();
if (event instanceof ProblemsLabelChangedEvent) {
ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
if (e.isMarkerChange() && input instanceof ICompilationUnit) {
return; // marker changes can be ignored
}
}
// look if the underlying resource changed
Object[] changed= event.getElements();
if (changed != null) {
IResource resource= getUnderlyingResource();
if (resource != null) {
for (int i= 0; i < changed.length; i++) {
if (changed[i] != null && changed[i].equals(resource)) {
// change event to a full refresh
event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
break;
}
}
}
}
super.handleLabelProviderChanged(event);
}
private IResource getUnderlyingResource() {
Object input= getInput();
if (input instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) input;
if (cu.isWorkingCopy()) {
return cu.getOriginalElement().getResource();
} else {
return cu.getResource();
}
} else if (input instanceof IClassFile) {
return ((IClassFile) input).getResource();
}
return null;
}
};
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$
boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
valueChanged(checked, false);
}
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.setSorter(on ? fSorter : null); }
});
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
};
class ClassOnlyAction extends Action {
public ClassOnlyAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fTopLevelTypeOnly);
}
private void setTopLevelTypeOnly(boolean show) {
fTopLevelTypeOnly= show;
setChecked(show);
fOutlineViewer.refresh(false);
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
}
};
/**
* This action toggles whether this Java Outline page links
* its selection to the active editor.
*
* @since 3.0
*/
public class ToggleLinkingAction extends AbstractToggleLinkingAction {
JavaOutlinePage fJavaOutlinePage;
/**
* Constructs a new action.
*/
public ToggleLinkingAction(JavaOutlinePage outlinePage) {
boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
setChecked(isLinkingEnabled);
fJavaOutlinePage= outlinePage;
}
/**
* Runs the action.
*/
public void run() {
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked());
}
}
/** A flag to show contents of top level type only */
private boolean fTopLevelTypeOnly;
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private ListenerList fPostSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private GotoErrorAction fPreviousError;
private GotoErrorAction fNextError;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
private ToggleLinkingAction fToggleLinkingAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private IPropertyChangeListener fPropertyChangeListener;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
fTogglePresentation= new TogglePresentationAction();
fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$
fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR);
fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$
fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR);
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fPreviousError.setEditor(editor);
fNextError.setEditor(editor);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
protected 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
*/
protected IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type != null && type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on Page
*/
public void init(IPageSite pageSite) {
super.init(pageSite);
}
private void doPropertyChange(PropertyChangeEvent event) {
if (fOutlineViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fOutlineViewer.refresh(false);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removeSelectionChangedListener(listener);
else
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#setSelection(ISelection)
*/
public void setSelection(ISelection selection) {
if (fOutlineViewer != null)
fOutlineViewer.setSelection(selection);
}
/*
* @see ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fOutlineViewer == null)
return StructuredSelection.EMPTY;
return fOutlineViewer.getSelection();
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addPostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.add(listener);
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removePostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.remove(listener);
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
toolBarManager.add(new ClassOnlyAction());
toolBarManager.add(new LexicalSortingAction());
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
fToggleLinkingAction= new ToggleLinkingAction(this);
toolBarManager.add(fToggleLinkingAction);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
fOutlineViewer= new JavaOutlineViewer(tree);
initDragAndDrop();
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
listeners= fPostSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fPostSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager m) {
contextMenuAboutToShow(m);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
IPageSite site= getSite();
site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
site.setSelectionProvider(fOutlineViewer);
// we must create the groups after we have set the selection provider to the site
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
// register global actions
IActionBars bars= site.getActionBars();
bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo);
bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError);
bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= bars.getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addPostSelectionChangedListener(updater);
}
registerToolbarActions();
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyReleased(e);
}
});
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= null;
fPostSelectionChangedListeners.clear();
fPostSelectionChangedListeners= null;
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
fTogglePresentation.setEditor(null);
fPreviousError.setEditor(null);
fNextError.setEditor(null);
fOutlineViewer= null;
super.dispose();
}
public Control getControl() {
if (fOutlineViewer != null)
return fOutlineViewer.getControl();
return null;
}
public void setInput(IJavaElement inputElement) {
fInput= inputElement;
if (fOutlineViewer != null)
fOutlineViewer.setInput(fInput);
}
public void select(ISourceReference reference) {
if (fOutlineViewer != null) {
ISelection s= fOutlineViewer.getSelection();
if (s instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) s;
List elements= ss.toList();
if (!elements.contains(reference)) {
s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
fOutlineViewer.setSelection(s, true);
}
}
}
}
public void setAction(String actionID, IAction action) {
Assert.isNotNull(actionID);
if (action == null)
fActions.remove(actionID);
else
fActions.put(actionID, action);
}
public IAction getAction(String actionID) {
Assert.isNotNull(actionID);
return (IAction) fActions.get(actionID);
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES };
}
};
}
if (key == IShowInTarget.class) {
return getShowInTarget();
}
return null;
}
/**
* Convenience method to add the action installed under the given actionID to the
* specified group of the menu.
*/
protected void addAction(IMenuManager menu, String group, String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
if (action.isEnabled()) {
IMenuManager subMenu= menu.findMenuUsingPath(group);
if (subMenu != null)
subMenu.add(action);
else
menu.appendToGroup(group, action);
}
}
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection)getSelection();
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
}
/*
* @see Page#setFocus()
*/
public void setFocus() {
if (fOutlineViewer != null)
fOutlineViewer.getControl().setFocus();
}
/**
* Checkes whether a given Java element is an inner type.
*/
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;
}
/**
* Handles key events in viewer.
*/
private void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
}
if (action != null && action.isEnabled())
action.run();
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
/**
* Returns the <code>IShowInTarget</code> for this view.
*/
protected IShowInTarget getShowInTarget() {
return new IShowInTarget() {
public boolean show(ShowInContext context) {
ISelection sel= context.getSelection();
if (sel instanceof ITextSelection) {
ITextSelection tsel= (ITextSelection) sel;
int offset= tsel.getOffset();
IJavaElement element= fEditor.getElementAt(offset);
if (element != null) {
setSelection(new StructuredSelection(element));
return true;
}
}
return false;
}
};
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fOutlineViewer)
};
fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners));
}
}
|
40,342 |
Bug 40342 quickfix from anonymous class creates wrong visibility method
|
------------------B.java-------------- package b; public class B { } -------------------------------------- ------------------A.java-------------- package a; import b.B; public class A { void method() { I i = new I() { public void method() { B.quickFixMethod(); //<-- use quickfix here } }; } } interface I { void method(); } ----------------------------------------- if you use quickfix to create the missing method quickfix produces: protected static void quickFixMethod() which is not visible from A.java it should be public!
|
resolved fixed
|
e463ba2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T16:42:07Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.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.tests.quickfix;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.internal.ui.text.correction.AssistContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation;
/**
*/
public class QuickFixTest extends TestCase {
public static Test suite() {
TestSuite suite= new TestSuite();
suite.addTest(UnresolvedTypesQuickFixTest.allTests());
suite.addTest(UnresolvedVariablesQuickFixTest.allTests());
suite.addTest(UnresolvedMethodsQuickFixTest.allTests());
suite.addTest(ReturnTypeQuickFixTest.allTests());
suite.addTest(LocalCorrectionsQuickFixTest.allTests());
suite.addTest(ReorgQuickFixTest.allTests());
suite.addTest(ModifierCorrectionsQuickFixTest.allTests());
suite.addTest(AssistQuickFixTest.allTests());
suite.addTest(MarkerResolutionTest.allTests());
return new ProjectTestSetup(suite);
}
public QuickFixTest(String name) {
super(name);
}
public static void assertCorrectLabels(List proposals) {
for (int i= 0; i < proposals.size(); i++) {
ICompletionProposal proposal= (ICompletionProposal) proposals.get(i);
String name= proposal.getDisplayString();
if (name == null || name.length() == 0 || name.charAt(0) == '!' || name.indexOf('{') != -1) {
assertTrue("wrong proposal label: " + name, false);
}
if (proposal.getImage() == null) {
assertTrue("wrong proposal image", false);
}
}
}
public static void assertCorrectContext(IInvocationContext context, ProblemLocation problem) {
if (problem.getProblemId() != 0) {
assertTrue("Problem type not marked with lightbulb", JavaCorrectionProcessor.hasCorrections(context.getCompilationUnit(), problem.getProblemId()));
}
}
public static void assertNumberOf(String name, int nProblems, int nProblemsExpected) {
assertTrue("Wrong number of " + name + ", is: " + nProblems + ", expected: " + nProblemsExpected, nProblems == nProblemsExpected);
}
public static void assertEqualStringsIgnoreOrder(String[] str1, String[] str2) {
ArrayList list1= new ArrayList(Arrays.asList(str1));
ArrayList list2= new ArrayList(Arrays.asList(str2));
for (int i= list1.size() - 1; i >= 0; i--) {
if (list2.remove(list1.get(i))) {
list1.remove(i);
}
}
int n1= list1.size();
int n2= list2.size();
if (n1 + n2 > 0) {
if (n1 == 1 && n2 == 1) {
assertEqualString((String) list1.get(0), (String) list2.get(0));
}
StringBuffer buf= new StringBuffer();
buf.append("Content not as expected: Content is: \n");
for (int i= 0; i < n1; i++) {
String s1= (String) list1.get(i);
if (s1 != null) {
buf.append(s1);
buf.append("\n");
}
}
buf.append("Expected contents: \n");
for (int i= 0; i < n2; i++) {
String s2= (String) list2.get(i);
if (s2 != null) {
buf.append(s2);
buf.append("\n");
}
}
assertTrue(buf.toString(), false);
}
}
private static int getDiffPos(String str1, String str2) {
int len1= Math.min(str1.length(), str2.length());
int diffPos= -1;
for (int i= 0; i < len1; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
diffPos= i;
break;
}
}
if (diffPos == -1 && str1.length() != str2.length()) {
diffPos= len1;
}
return diffPos;
}
private static final int printRange= 6;
public static void assertEqualString(String str1, String str2) {
int diffPos= getDiffPos(str1, str2);
if (diffPos != -1) {
int diffAhead= Math.max(0, diffPos - printRange);
int diffAfter= Math.min(str1.length(), diffPos + printRange);
String diffStr= str1.substring(diffAhead, diffPos) + '^' + str1.substring(diffPos, diffAfter);
assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + str2, false);
}
}
public static void assertEqualStringIgnoreDelim(String str1, String str2) throws IOException {
BufferedReader read1= new BufferedReader(new StringReader(str1));
BufferedReader read2= new BufferedReader(new StringReader(str2));
int line= 1;
do {
String s1= read1.readLine();
String s2= read2.readLine();
if (s1 == null || !s1.equals(s2)) {
if (s1 == null && s2 == null) {
return;
}
String diffStr= (s1 == null) ? s2 : s1;
assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at line " + line + ": " + diffStr + "\nexpected:\n" + str2, false);
}
line++;
} while (true);
}
public static TypeDeclaration findTypeDeclaration(CompilationUnit astRoot, String simpleTypeName) {
List types= astRoot.types();
for (int i= 0; i < types.size(); i++) {
TypeDeclaration elem= (TypeDeclaration) types.get(i);
if (simpleTypeName.equals(elem.getName().getIdentifier())) {
return elem;
}
}
return null;
}
public static MethodDeclaration findMethodDeclaration(TypeDeclaration typeDecl, String methodName) {
MethodDeclaration[] methods= typeDecl.getMethods();
for (int i= 0; i < methods.length; i++) {
if (methodName.equals(methods[i].getName().getIdentifier())) {
return methods[i];
}
}
return null;
}
public static VariableDeclarationFragment findFieldDeclaration(TypeDeclaration typeDecl, String fieldName) {
FieldDeclaration[] fields= typeDecl.getFields();
for (int i= 0; i < fields.length; i++) {
List list= fields[i].fragments();
for (int k= 0; k < list.size(); k++) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) list.get(k);
if (fieldName.equals(fragment.getName().getIdentifier())) {
return fragment;
}
}
}
return null;
}
public static AssistContext getCorrectionContext(ICompilationUnit cu, int offset, int length) {
AssistContext context= new AssistContext(cu, offset, length);
return context;
}
protected final ArrayList collectCorrections(ICompilationUnit cu, CompilationUnit astRoot) {
return collectCorrections(cu, astRoot, 1);
}
protected final ArrayList collectCorrections(ICompilationUnit cu, CompilationUnit astRoot, int nProblems) {
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, nProblems);
IProblem curr= problems[0];
int offset= curr.getSourceStart();
int length= curr.getSourceEnd() + 1 - offset;
ProblemLocation problem= new ProblemLocation(offset, length, curr.getID(), curr.getArguments());
AssistContext context= new AssistContext(cu, offset, length);
assertCorrectContext(context, problem);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, new ProblemLocation[] { problem }, proposals);
return proposals;
}
}
|
40,342 |
Bug 40342 quickfix from anonymous class creates wrong visibility method
|
------------------B.java-------------- package b; public class B { } -------------------------------------- ------------------A.java-------------- package a; import b.B; public class A { void method() { I i = new I() { public void method() { B.quickFixMethod(); //<-- use quickfix here } }; } } interface I { void method(); } ----------------------------------------- if you use quickfix to create the missing method quickfix produces: protected static void quickFixMethod() which is not visible from A.java it should be public!
|
resolved fixed
|
e463ba2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T16:42:07Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedMethodsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.NewMethodCompletionProposal;
public class UnresolvedMethodsQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedMethodsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedMethodsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedMethodsQuickFixTest("testMethodInForInit"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
fJProject1= ProjectTestSetup.getProject();
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testMethodInSameType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
private static final boolean bug_37381= true;
public void testMethodInForInit() throws Exception {
if (bug_37381) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(int i) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing0EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing1EmptyLine() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing2EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingComment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingNonJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInSameTypeUsingThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentClass() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(1, 2.1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("\n");
buf.append(" public boolean goo(int i, double d) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentInterface() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(getClass());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("\n");
buf.append(" boolean goo(Class class1);\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testParameterMismatchCast() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo((int) (x + 1));\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(long l) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(long l) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchCast2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((float) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((int) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(float f, E e) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(float f, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x, o);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(null);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(0, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(Object object) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, 1, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, int j, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(int i, int j, X x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(String s, int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int x2) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(Collections.EMPTY_SET, 1, 2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(Set set, int i, int k) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(Set set, int i, int j) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchSwap() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(i - 1, new Object[] { o });\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(Object[] objects, int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o, int i) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" super.foo(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCanAssign() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Collection;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public class E {\n");
buf.append(" boolean bool;\n");
buf.append(" char c;\n");
buf.append(" byte b;\n");
buf.append(" short s;\n");
buf.append(" int i;\n");
buf.append(" long l;\n");
buf.append(" float f;\n");
buf.append(" double d;\n");
buf.append(" Object object;\n");
buf.append(" Vector vector;\n");
buf.append(" Cloneable cloneable;\n");
buf.append(" Collection collection;\n");
buf.append(" Serializable serializable;\n");
buf.append(" Object[] objectArr;\n");
buf.append(" int[] int_arr;\n");
buf.append(" long[] long_arr;\n");
buf.append(" Vector[] vector_arr;\n");
buf.append(" Collection[] collection_arr;\n");
buf.append(" Object[][] objectArrArr;\n");
buf.append(" Collection[][] collection_arrarr;\n");
buf.append(" Vector[][] vector_arrarr;\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
VariableDeclarationFragment bool= findFieldDeclaration(type, "bool");
VariableDeclarationFragment c= findFieldDeclaration(type, "c");
VariableDeclarationFragment b= findFieldDeclaration(type, "b");
VariableDeclarationFragment s= findFieldDeclaration(type, "s");
VariableDeclarationFragment i= findFieldDeclaration(type, "i");
VariableDeclarationFragment l= findFieldDeclaration(type, "l");
VariableDeclarationFragment f= findFieldDeclaration(type, "f");
VariableDeclarationFragment d= findFieldDeclaration(type, "d");
VariableDeclarationFragment object= findFieldDeclaration(type, "object");
VariableDeclarationFragment vector= findFieldDeclaration(type, "vector");
VariableDeclarationFragment cloneable= findFieldDeclaration(type, "cloneable");
VariableDeclarationFragment collection= findFieldDeclaration(type, "collection");
VariableDeclarationFragment serializable= findFieldDeclaration(type, "serializable");
VariableDeclarationFragment objectArr= findFieldDeclaration(type, "objectArr");
VariableDeclarationFragment int_arr= findFieldDeclaration(type, "int_arr");
VariableDeclarationFragment long_arr= findFieldDeclaration(type, "long_arr");
VariableDeclarationFragment vector_arr= findFieldDeclaration(type, "vector_arr");
VariableDeclarationFragment collection_arr= findFieldDeclaration(type, "collection_arr");
VariableDeclarationFragment objectArrArr= findFieldDeclaration(type, "objectArrArr");
VariableDeclarationFragment collection_arrarr= findFieldDeclaration(type, "collection_arrarr");
VariableDeclarationFragment vector_arrarr= findFieldDeclaration(type, "vector_arrarr");
VariableDeclarationFragment[] targets= new VariableDeclarationFragment[] {
bool, c, b, s, i, l, f, d, object, vector, cloneable, serializable, collection, objectArr, int_arr, long_arr,
vector_arr, collection_arr, objectArrArr, collection_arrarr, vector_arrarr
};
for (int k= 0; k < targets.length; k++) {
for (int n= 0; n < targets.length; n++) {
VariableDeclarationFragment f1= targets[k];
VariableDeclarationFragment f2= targets[n];
String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F extends E {\n");
buf.append(" void foo() {\n");
buf.append(" ").append(line).append(";\n");
buf.append(" }\n");
buf.append("}\n");
char[] content= buf.toString().toCharArray();
astRoot= AST.parseCompilationUnit(content, "F.java", cu1.getJavaProject());
problems= astRoot.getProblems();
ITypeBinding b1= f1.resolveBinding().getType();
assertNotNull(b1);
ITypeBinding b2= f2.resolveBinding().getType();
assertNotNull(b2);
boolean res= TypeRules.canAssign(b1, b2.getQualifiedName());
assertEquals(line, problems.length == 0, res);
boolean res2= TypeRules.canAssign(b1, b2);
assertEquals(line, problems.length == 0, res2);
}
}
}
}
|
40,342 |
Bug 40342 quickfix from anonymous class creates wrong visibility method
|
------------------B.java-------------- package b; public class B { } -------------------------------------- ------------------A.java-------------- package a; import b.B; public class A { void method() { I i = new I() { public void method() { B.quickFixMethod(); //<-- use quickfix here } }; } } interface I { void method(); } ----------------------------------------- if you use quickfix to create the missing method quickfix produces: protected static void quickFixMethod() which is not visible from A.java it should be public!
|
resolved fixed
|
e463ba2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T16:42:07Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.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.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
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.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class NewMethodCompletionProposal extends LinkedCorrectionProposal {
private static final String KEY_NAME= "name"; //$NON-NLS-1$
private static final String KEY_TYPE= "type"; //$NON-NLS-1$
private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation
private List fArguments;
private ITypeBinding fSenderBinding;
private boolean fIsInDifferentCU;
public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) {
super(label, targetCU, null, relevance, image);
fNode= invocationNode;
fArguments= arguments;
fSenderBinding= binding;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
ASTNode newTypeDecl= null;
if (typeDecl != null) {
fIsInDifferentCU= false;
newTypeDecl= typeDecl;
} else {
fIsInDifferentCU= true;
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newTypeDecl != null) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
List members;
if (fSenderBinding.isAnonymous()) {
members= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations();
} else {
members= ((TypeDeclaration) newTypeDecl).bodyDeclarations();
}
MethodDeclaration newStub= getStub(rewrite, newTypeDecl);
if (isConstructor()) {
members.add(findConstructorInsertIndex(members), newStub);
} else if (!fIsInDifferentCU) {
members.add(findMethodInsertIndex(members, fNode.getStartPosition()), newStub);
} else {
members.add(newStub);
}
rewrite.markAsInserted(newStub);
if (!fIsInDifferentCU) {
Name invocationName= getInvocationName();
if (invocationName != null) {
markAsLinked(rewrite, invocationName, true, KEY_NAME);
}
}
markAsLinked(rewrite, newStub.getName(), false, KEY_NAME); //$NON-NLS-1$
if (!newStub.isConstructor()) {
markAsLinked(rewrite, newStub.getReturnType(), false, KEY_TYPE); //$NON-NLS-1$
}
return rewrite;
}
return null;
}
private boolean isConstructor() {
return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION;
}
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
AST ast= targetTypeDecl.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(isConstructor());
decl.setModifiers(evaluateModifiers(targetTypeDecl));
decl.setName(ast.newSimpleName(getMethodName()));
List arguments= fArguments;
List params= decl.parameters();
int nArguments= arguments.size();
ArrayList takenNames= new ArrayList(nArguments);
IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
takenNames.add(declaredFields[i].getName());
}
for (int i= 0; i < arguments.size(); i++) {
Expression elem= (Expression) arguments.get(i);
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
// argument type
String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
Type type= evaluateParameterTypes(ast, elem, argTypeKey);
param.setType(type);
// argument name
String argNameKey= "arg_name_" + i; //$NON-NLS-1$
String name= evaluateParameterNames(takenNames, elem, type, argNameKey);
param.setName(ast.newSimpleName(name));
params.add(param);
markAsLinked(rewrite, param.getType(), false, argTypeKey);
markAsLinked(rewrite, param.getName(), false, argNameKey);
}
Block body= null;
String bodyStatement= ""; //$NON-NLS-1$
if (!isConstructor()) {
Type returnType= evaluateMethodType(ast);
if (returnType == null) {
decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID));
} else {
decl.setReturnType(returnType);
}
if (!fSenderBinding.isInterface() && returnType != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'));
}
}
if (!fSenderBinding.isInterface()) {
body= ast.newBlock();
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), getMethodName(), isConstructor(), bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
}
decl.setBody(body);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (settings.createComments && !fSenderBinding.isAnonymous()) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private int findMethodInsertIndex(List decls, int currPos) {
int nDecls= decls.size();
for (int i= 0; i < nDecls; i++) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) {
return i + 1;
}
}
return nDecls;
}
private int findConstructorInsertIndex(List decls) {
int nDecls= decls.size();
int lastMethod= 0;
for (int i= nDecls - 1; i >= 0; i--) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration) {
if (((MethodDeclaration) curr).isConstructor()) {
return i + 1;
}
lastMethod= i;
}
}
return lastMethod;
}
private Name getInvocationName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName();
} else if (fNode instanceof ClassInstanceCreation) {
return ((ClassInstanceCreation)fNode).getName();
}
return null;
}
private String getMethodName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName().getIdentifier();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName().getIdentifier();
} else {
return fSenderBinding.getName(); // name of the class
}
}
private int evaluateModifiers(ASTNode targetTypeDecl) {
if (fSenderBinding.isInterface()) {
// for interface members copy the modifiers from an existing field
MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods();
if (methodDecls.length > 0) {
return methodDecls[0].getModifiers();
}
return 0;
}
if (fNode instanceof MethodInvocation) {
int modifiers= 0;
Expression expression= ((MethodInvocation)fNode).getExpression();
if (expression != null) {
if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
modifiers |= Modifier.STATIC;
}
} else if (ASTResolving.isInStaticContext(fNode)) {
modifiers |= Modifier.STATIC;
}
ASTNode node= ASTResolving.findParentType(fNode);
if (targetTypeDecl.equals(node)) {
modifiers |= Modifier.PRIVATE;
} else if (node instanceof AnonymousClassDeclaration) {
modifiers |= Modifier.PROTECTED;
} else {
modifiers |= Modifier.PUBLIC;
}
return modifiers;
}
return Modifier.PUBLIC;
}
private Type evaluateMethodType(AST ast) throws CoreException {
ITypeBinding binding= ASTResolving.guessBindingForReference(fNode);
if (binding != null) {
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
} else {
ASTNode parent= fNode.getParent();
if (!(parent instanceof ExpressionStatement)) {
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
}
return null;
}
private Type evaluateParameterTypes(AST ast, Expression elem, String key) throws CoreException {
ITypeBinding binding= Bindings.normalizeTypeBinding(elem.resolveTypeBinding());
if (binding != null) {
ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding);
for (int i= 0; i < typeProposals.length; i++) {
addLinkedModeProposal(key, typeProposals[i]);
}
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
private String evaluateParameterNames(ArrayList takenNames, Expression argNode, Type type, String key) {
IJavaProject project= getCompilationUnit().getJavaProject();
String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]);
String favourite= null;
if (argNode instanceof SimpleName) {
SimpleName name= (SimpleName) argNode;
favourite= StubUtility.guessArgumentName(project, name.getIdentifier(), excludedNames);
}
int dim= 0;
if (type.isArrayType()) {
ArrayType arrayType= (ArrayType) type;
dim= arrayType.getDimensions();
type= arrayType.getElementType();
}
String typeName= ASTNodes.asString(type);
String packName= Signature.getQualifier(typeName);
String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames);
if (favourite == null) {
favourite= names[0];
}
for (int i= 0; i < names.length; i++) {
addLinkedModeProposal(key, names[i]);
}
takenNames.add(favourite);
return favourite;
}
}
|
40,300 |
Bug 40300 Compiler pref page does not disable unavailable preferences [build path]
|
I20030716 + plug-in export If I set a parent preference to ignore I'd expect that sub-properties get disabled.
|
verified fixed
|
be2c76b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T17:36:55Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerConfigurationBlock.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/**
*/
public class CompilerConfigurationBlock extends OptionsConfigurationBlock {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR;
private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR;
private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR;
private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL;
private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM;
//private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE;
//private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT;
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD;
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME;
private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION;
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK;
private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL;
private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER;
private static final String PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_OVERRIDING_CONCRETE;
private static final String PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT= JavaCore.COMPILER_PB_UNUSED_PARAMETER_WHEN_IMPLEMENTING_ABSTRACT;
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION;
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL;
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER;
private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT;
private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT;
private static final String PREF_PB_UNUSED_PRIVATE= JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER;
private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER;
private static final String PREF_PB_NO_EFFECT_ASSIGNMENT= JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT;
private static final String PREF_PB_CHAR_ARRAY_IN_CONCAT= JavaCore.COMPILER_PB_CHAR_ARRAY_IN_STRING_CONCATENATION;
private static final String PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT= JavaCore.COMPILER_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT;
private static final String PREF_PB_LOCAL_VARIABLE_HIDING= JavaCore.COMPILER_PB_LOCAL_VARIABLE_HIDING;
private static final String PREF_PB_FIELD_HIDING= JavaCore.COMPILER_PB_FIELD_HIDING;
private static final String PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD= JavaCore.COMPILER_PB_SPECIAL_PARAMETER_HIDING_FIELD;
private static final String PREF_PB_INDIRECT_STATIC_ACCESS= JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS;
private static final String PREF_PB_SUPERFLUOUS_SEMICOLON= JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON;
private static final String PREF_PB_UNNECESSARY_TYPE_CHECK= JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK;
private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE;
private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE;
private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER;
private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH;
private static final String PREF_BUILD_CLEAN_OUTPUT_FOLDER= JavaCore.CORE_JAVA_BUILD_CLEAN_OUTPUT_FOLDER;
private static final String PREF_ENABLE_EXCLUSION_PATTERNS= JavaCore.CORE_ENABLE_CLASSPATH_EXCLUSION_PATTERNS;
private static final String PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS= JavaCore.CORE_ENABLE_CLASSPATH_MULTIPLE_OUTPUT_LOCATIONS;
private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH;
private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH;
private static final String PREF_PB_INCOMPATIBLE_JDK_LEVEL= JavaCore.CORE_INCOMPATIBLE_JDK_LEVEL;
private static final String PREF_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE;
private static final String PREF_PB_DUPLICATE_RESOURCE= JavaCore.CORE_JAVA_BUILD_DUPLICATE_RESOURCE;
private static final String PREF_PB_INCOMPATIBLE_INTERFACE_METHOD= JavaCore.COMPILER_PB_INCOMPATIBLE_NON_INHERITED_INTERFACE_METHOD;
private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$
// values
private static final String GENERATE= JavaCore.GENERATE;
private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE;
private static final String PRESERVE= JavaCore.PRESERVE;
private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT;
private static final String VERSION_1_1= JavaCore.VERSION_1_1;
private static final String VERSION_1_2= JavaCore.VERSION_1_2;
private static final String VERSION_1_3= JavaCore.VERSION_1_3;
private static final String VERSION_1_4= JavaCore.VERSION_1_4;
private static final String ERROR= JavaCore.ERROR;
private static final String WARNING= JavaCore.WARNING;
private static final String IGNORE= JavaCore.IGNORE;
private static final String ABORT= JavaCore.ABORT;
private static final String CLEAN= JavaCore.CLEAN;
private static final String ENABLED= JavaCore.ENABLED;
private static final String DISABLED= JavaCore.DISABLED;
private static final String DEFAULT= "default"; //$NON-NLS-1$
private static final String USER= "user"; //$NON-NLS-1$
private ArrayList fComplianceControls;
private PixelConverter fPixelConverter;
private IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus;
public CompilerConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
super(context, project);
fComplianceControls= new ArrayList();
fComplianceStatus= new StatusInfo();
fMaxNumberProblemsStatus= new StatusInfo();
fResourceFilterStatus= new StatusInfo();
}
private final String[] KEYS= new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD,
PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL,
PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS,
PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE,
PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH,
PREF_PB_CIRCULAR_BUILDPATH, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_BUILD_CLEAN_OUTPUT_FOLDER,
PREF_PB_DUPLICATE_RESOURCE, PREF_PB_NO_EFFECT_ASSIGNMENT, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD,
PREF_PB_UNUSED_PRIVATE, PREF_PB_CHAR_ARRAY_IN_CONCAT, PREF_ENABLE_EXCLUSION_PATTERNS, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS,
PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, PREF_PB_LOCAL_VARIABLE_HIDING, PREF_PB_FIELD_HIDING,
PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, PREF_PB_INCOMPATIBLE_JDK_LEVEL, PREF_PB_INDIRECT_STATIC_ACCESS,
PREF_PB_SUPERFLUOUS_SEMICOLON, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT,
PREF_PB_UNNECESSARY_TYPE_CHECK
};
protected String[] getAllKeys() {
return KEYS;
}
protected final Map getOptions(boolean inheritJavaCoreOptions) {
Map map= super.getOptions(inheritJavaCoreOptions);
map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map));
return map;
}
protected final Map getDefaultOptions() {
Map map= super.getDefaultOptions();
map.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance(map));
return map;
}
/*
* @see org.eclipse.jface.preference.PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
fPixelConverter= new PixelConverter(parent);
setShell(parent.getShell());
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite commonComposite= createStyleTabContent(folder);
Composite unusedComposite= createUnusedCodeTabContent(folder);
Composite advancedComposite= createAdvancedTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
Composite othersComposite= createBuildPathTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.tabtitle")); //$NON-NLS-1$
item.setControl(commonComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.tabtitle")); //$NON-NLS-1$
item.setControl(advancedComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.tabtitle")); //$NON-NLS-1$
item.setControl(unusedComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.tabtitle")); //$NON-NLS-1$
item.setControl(complianceComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(PreferencesMessages.getString("CompilerConfigurationBlock.others.tabtitle")); //$NON-NLS-1$
item.setControl(othersComposite);
validateSettings(null, null);
return folder;
}
private Composite createStyleTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.common.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_static_access_receiver.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_no_effect_assignment.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_NO_EFFECT_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_indirect_access_to_static.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INDIRECT_STATIC_ACCESS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_accidential_assignement.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_POSSIBLE_ACCIDENTAL_BOOLEAN_ASSIGNMENT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return composite;
}
private Composite createAdvancedTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.advanced.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_local_variable_hiding.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_LOCAL_VARIABLE_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_special_param_hiding.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_SPECIAL_PARAMETER_HIDING_FIELD, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_field_hiding.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_FIELD_HIDING, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incompatible_interface_method.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_INCOMPATIBLE_INTERFACE_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_char_array_in_concat.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_CHAR_ARRAY_IN_CONCAT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
gd= new GridData();
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(6);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_max_per_unit.label"); //$NON-NLS-1$
Text text= addTextField(composite, label, PREF_PB_MAX_PER_UNIT, 0, 0);
text.setTextLimit(6);
text.setLayoutData(gd);
return composite;
}
private Composite createUnusedCodeTabContent(TabFolder folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
String[] enabledDisabled= new String[] { ENABLED, DISABLED };
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite composite= new Composite(folder, SWT.NULL);
composite.setLayout(layout);
Label description= new Label(composite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.unused.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(50);
description.setLayoutData(gd);
Composite combos= composite;
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_overriding.label"); //$NON-NLS-1$
addCheckBox(combos, label, PREF_PB_SIGNAL_PARAMETER_IN_OVERRIDING, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_signal_param_in_abstract.label"); //$NON-NLS-1$
addCheckBox(combos, label, PREF_PB_SIGNAL_PARAMETER_IN_ABSTRACT, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_imports.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unused_private.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_UNUSED_PRIVATE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(combos, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$
addCheckBox(composite, label, PREF_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_superfluous_semicolon.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_SUPERFLUOUS_SEMICOLON, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_unnecessary_type_check.label"); //$NON-NLS-1$
addComboBox(composite, label, PREF_PB_UNNECESSARY_TYPE_CHECK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return composite;
}
private Composite createBuildPathTabContent(TabFolder folder) {
String[] abortIgnoreValues= new String[] { ABORT, IGNORE };
String[] cleanIgnoreValues= new String[] { CLEAN, IGNORE };
String[] enableDisableValues= new String[] { ENABLED, DISABLED };
String[] errorWarning= new String[] { ERROR, WARNING };
String[] errorWarningLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning") //$NON-NLS-1$
};
int nColumns= 3;
GridLayout layout= new GridLayout();
layout.numColumns= nColumns;
Composite othersComposite= new Composite(folder, SWT.NULL);
othersComposite.setLayout(layout);
Label description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.build_warnings.description")); //$NON-NLS-1$
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= nColumns;
description.setLayoutData(gd);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_incomplete_build_path.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_build_path_cycles.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_duplicate_resources.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_DUPLICATE_RESOURCE, errorWarning, errorWarningLabels, 0);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_check_prereq_binary_level.label"); //$NON-NLS-1$
addComboBox(othersComposite, label, PREF_PB_INCOMPATIBLE_JDK_LEVEL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_invalid_classpath.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.build_clean_outputfolder.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_BUILD_CLEAN_OUTPUT_FOLDER, cleanIgnoreValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.enable_exclusion_patterns.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_ENABLE_EXCLUSION_PATTERNS, enableDisableValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.enable_multiple_outputlocations.label"); //$NON-NLS-1$
addCheckBox(othersComposite, label, PREF_ENABLE_MULTIPLE_OUTPUT_LOCATIONS, enableDisableValues, 0);
description= new Label(othersComposite, SWT.WRAP);
description.setText(PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.description")); //$NON-NLS-1$
gd= new GridData(GridData.FILL);
gd.horizontalSpan= nColumns;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
label= PreferencesMessages.getString("CompilerConfigurationBlock.resource_filter.label"); //$NON-NLS-1$
Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER, 0, 0);
gd= (GridData) text.getLayoutData();
gd.grabExcessHorizontalSpace= true;
gd.widthHint= fPixelConverter.convertWidthInCharsToPixels(10);
return othersComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 1;
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
Composite compComposite= new Composite(folder, SWT.NULL);
compComposite.setLayout(layout);
int nColumns= 3;
layout= new GridLayout();
layout.numColumns= nColumns;
Group group= new Group(compComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.compliance.group.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String label= PreferencesMessages.getString("CompilerConfigurationBlock.compiler_compliance.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_COMPLIANCE, values34, values34Labels, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.default_settings.label"); //$NON-NLS-1$
addCheckBox(group, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0);
int indent= fPixelConverter.convertWidthInCharsToPixels(2);
Control[] otherChildren= group.getChildren();
String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] values14Labels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.version11"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version12"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version13"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.version14") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_compatibility.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
PreferencesMessages.getString("CompilerConfigurationBlock.error"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.warning"), //$NON-NLS-1$
PreferencesMessages.getString("CompilerConfigurationBlock.ignore") //$NON-NLS-1$
};
label= PreferencesMessages.getString("CompilerConfigurationBlock.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(group, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
Control[] allChildren= group.getChildren();
fComplianceControls.addAll(Arrays.asList(allChildren));
fComplianceControls.removeAll(Arrays.asList(otherChildren));
layout= new GridLayout();
layout.numColumns= nColumns;
group= new Group(compComposite, SWT.NONE);
group.setText(PreferencesMessages.getString("CompilerConfigurationBlock.classfiles.group.label")); //$NON-NLS-1$
group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
group.setLayout(layout);
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
label= PreferencesMessages.getString("CompilerConfigurationBlock.variable_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= PreferencesMessages.getString("CompilerConfigurationBlock.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(group, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return compComposite;
}
/* (non-javadoc)
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
protected void validateSettings(String changedKey, String newValue) {
if (changedKey != null) {
if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
updateComplianceEnableState();
if (DEFAULT.equals(newValue)) {
updateComplianceDefaultSettings();
}
fComplianceStatus= validateCompliance();
} else if (PREF_COMPLIANCE.equals(changedKey)) {
if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) {
updateComplianceDefaultSettings();
}
fComplianceStatus= validateCompliance();
} else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) ||
PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) ||
PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) {
fComplianceStatus= validateCompliance();
} else if (PREF_PB_MAX_PER_UNIT.equals(changedKey)) {
fMaxNumberProblemsStatus= validateMaxNumberProblems();
} else if (PREF_RESOURCE_FILTER.equals(changedKey)) {
fResourceFilterStatus= validateResourceFilters();
} else {
return;
}
} else {
updateComplianceEnableState();
fComplianceStatus= validateCompliance();
fMaxNumberProblemsStatus= validateMaxNumberProblems();
fResourceFilterStatus= validateResourceFilters();
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus });
fContext.statusChanged(status);
}
private IStatus validateCompliance() {
StatusInfo status= new StatusInfo();
if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) {
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13src14.error")); //$NON-NLS-1$
return status;
} else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.cpl13trg14.error")); //$NON-NLS-1$
return status;
}
}
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14asrterr.error")); //$NON-NLS-1$
return status;
}
}
if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.src14tgt14.error")); //$NON-NLS-1$
return status;
}
}
return status;
}
private IStatus validateMaxNumberProblems() {
String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT);
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(PreferencesMessages.getString("CompilerConfigurationBlock.empty_input")); //$NON-NLS-1$
} else {
try {
int value= Integer.parseInt(number);
if (value <= 0) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(PreferencesMessages.getFormattedString("CompilerConfigurationBlock.invalid_input", number)); //$NON-NLS-1$
}
}
return status;
}
private IStatus validateResourceFilters() {
String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER);
IWorkspace workspace= ResourcesPlugin.getWorkspace();
String[] filters= getTokens(text, ","); //$NON-NLS-1$
for (int i= 0; i < filters.length; i++) {
String fileName= filters[i].replace('*', 'x');
int resourceType= IResource.FILE;
int lastCharacter= fileName.length() - 1;
if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') {
fileName= fileName.substring(0, lastCharacter);
resourceType= IResource.FOLDER;
}
IStatus status= workspace.validateName(fileName, resourceType);
if (status.matches(IStatus.ERROR)) {
String message= PreferencesMessages.getFormattedString("CompilerConfigurationBlock.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$
return new StatusInfo(IStatus.ERROR, message);
}
}
return new StatusInfo();
}
/*
* Update the compliance controls' enable state
*/
private void updateComplianceEnableState() {
boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER);
for (int i= fComplianceControls.size() - 1; i >= 0; i--) {
Control curr= (Control) fComplianceControls.get(i);
curr.setEnabled(enabled);
}
}
/*
* Set the default compliance values derived from the chosen level
*/
private void updateComplianceDefaultSettings() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if (VERSION_1_3.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1);
} else if (VERSION_1_4.equals(complianceLevel)) {
fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR);
fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_4);
fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4);
}
updateControls();
}
/*
* Evaluate if the current compliance setting correspond to a default setting
*/
private static String getCurrentCompliance(Map map) {
Object complianceLevel= map.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& IGNORE.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER))
&& VERSION_1_3.equals(map.get(PREF_SOURCE_COMPATIBILITY))
&& VERSION_1_1.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))
|| (VERSION_1_4.equals(complianceLevel)
&& ERROR.equals(map.get(PREF_PB_ASSERT_AS_IDENTIFIER))
&& VERSION_1_4.equals(map.get(PREF_SOURCE_COMPATIBILITY))
&& VERSION_1_4.equals(map.get(PREF_CODEGEN_TARGET_PLATFORM)))) {
return DEFAULT;
}
return USER;
}
protected String[] getFullBuildDialogStrings(boolean workspaceSettings) {
String title= PreferencesMessages.getString("CompilerConfigurationBlock.needsbuild.title"); //$NON-NLS-1$
String message;
if (workspaceSettings) {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$
} else {
message= PreferencesMessages.getString("CompilerConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$
}
return new String[] { title, message };
}
}
|
40,300 |
Bug 40300 Compiler pref page does not disable unavailable preferences [build path]
|
I20030716 + plug-in export If I set a parent preference to ignore I'd expect that sub-properties get disabled.
|
verified fixed
|
be2c76b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-21T17:36:55Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/OptionsConfigurationBlock.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
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.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
/**
*/
public abstract class OptionsConfigurationBlock {
protected static class ControlData {
private String fKey;
private String[] fValues;
public ControlData(String key, String[] values) {
fKey= key;
fValues= values;
}
public String getKey() {
return fKey;
}
public String getValue(boolean selection) {
int index= selection ? 0 : 1;
return fValues[index];
}
public String getValue(int index) {
return fValues[index];
}
public int getSelection(String value) {
for (int i= 0; i < fValues.length; i++) {
if (value.equals(fValues[i])) {
return i;
}
}
throw new IllegalArgumentException();
}
}
protected Map fWorkingValues;
protected ArrayList fCheckBoxes;
protected ArrayList fComboBoxes;
protected ArrayList fTextBoxes;
private SelectionListener fSelectionListener;
private ModifyListener fTextModifyListener;
protected IStatusChangeListener fContext;
protected IJavaProject fProject; // project or null
private Shell fShell;
public OptionsConfigurationBlock(IStatusChangeListener context, IJavaProject project) {
fContext= context;
fProject= project;
fWorkingValues= getOptions(true);
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fTextBoxes= new ArrayList(2);
}
protected abstract String[] getAllKeys();
protected Map getOptions(boolean inheritJavaCoreOptions) {
if (fProject != null) {
return fProject.getOptions(inheritJavaCoreOptions);
} else {
return JavaCore.getOptions();
}
}
protected Map getDefaultOptions() {
return JavaCore.getDefaultOptions();
}
public final boolean hasProjectSpecificOptions() {
if (fProject != null) {
Map settings= fProject.getOptions(false);
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
if (settings.get(allKeys[i]) != null) {
return true;
}
}
}
return false;
}
protected final void setOptions(Map map) {
if (fProject != null) {
fProject.setOptions(map);
} else {
JavaCore.setOptions((Hashtable) map);
}
}
protected Shell getShell() {
return fShell;
}
protected void setShell(Shell shell) {
fShell= shell;
}
protected abstract Control createContents(Composite parent);
protected void addCheckBox(Composite parent, String label, String key, String[] values, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 3;
gd.horizontalIndent= indent;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(getSelectionListener());
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
fCheckBoxes.add(checkBox);
}
protected void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
gd.horizontalIndent= indent;
Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP);
labelControl.setText(label);
labelControl.setLayoutData(gd);
Combo comboBox= new Combo(parent, SWT.READ_ONLY);
comboBox.setItems(valueLabels);
comboBox.setData(data);
comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
comboBox.addSelectionListener(getSelectionListener());
Label placeHolder= new Label(parent, SWT.NONE);
placeHolder.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
protected Text addTextField(Composite parent, String label, String key, int indent, int widthHint) {
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(new GridData());
Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE);
textBox.setData(key);
textBox.setLayoutData(new GridData());
String currValue= (String) fWorkingValues.get(key);
textBox.setText(currValue);
textBox.addModifyListener(getTextModifyListener());
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
if (widthHint != 0) {
data.widthHint= widthHint;
}
data.horizontalIndent= indent;
data.horizontalSpan= 2;
textBox.setLayoutData(data);
fTextBoxes.add(textBox);
return textBox;
}
protected SelectionListener getSelectionListener() {
if (fSelectionListener == null) {
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
}
return fSelectionListener;
}
protected ModifyListener getTextModifyListener() {
if (fTextModifyListener == null) {
fTextModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
textChanged((Text) e.widget);
}
};
}
return fTextModifyListener;
}
protected void controlChanged(Widget widget) {
ControlData data= (ControlData) widget.getData();
String newValue= null;
if (widget instanceof Button) {
newValue= data.getValue(((Button)widget).getSelection());
} else if (widget instanceof Combo) {
newValue= data.getValue(((Combo)widget).getSelectionIndex());
} else {
return;
}
fWorkingValues.put(data.getKey(), newValue);
validateSettings(data.getKey(), newValue);
}
protected void textChanged(Text textControl) {
String key= (String) textControl.getData();
String number= textControl.getText();
fWorkingValues.put(key, number);
validateSettings(key, number);
}
protected boolean checkValue(String key, String value) {
return value.equals(fWorkingValues.get(key));
}
/* (non-javadoc)
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
protected abstract void validateSettings(String changedKey, String newValue);
protected String[] getTokens(String text, String separator) {
StringTokenizer tok= new StringTokenizer(text, separator); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < res.length; i++) {
res[i]= tok.nextToken().trim();
}
return res;
}
public boolean performOk(boolean enabled) {
String[] allKeys= getAllKeys();
Map actualOptions= getOptions(false);
// preserve other options
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String oldVal= (String) actualOptions.get(key);
String val= null;
if (enabled) {
val= (String) fWorkingValues.get(key);
if (!val.equals(oldVal)) {
hasChanges= true;
actualOptions.put(key, val);
}
} else {
if (oldVal != null) {
actualOptions.remove(key);
hasChanges= true;
}
}
}
if (hasChanges) {
boolean doBuild= false;
String[] strings= getFullBuildDialogStrings(fProject == null);
if (strings != null) {
MessageDialog dialog= new MessageDialog(getShell(), strings[0], null, strings[1], MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2);
int res= dialog.open();
if (res == 0) {
doBuild= true;
} else if (res != 1) {
return false; // cancel pressed
}
}
setOptions(actualOptions);
if (doBuild) {
doFullBuild();
}
}
return true;
}
protected abstract String[] getFullBuildDialogStrings(boolean workspaceSettings);
protected void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
monitor.beginTask("", 1); //$NON-NLS-1$
try {
if (fProject != null) {
monitor.setTaskName(PreferencesMessages.getFormattedString("OptionsConfigurationBlock.buildproject.taskname", fProject.getElementName())); //$NON-NLS-1$
fProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor,1));
} else {
monitor.setTaskName(PreferencesMessages.getString("OptionsConfigurationBlock.buildall.taskname")); //$NON-NLS-1$
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor,1));
}
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= PreferencesMessages.getString("OptionsConfigurationBlock.builderror.title"); //$NON-NLS-1$
String message= PreferencesMessages.getString("OptionsConfigurationBlock.builderror.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
public void performDefaults() {
fWorkingValues= getDefaultOptions();
updateControls();
validateSettings(null, null);
}
protected void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= fComboBoxes.size() - 1; i >= 0; i--) {
Combo curr= (Combo) fComboBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.select(data.getSelection(currValue));
}
for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
Text curr= (Text) fTextBoxes.get(i);
String key= (String) curr.getData();
String currValue= (String) fWorkingValues.get(key);
curr.setText(currValue);
}
}
}
|
40,557 |
Bug 40557 quick fix: improve return type guessing
|
3.0 M2 class A { private boolean foo() { return f(1) || f(2); } } quich fix should be able to figure out that i want 'f' to be a boolean method
|
resolved fixed
|
4987a34
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T08:49:36Z | 2003-07-21T15:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/QuickFixTest.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.tests.quickfix;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.ui.text.java.IInvocationContext;
import org.eclipse.jdt.internal.ui.text.correction.AssistContext;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.correction.ProblemLocation;
/**
*/
public class QuickFixTest extends TestCase {
public static Test suite() {
TestSuite suite= new TestSuite();
suite.addTest(UnresolvedTypesQuickFixTest.allTests());
suite.addTest(UnresolvedVariablesQuickFixTest.allTests());
suite.addTest(UnresolvedMethodsQuickFixTest.allTests());
suite.addTest(ReturnTypeQuickFixTest.allTests());
suite.addTest(LocalCorrectionsQuickFixTest.allTests());
suite.addTest(ReorgQuickFixTest.allTests());
suite.addTest(ModifierCorrectionsQuickFixTest.allTests());
suite.addTest(AssistQuickFixTest.allTests());
suite.addTest(MarkerResolutionTest.allTests());
return new ProjectTestSetup(suite);
}
public QuickFixTest(String name) {
super(name);
}
public static void assertCorrectLabels(List proposals) {
for (int i= 0; i < proposals.size(); i++) {
ICompletionProposal proposal= (ICompletionProposal) proposals.get(i);
String name= proposal.getDisplayString();
if (name == null || name.length() == 0 || name.charAt(0) == '!' || name.indexOf('{') != -1) {
assertTrue("wrong proposal label: " + name, false);
}
if (proposal.getImage() == null) {
assertTrue("wrong proposal image", false);
}
}
}
public static void assertCorrectContext(IInvocationContext context, ProblemLocation problem) {
if (problem.getProblemId() != 0) {
assertTrue("Problem type not marked with lightbulb", JavaCorrectionProcessor.hasCorrections(context.getCompilationUnit(), problem.getProblemId()));
}
}
public static void assertNumberOf(String name, int nProblems, int nProblemsExpected) {
assertTrue("Wrong number of " + name + ", is: " + nProblems + ", expected: " + nProblemsExpected, nProblems == nProblemsExpected);
}
public static void assertEqualStringsIgnoreOrder(String[] str1, String[] str2) {
ArrayList list1= new ArrayList(Arrays.asList(str1));
ArrayList list2= new ArrayList(Arrays.asList(str2));
for (int i= list1.size() - 1; i >= 0; i--) {
if (list2.remove(list1.get(i))) {
list1.remove(i);
}
}
int n1= list1.size();
int n2= list2.size();
if (n1 + n2 > 0) {
if (n1 == 1 && n2 == 1) {
assertEqualString((String) list1.get(0), (String) list2.get(0));
}
StringBuffer buf= new StringBuffer();
buf.append("Content not as expected: Content is: \n");
for (int i= 0; i < n1; i++) {
String s1= (String) list1.get(i);
if (s1 != null) {
buf.append(s1);
buf.append("\n");
}
}
buf.append("Expected contents: \n");
for (int i= 0; i < n2; i++) {
String s2= (String) list2.get(i);
if (s2 != null) {
buf.append(s2);
buf.append("\n");
}
}
assertTrue(buf.toString(), false);
}
}
private static int getDiffPos(String str1, String str2) {
int len1= Math.min(str1.length(), str2.length());
int diffPos= -1;
for (int i= 0; i < len1; i++) {
if (str1.charAt(i) != str2.charAt(i)) {
diffPos= i;
break;
}
}
if (diffPos == -1 && str1.length() != str2.length()) {
diffPos= len1;
}
return diffPos;
}
private static final int printRange= 6;
public static void assertEqualString(String str1, String str2) {
int diffPos= getDiffPos(str1, str2);
if (diffPos != -1) {
int diffAhead= Math.max(0, diffPos - printRange);
int diffAfter= Math.min(str1.length(), diffPos + printRange);
String diffStr= str1.substring(diffAhead, diffPos) + '^' + str1.substring(diffPos, diffAfter);
assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + str2, false);
}
}
public static void assertEqualStringIgnoreDelim(String str1, String str2) throws IOException {
BufferedReader read1= new BufferedReader(new StringReader(str1));
BufferedReader read2= new BufferedReader(new StringReader(str2));
int line= 1;
do {
String s1= read1.readLine();
String s2= read2.readLine();
if (s1 == null || !s1.equals(s2)) {
if (s1 == null && s2 == null) {
return;
}
String diffStr= (s1 == null) ? s2 : s1;
assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at line " + line + ": " + diffStr + "\nexpected:\n" + str2, false);
}
line++;
} while (true);
}
public static TypeDeclaration findTypeDeclaration(CompilationUnit astRoot, String simpleTypeName) {
List types= astRoot.types();
for (int i= 0; i < types.size(); i++) {
TypeDeclaration elem= (TypeDeclaration) types.get(i);
if (simpleTypeName.equals(elem.getName().getIdentifier())) {
return elem;
}
}
return null;
}
public static MethodDeclaration findMethodDeclaration(TypeDeclaration typeDecl, String methodName) {
MethodDeclaration[] methods= typeDecl.getMethods();
for (int i= 0; i < methods.length; i++) {
if (methodName.equals(methods[i].getName().getIdentifier())) {
return methods[i];
}
}
return null;
}
public static VariableDeclarationFragment findFieldDeclaration(TypeDeclaration typeDecl, String fieldName) {
FieldDeclaration[] fields= typeDecl.getFields();
for (int i= 0; i < fields.length; i++) {
List list= fields[i].fragments();
for (int k= 0; k < list.size(); k++) {
VariableDeclarationFragment fragment= (VariableDeclarationFragment) list.get(k);
if (fieldName.equals(fragment.getName().getIdentifier())) {
return fragment;
}
}
}
return null;
}
public static AssistContext getCorrectionContext(ICompilationUnit cu, int offset, int length) {
AssistContext context= new AssistContext(cu, offset, length);
return context;
}
protected final ArrayList collectCorrections(ICompilationUnit cu, CompilationUnit astRoot) {
return collectCorrections(cu, astRoot, 1);
}
protected final ArrayList collectCorrections(ICompilationUnit cu, CompilationUnit astRoot, int nProblems) {
IProblem[] problems= astRoot.getProblems();
if (problems.length != nProblems) {
StringBuffer buf= new StringBuffer("Wrong number of problems, is: ");
buf.append(nProblems).append(", expected: ").append(nProblems).append('\n');
for (int i= 0; i < problems.length; i++) {
buf.append(problems[i].getMessage()).append('\n');
}
assertTrue(buf.toString(), false);
}
IProblem curr= problems[0];
int offset= curr.getSourceStart();
int length= curr.getSourceEnd() + 1 - offset;
ProblemLocation problem= new ProblemLocation(offset, length, curr.getID(), curr.getArguments());
AssistContext context= new AssistContext(cu, offset, length);
assertCorrectContext(context, problem);
ArrayList proposals= new ArrayList();
JavaCorrectionProcessor.collectCorrections(context, new ProblemLocation[] { problem }, proposals);
return proposals;
}
}
|
40,557 |
Bug 40557 quick fix: improve return type guessing
|
3.0 M2 class A { private boolean foo() { return f(1) || f(2); } } quich fix should be able to figure out that i want 'f' to be a boolean method
|
resolved fixed
|
4987a34
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T08:49:36Z | 2003-07-21T15:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedMethodsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.NewMethodCompletionProposal;
public class UnresolvedMethodsQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedMethodsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedMethodsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedMethodsQuickFixTest("testMethodInAnonymous2"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
fJProject1= ProjectTestSetup.getProject();
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testMethodInSameType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
private static final boolean bug_37381= true;
public void testMethodInForInit() throws Exception {
if (bug_37381) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(int i) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing0EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing1EmptyLine() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing2EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingComment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingNonJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInSameTypeUsingThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentClass() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(1, 2.1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("\n");
buf.append(" public boolean goo(int i, double d) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInAnonymous1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void xoo() {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" protected void xoo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" foo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testMethodInAnonymous2() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import other.A;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" A.xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public static void xoo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
assertEqualString(preview1, expected1);
}
public void testMethodInDifferentInterface() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(getClass());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("\n");
buf.append(" boolean goo(Class class1);\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testParameterMismatchCast() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo((int) (x + 1));\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(long l) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(long l) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchCast2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((float) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((int) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(float f, E e) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(float f, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x, o);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(null);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(0, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(Object object) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, 1, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, int j, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(int i, int j, X x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(String s, int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int x2) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(Collections.EMPTY_SET, 1, 2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(Set set, int i, int k) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(Set set, int i, int j) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchSwap() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(i - 1, new Object[] { o });\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(Object[] objects, int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o, int i) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" super.foo(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCanAssign() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Collection;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public class E {\n");
buf.append(" boolean bool;\n");
buf.append(" char c;\n");
buf.append(" byte b;\n");
buf.append(" short s;\n");
buf.append(" int i;\n");
buf.append(" long l;\n");
buf.append(" float f;\n");
buf.append(" double d;\n");
buf.append(" Object object;\n");
buf.append(" Vector vector;\n");
buf.append(" Cloneable cloneable;\n");
buf.append(" Collection collection;\n");
buf.append(" Serializable serializable;\n");
buf.append(" Object[] objectArr;\n");
buf.append(" int[] int_arr;\n");
buf.append(" long[] long_arr;\n");
buf.append(" Vector[] vector_arr;\n");
buf.append(" Collection[] collection_arr;\n");
buf.append(" Object[][] objectArrArr;\n");
buf.append(" Collection[][] collection_arrarr;\n");
buf.append(" Vector[][] vector_arrarr;\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
VariableDeclarationFragment bool= findFieldDeclaration(type, "bool");
VariableDeclarationFragment c= findFieldDeclaration(type, "c");
VariableDeclarationFragment b= findFieldDeclaration(type, "b");
VariableDeclarationFragment s= findFieldDeclaration(type, "s");
VariableDeclarationFragment i= findFieldDeclaration(type, "i");
VariableDeclarationFragment l= findFieldDeclaration(type, "l");
VariableDeclarationFragment f= findFieldDeclaration(type, "f");
VariableDeclarationFragment d= findFieldDeclaration(type, "d");
VariableDeclarationFragment object= findFieldDeclaration(type, "object");
VariableDeclarationFragment vector= findFieldDeclaration(type, "vector");
VariableDeclarationFragment cloneable= findFieldDeclaration(type, "cloneable");
VariableDeclarationFragment collection= findFieldDeclaration(type, "collection");
VariableDeclarationFragment serializable= findFieldDeclaration(type, "serializable");
VariableDeclarationFragment objectArr= findFieldDeclaration(type, "objectArr");
VariableDeclarationFragment int_arr= findFieldDeclaration(type, "int_arr");
VariableDeclarationFragment long_arr= findFieldDeclaration(type, "long_arr");
VariableDeclarationFragment vector_arr= findFieldDeclaration(type, "vector_arr");
VariableDeclarationFragment collection_arr= findFieldDeclaration(type, "collection_arr");
VariableDeclarationFragment objectArrArr= findFieldDeclaration(type, "objectArrArr");
VariableDeclarationFragment collection_arrarr= findFieldDeclaration(type, "collection_arrarr");
VariableDeclarationFragment vector_arrarr= findFieldDeclaration(type, "vector_arrarr");
VariableDeclarationFragment[] targets= new VariableDeclarationFragment[] {
bool, c, b, s, i, l, f, d, object, vector, cloneable, serializable, collection, objectArr, int_arr, long_arr,
vector_arr, collection_arr, objectArrArr, collection_arrarr, vector_arrarr
};
for (int k= 0; k < targets.length; k++) {
for (int n= 0; n < targets.length; n++) {
VariableDeclarationFragment f1= targets[k];
VariableDeclarationFragment f2= targets[n];
String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F extends E {\n");
buf.append(" void foo() {\n");
buf.append(" ").append(line).append(";\n");
buf.append(" }\n");
buf.append("}\n");
char[] content= buf.toString().toCharArray();
astRoot= AST.parseCompilationUnit(content, "F.java", cu1.getJavaProject());
problems= astRoot.getProblems();
ITypeBinding b1= f1.resolveBinding().getType();
assertNotNull(b1);
ITypeBinding b2= f2.resolveBinding().getType();
assertNotNull(b2);
boolean res= TypeRules.canAssign(b1, b2.getQualifiedName());
assertEquals(line, problems.length == 0, res);
boolean res2= TypeRules.canAssign(b1, b2);
assertEquals(line, problems.length == 0, res2);
}
}
}
}
|
40,557 |
Bug 40557 quick fix: improve return type guessing
|
3.0 M2 class A { private boolean foo() { return f(1) || f(2); } } quich fix should be able to figure out that i want 'f' to be a boolean method
|
resolved fixed
|
4987a34
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T08:49:36Z | 2003-07-21T15:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.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.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.dom.PrimitiveType.Code;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
public class ASTResolving {
public static ITypeBinding guessBindingForReference(ASTNode node) {
return Bindings.normalizeTypeBinding(getPossibleReferenceBinding(node));
}
private static ITypeBinding getPossibleReferenceBinding(ASTNode node) {
ASTNode parent= node.getParent();
switch (parent.getNodeType()) {
case ASTNode.ASSIGNMENT:
Assignment assignment= (Assignment) parent;
if (node.equals(assignment.getLeftHandSide())) {
// field write access: xx= expression
return assignment.getRightHandSide().resolveTypeBinding();
}
// read access
return assignment.getLeftHandSide().resolveTypeBinding();
case ASTNode.INFIX_EXPRESSION:
InfixExpression infix= (InfixExpression) parent;
if (node.equals(infix.getLeftOperand())) {
// xx == expression
return infix.getRightOperand().resolveTypeBinding();
}
// expression == xx
InfixExpression.Operator op= infix.getOperator();
if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED
|| op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) {
return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
return infix.getLeftOperand().resolveTypeBinding();
case ASTNode.INSTANCEOF_EXPRESSION:
InstanceofExpression instanceofExpression= (InstanceofExpression) parent;
return instanceofExpression.getRightOperand().resolveBinding();
case ASTNode.VARIABLE_DECLARATION_FRAGMENT:
VariableDeclarationFragment frag= (VariableDeclarationFragment) parent;
if (frag.getInitializer().equals(node)) {
return frag.getName().resolveTypeBinding();
}
break;
case ASTNode.SUPER_METHOD_INVOCATION:
SuperMethodInvocation superMethodInvocation= (SuperMethodInvocation) parent;
IMethodBinding superMethodBinding= ASTNodes.getMethodBinding(superMethodInvocation.getName());
if (superMethodBinding != null) {
return getParameterTypeBinding(node, superMethodInvocation.arguments(), superMethodBinding);
}
break;
case ASTNode.METHOD_INVOCATION:
MethodInvocation methodInvocation= (MethodInvocation) parent;
IMethodBinding methodBinding= ASTNodes.getMethodBinding(methodInvocation.getName());
if (methodBinding != null) {
return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding);
}
break;
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
SuperConstructorInvocation superInvocation= (SuperConstructorInvocation) parent;
IMethodBinding superBinding= superInvocation.resolveConstructorBinding();
if (superBinding != null) {
return getParameterTypeBinding(node, superInvocation.arguments(), superBinding);
}
break;
case ASTNode.CONSTRUCTOR_INVOCATION:
ConstructorInvocation constrInvocation= (ConstructorInvocation) parent;
IMethodBinding constrBinding= constrInvocation.resolveConstructorBinding();
if (constrBinding != null) {
return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding);
}
break;
case ASTNode.CLASS_INSTANCE_CREATION:
ClassInstanceCreation creation= (ClassInstanceCreation) parent;
IMethodBinding creationBinding= creation.resolveConstructorBinding();
if (creationBinding != null) {
return getParameterTypeBinding(node, creation.arguments(), creationBinding);
}
break;
case ASTNode.PARENTHESIZED_EXPRESSION:
return guessBindingForReference(parent);
case ASTNode.ARRAY_ACCESS:
if (((ArrayAccess) parent).getIndex().equals(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
} else {
return getPossibleReferenceBinding(parent);
}
case ASTNode.ARRAY_CREATION:
if (((ArrayCreation) parent).dimensions().contains(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.ARRAY_INITIALIZER:
ASTNode initializerParent= parent.getParent();
if (initializerParent instanceof ArrayCreation) {
return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding();
}
break;
case ASTNode.CONDITIONAL_EXPRESSION:
ConditionalExpression expression= (ConditionalExpression) parent;
if (node.equals(expression.getExpression())) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
if (node.equals(expression.getElseExpression())) {
return expression.getThenExpression().resolveTypeBinding();
}
return expression.getElseExpression().resolveTypeBinding();
case ASTNode.POSTFIX_EXPRESSION:
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
case ASTNode.PREFIX_EXPRESSION:
if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
case ASTNode.IF_STATEMENT:
case ASTNode.WHILE_STATEMENT:
case ASTNode.DO_STATEMENT:
if (node instanceof Expression) {
return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$
}
break;
case ASTNode.SWITCH_STATEMENT:
if (((SwitchStatement) parent).getExpression().equals(node)) {
return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$
}
break;
case ASTNode.RETURN_STATEMENT:
MethodDeclaration decl= findParentMethodDeclaration(parent);
if (decl != null) {
return decl.getReturnType().resolveBinding();
}
break;
case ASTNode.CAST_EXPRESSION:
return ((CastExpression) parent).getType().resolveBinding();
case ASTNode.THROW_STATEMENT:
case ASTNode.CATCH_CLAUSE:
return parent.getAST().resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$
case ASTNode.FIELD_ACCESS:
if (node.equals(((FieldAccess) parent).getName())) {
return getPossibleReferenceBinding(parent);
}
break;
case ASTNode.SUPER_FIELD_ACCESS:
return getPossibleReferenceBinding(parent);
case ASTNode.QUALIFIED_NAME:
if (node.equals(((QualifiedName) parent).getName())) {
return getPossibleReferenceBinding(parent);
}
break;
}
return null;
}
private static ITypeBinding getParameterTypeBinding(ASTNode node, List args, IMethodBinding binding) {
ITypeBinding[] paramTypes= binding.getParameterTypes();
int index= args.indexOf(node);
if (index >= 0 && index < paramTypes.length) {
return paramTypes[index];
}
return null;
}
public static ITypeBinding guessBindingForTypeReference(ASTNode node) {
return Bindings.normalizeTypeBinding(getPossibleTypeBinding(node));
}
private static ITypeBinding getPossibleTypeBinding(ASTNode node) {
ASTNode parent= node.getParent();
while (parent instanceof Type) {
parent= parent.getParent();
}
switch (parent.getNodeType()) {
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return guessVariableType(((VariableDeclarationStatement) parent).fragments());
case ASTNode.FIELD_DECLARATION:
return guessVariableType(((FieldDeclaration) parent).fragments());
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return guessVariableType(((VariableDeclarationExpression) parent).fragments());
case ASTNode.SINGLE_VARIABLE_DECLARATION:
SingleVariableDeclaration varDecl= (SingleVariableDeclaration) parent;
if (varDecl.getInitializer() != null) {
return varDecl.getInitializer().resolveTypeBinding();
}
break;
case ASTNode.ARRAY_CREATION:
ArrayCreation creation= (ArrayCreation) parent;
if (creation.getInitializer() != null) {
return creation.getInitializer().resolveTypeBinding();
}
return getPossibleReferenceBinding(parent);
case ASTNode.TYPE_LITERAL:
case ASTNode.CLASS_INSTANCE_CREATION:
return getPossibleReferenceBinding(parent);
}
return null;
}
private static ITypeBinding guessVariableType(List fragments) {
for (Iterator iter= fragments.iterator(); iter.hasNext();) {
VariableDeclarationFragment frag= (VariableDeclarationFragment) iter.next();
if (frag.getInitializer() != null) {
return frag.getInitializer().resolveTypeBinding();
}
}
return null;
}
public static MethodDeclaration findParentMethodDeclaration(ASTNode node) {
while ((node != null) && (node.getNodeType() != ASTNode.METHOD_DECLARATION)) {
node= node.getParent();
}
return (MethodDeclaration) node;
}
public static BodyDeclaration findParentBodyDeclaration(ASTNode node) {
while ((node != null) && (!(node instanceof BodyDeclaration))) {
node= node.getParent();
}
return (BodyDeclaration) node;
}
public static CompilationUnit findParentCompilationUnit(ASTNode node) {
return (CompilationUnit) findAncestor(node, ASTNode.COMPILATION_UNIT);
}
/**
* Returns either a TypeDeclaration or an AnonymousTypeDeclaration
* @param node
* @return CompilationUnit
*/
public static ASTNode findParentType(ASTNode node) {
while ((node != null) && (node.getNodeType() != ASTNode.TYPE_DECLARATION) && (node.getNodeType() != ASTNode.ANONYMOUS_CLASS_DECLARATION)) {
node= node.getParent();
}
return node;
}
public static ASTNode findAncestor(ASTNode node, int nodeType) {
while ((node != null) && (node.getNodeType() != nodeType)) {
node= node.getParent();
}
return node;
}
public static Statement findParentStatement(ASTNode node) {
while ((node != null) && (!(node instanceof Statement))) {
node= node.getParent();
if (node instanceof BodyDeclaration) {
return null;
}
}
return (Statement) node;
}
public static TryStatement findParentTryStatement(ASTNode node) {
while ((node != null) && (!(node instanceof TryStatement))) {
node= node.getParent();
if (node instanceof BodyDeclaration) {
return null;
}
}
return (TryStatement) node;
}
public static boolean isInStaticContext(ASTNode selectedNode) {
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methodDecl= (MethodDeclaration) decl;
if (methodDecl.isConstructor()) {
Statement statement= findParentStatement(selectedNode);
if (statement instanceof ConstructorInvocation || statement instanceof SuperConstructorInvocation) {
return true; // argument in a this or super call
}
}
return Modifier.isStatic(methodDecl.getModifiers());
} else if (decl instanceof Initializer) {
return Modifier.isStatic(((Initializer)decl).getModifiers());
} else if (decl instanceof FieldDeclaration) {
return Modifier.isStatic(((FieldDeclaration)decl).getModifiers());
}
return false;
}
public static Type getTypeFromTypeBinding(AST ast, ITypeBinding binding) {
if (binding.isArray()) {
int dim= binding.getDimensions();
return ast.newArrayType(getTypeFromTypeBinding(ast, binding.getElementType()), dim);
} else if (binding.isPrimitive()) {
String name= binding.getName();
return ast.newPrimitiveType(PrimitiveType.toCode(name));
} else if (!binding.isNullType() && !binding.isAnonymous()) {
return ast.newSimpleType(ast.newSimpleName(binding.getName()));
}
return null;
}
private static TypeDeclaration findTypeDeclaration(List decls, String name) {
for (Iterator iter= decls.iterator(); iter.hasNext();) {
ASTNode elem= (ASTNode) iter.next();
if (elem instanceof TypeDeclaration) {
TypeDeclaration decl= (TypeDeclaration) elem;
if (name.equals(decl.getName().getIdentifier())) {
return decl;
}
}
}
return null;
}
public static TypeDeclaration findTypeDeclaration(CompilationUnit root, ITypeBinding binding) {
ArrayList names= new ArrayList(5);
while (binding != null) {
names.add(binding.getName());
binding= binding.getDeclaringClass();
}
List types= root.types();
for (int i= names.size() - 1; i >= 0; i--) {
String name= (String) names.get(i);
TypeDeclaration decl= findTypeDeclaration(types, name);
if (decl == null || i == 0) {
return decl;
}
types= decl.bodyDeclarations();
}
return null;
}
public static String getFullName(Name name) {
return ASTNodes.asString(name);
}
public static String getQualifier(Name name) {
if (name.isQualifiedName()) {
return getFullName(((QualifiedName) name).getQualifier());
}
return ""; //$NON-NLS-1$
}
public static String getSimpleName(Name name) {
if (name.isQualifiedName()) {
return ((QualifiedName) name).getName().getIdentifier();
} else {
return ((SimpleName) name).getIdentifier();
}
}
public static ICompilationUnit findCompilationUnitForBinding(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding) throws JavaModelException {
if (binding != null && binding.isFromSource() && astRoot.findDeclaringNode(binding) == null) {
ICompilationUnit targetCU= Bindings.findCompilationUnit(binding, cu.getJavaProject());
if (targetCU != null) {
return JavaModelUtil.toWorkingCopy(targetCU);
}
return null;
}
return cu;
}
private static final Code[] CODE_ORDER= { PrimitiveType.CHAR, PrimitiveType.SHORT, PrimitiveType.INT, PrimitiveType.LONG, PrimitiveType.FLOAT, PrimitiveType.DOUBLE };
public static ITypeBinding[] getRelaxingTypes(AST ast, ITypeBinding type) {
HashSet res= new HashSet();
res.add(type);
if (type.isArray()) {
res.add(ast.resolveWellKnownType("java.lang.Object")); //$NON-NLS-1$
} else if (type.isPrimitive()) {
Code code= PrimitiveType.toCode(type.getName());
boolean found= false;
for (int i= 0; i < CODE_ORDER.length; i++) {
if (found) {
String typeName= CODE_ORDER[i].toString();
res.add(ast.resolveWellKnownType(typeName));
}
if (code == CODE_ORDER[i]) {
found= true;
}
}
} else {
collectRelaxingTypes(res, type);
}
return (ITypeBinding[]) res.toArray(new ITypeBinding[res.size()]);
}
private static void collectRelaxingTypes(Set res, ITypeBinding type) {
ITypeBinding[] interfaces= type.getInterfaces();
for (int i= 0; i < interfaces.length; i++) {
ITypeBinding curr= interfaces[i];
res.add(curr);
collectRelaxingTypes(res, curr);
}
ITypeBinding binding= type.getSuperclass();
if (binding != null) {
res.add(binding);
collectRelaxingTypes(res, binding);
}
}
}
|
40,547 |
Bug 40547 (3.0 M2) Export to .jar fails
|
When I select three different files within the same project but within different packages and try to "Export..." them, I get the following Exception in JarFileExportOperation.countSelectedElements(): java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:758) at org.eclipse.jdt.internal.ui.jarpackager.JarPackageWizard.executeExportOperation(JarPackageWizard.java:172) at org.eclipse.jdt.internal.ui.jarpackager.JarPackageWizard.performFinish(JarPackageWizard.java:146) at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:608) at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:321) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:423) 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:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.ui.actions.ExportResourcesAction.run(ExportResourcesAction.java:112) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.jarpackager.JarFileExportOperation.countSelectedElements(JarFileExportOperation.java:197) at org.eclipse.jdt.internal.ui.jarpackager.JarFileExportOperation.singleRun(JarFileExportOperation.java:736) at org.eclipse.jdt.internal.ui.jarpackager.JarFileExportOperation.execute(JarFileExportOperation.java:725) at org.eclipse.ui.actions.WorkspaceModifyOperation$1.run(WorkspaceModifyOperation.java:71) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1595) at org.eclipse.ui.actions.WorkspaceModifyOperation.run(WorkspaceModifyOperation.java:85) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:101)
|
resolved fixed
|
50c8ad6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T09:03:27Z | 2003-07-21T09:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.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.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.Manifest;
import java.util.zip.ZipException;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.operation.ModalContext;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModelMarker;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.jarpackager.IJarDescriptionWriter;
import org.eclipse.jdt.ui.jarpackager.IJarExportRunnable;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.ui.jarpackager.JarWriter;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation extends WorkspaceModifyOperation implements IJarExportRunnable {
private static class MessageMultiStatus extends MultiStatus {
MessageMultiStatus(String pluginId, int code, String message, Throwable exception) {
super(pluginId, code, message, exception);
}
/*
* allows to change the message
*/
protected void setMessage(String message) {
super.setMessage(message);
}
}
private JarWriter fJarWriter;
private JarPackageData fJarPackage;
private JarPackageData[] fJarPackages;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private Set fExportedClassContainers;
private MessageMultiStatus fStatus;
private StandardJavaElementContentProvider fJavaElementContentProvider;
/**
* Creates an instance of this class.
*
* @param jarPackage the JAR package specification
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData jarPackage, Shell parent) {
this(new JarPackageData[] {jarPackage}, parent);
}
/**
* Creates an instance of this class.
*
* @param jarPackages an array with JAR package data objects
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(JarPackageData[] jarPackages, Shell parent) {
this(parent);
fJarPackages= jarPackages;
}
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fStatus= new MessageMultiStatus(JavaPlugin.getPluginId(), IStatus.OK, "", null); //$NON-NLS-1$
fJavaElementContentProvider= new StandardJavaElementContentProvider();
}
protected void addToStatus(CoreException ex) {
IStatus status= ex.getStatus();
String message= ex.getLocalizedMessage();
if (message == null || message.length() < 1) {
message= JarPackagerMessages.getString("JarFileExportOperation.coreErrorDuringExport"); //$NON-NLS-1$
status= new Status(status.getSeverity(), status.getPlugin(), status.getCode(), message, ex);
}
fStatus.add(status);
}
/**
* Adds a new info to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addInfo(String message, Throwable error) {
fStatus.add(new Status(IStatus.INFO, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new warning to the list with the passed information.
* Normally the export operation continues after a warning.
* @param message the message
* @param exception the throwable that caused the warning, or <code>null</code>
*/
protected void addWarning(String message, Throwable error) {
fStatus.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Adds a new error to the list with the passed information.
* Normally an error terminates the export operation.
* @param message the message
* @param exception the throwable that caused the error, or <code>null</code>
*/
protected void addError(String message, Throwable error) {
fStatus.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
continue;
}
}
else
resource= (IResource)element;
if (resource.getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)resource);
}
return count;
}
private int getTotalChildCount(IContainer container) {
IResource[] members;
try {
members= container.members();
} catch (CoreException ex) {
return 0;
}
int count= 0;
for (int i= 0; i < members.length; i++) {
if (members[i].getType() == IResource.FILE)
count++;
else
count += getTotalChildCount((IContainer)members[i]);
}
return count;
}
/**
* Exports the passed resource to the JAR file
*
* @param element the resource or JavaElement to export
*/
protected void exportElement(Object element, IProgressMonitor progressMonitor) throws InterruptedException {
int leadSegmentsToRemove= 1;
IPackageFragmentRoot pkgRoot= null;
boolean isInJavaProject= false;
IResource resource= null;
IJavaProject jProject= null;
if (element instanceof IJavaElement) {
isInJavaProject= true;
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type != IJavaElement.CLASS_FILE && type != IJavaElement.COMPILATION_UNIT) {
exportJavaElement(progressMonitor, je);
return;
}
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return;
}
jProject= je.getJavaProject();
pkgRoot= JavaModelUtil.getPackageFragmentRoot(je);
}
else
resource= (IResource)element;
if (!resource.isAccessible()) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotFound", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
if (resource.getType() == IResource.FILE) {
if (!resource.isLocal(IResource.DEPTH_ZERO))
try {
resource.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceNotLocal", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (!isInJavaProject) {
// check if it's a Java resource
try {
isInJavaProject= resource.getProject().hasNature(JavaCore.NATURE_ID);
} catch (CoreException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.projectNatureNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
if (isInJavaProject) {
jProject= JavaCore.create(resource.getProject());
try {
IPackageFragment pkgFragment= jProject.findPackageFragment(resource.getFullPath().removeLastSegments(1));
if (pkgFragment != null)
pkgRoot= JavaModelUtil.getPackageFragmentRoot(pkgFragment);
else
pkgRoot= findPackageFragmentRoot(jProject, resource.getFullPath().removeLastSegments(1));
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.javaPackageNotDeterminable", resource.getFullPath()), ex); //$NON-NLS-1$
return;
}
}
}
if (pkgRoot != null) {
leadSegmentsToRemove= pkgRoot.getPath().segmentCount();
boolean isOnBuildPath;
isOnBuildPath= jProject.isOnClasspath(resource);
if (!isOnBuildPath || (mustUseSourceFolderHierarchy() && !pkgRoot.getElementName().equals(IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH)))
leadSegmentsToRemove--;
}
IPath destinationPath= resource.getFullPath().removeFirstSegments(leadSegmentsToRemove);
boolean isInOutputFolder= false;
if (isInJavaProject) {
try {
isInOutputFolder= jProject.getOutputLocation().isPrefixOf(resource.getFullPath());
} catch (JavaModelException ex) {
isInOutputFolder= false;
}
}
exportClassFiles(progressMonitor, pkgRoot, resource, jProject, destinationPath);
exportResource(progressMonitor, pkgRoot, isInJavaProject, resource, destinationPath, isInOutputFolder);
progressMonitor.worked(1);
ModalContext.checkCanceled(progressMonitor);
} else
exportContainer(progressMonitor, (IContainer)resource);
}
private void exportJavaElement(IProgressMonitor progressMonitor, IJavaElement je) throws java.lang.InterruptedException {
if (je.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT && ((IPackageFragmentRoot)je).isArchive())
return;
Object[] children= fJavaElementContentProvider.getChildren(je);
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportContainer(IProgressMonitor progressMonitor, IContainer container) throws java.lang.InterruptedException {
if (container.getType() == IResource.FOLDER && isOutputFolder((IFolder)container))
return;
IResource[] children= null;
try {
children= container.members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", container.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private IPackageFragmentRoot findPackageFragmentRoot(IJavaProject jProject, IPath path) throws JavaModelException {
if (jProject == null || path == null || path.segmentCount() <= 0)
return null;
IPackageFragmentRoot pkgRoot= jProject.findPackageFragmentRoot(path);
if (pkgRoot != null)
return pkgRoot;
else
return findPackageFragmentRoot(jProject, path.removeLastSegments(1));
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
// Handle case where META-INF/MANIFEST.MF is part of the exported files
if (fJarPackage.areClassFilesExported() && destinationPath.toString().equals("META-INF/MANIFEST.MF")) {//$NON-NLS-1$
if (fJarPackage.isManifestGenerated())
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.didNotAddManifestToJar", resource.getFullPath()), null); //$NON-NLS-1$
return;
}
boolean isNonJavaResource= !isInJavaProject || pkgRoot == null;
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == IPackageFragmentRoot.K_BINARY;
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.cantGetRootKind", resource.getFullPath()), ex); //$NON-NLS-1$
}
if ((fJarPackage.areClassFilesExported() &&
((isNonJavaResource || (pkgRoot != null && !isJavaFile(resource) && !isClassFile(resource)))
|| isInClassFolder && isClassFile(resource)))
|| (fJarPackage.areJavaFilesExported() && (isNonJavaResource || (pkgRoot != null && !isClassFile(resource))))) {
try {
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", destinationPath.toString())); //$NON-NLS-1$
fJarWriter.write((IFile) resource, destinationPath);
} catch (CoreException ex) {
Throwable realEx= ex.getStatus().getException();
if (realEx instanceof ZipException && realEx.getMessage() != null && realEx.getMessage().startsWith("duplicate entry:")) //$NON-NLS-1$
addWarning(ex.getMessage(), realEx);
else
addToStatus(ex);
}
}
}
private boolean isOutputFolder(IFolder folder) {
try {
IJavaProject javaProject= JavaCore.create(folder.getProject());
IPath outputFolderPath= javaProject.getOutputLocation();
return folder.getFullPath().equals(outputFolderPath);
} catch (JavaModelException ex) {
return false;
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
if (!jProject.isOnClasspath(resource))
return;
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, pkgRoot, progressMonitor);
IPath baseDestinationPath= destinationPath.removeLastSegments(1);
while (iter.hasNext()) {
IFile file= (IFile)iter.next();
if (!resource.isLocal(IResource.DEPTH_ZERO))
file.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
IPath classFilePath= baseDestinationPath.append(file.getName());
progressMonitor.subTask(JarPackagerMessages.getFormattedString("JarFileExportOperation.exporting", classFilePath.toString())); //$NON-NLS-1$
fJarWriter.write(file, classFilePath);
}
} catch (CoreException ex) {
addToStatus(ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
fExportedClassContainers= new HashSet(10);
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++)
exportElement(fJarPackage.getElements()[i], progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @return the iterator over the corresponding classpath files for the given file
* @deprecated As of 2.1 use the method with additional IPackageFragmentRoot paramter
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
return filesOnClasspath(file, pathInJar, javaProject, null, progressMonitor);
}
/**
* Returns an iterator on a list with files that correspond to the
* passed file and that are on the classpath of its project.
*
* @param file the file for which to find the corresponding classpath resources
* @param pathInJar the path that the file has in the JAR (i.e. project and source folder segments removed)
* @param javaProject the javaProject that contains the file
* @param pkgRoot the package fragment root that contains the file
* @return the iterator over the corresponding classpath files for the given file
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IPackageFragmentRoot pkgRoot, IProgressMonitor progressMonitor) throws CoreException {
// Allow JAR Package to provide its own strategy
IFile[] classFiles= fJarPackage.findClassfilesFor(file);
if (classFiles != null)
return Arrays.asList(classFiles).iterator();
if (!isJavaFile(file))
return Collections.EMPTY_LIST.iterator();
IPath outputPath= null;
if (pkgRoot != null) {
IClasspathEntry cpEntry= pkgRoot.getRawClasspathEntry();
if (cpEntry.getEntryKind() == IClasspathEntry.CPE_SOURCE)
outputPath= cpEntry.getOutputLocation();
}
if (outputPath == null)
// Use default output location
outputPath= javaProject.getOutputLocation();
IContainer outputContainer;
if (javaProject.getProject().getFullPath().equals(outputPath))
outputContainer= javaProject.getProject();
else {
outputContainer= createFolderHandle(outputPath);
if (outputContainer == null || !outputContainer.isAccessible()) {
String msg= JarPackagerMessages.getString("JarFileExportOperation.outputContainerNotAccessible"); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
// Java CU - search files with .class ending
boolean hasErrors= hasCompileErrors(file);
boolean hasWarnings= hasCompileWarnings(file);
boolean canBeExported= canBeExported(hasErrors, hasWarnings);
if (!canBeExported)
return Collections.EMPTY_LIST.iterator();
reportPossibleCompileProblems(file, hasErrors, hasWarnings, canBeExported);
IContainer classContainer= outputContainer;
if (pathInJar.segmentCount() > 1)
classContainer= outputContainer.getFolder(pathInJar.removeLastSegments(1));
if (fExportedClassContainers.contains(classContainer))
return Collections.EMPTY_LIST.iterator();
if (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
if (fJavaNameToClassFilesMap == null) {
// Could not fully build map. fallback is to export whole directory
IPath location= classContainer.getLocation();
String containerName= ""; //$NON-NLS-1$
if (location != null)
containerName= location.toFile().toString();
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.missingSourceFileAttributeExportedAll", containerName); //$NON-NLS-1$
addInfo(msg, null);
fExportedClassContainers.add(classContainer);
return getClassesIn(classContainer);
}
fClassFilesMapContainer= classContainer;
}
ArrayList classFileList= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFileList == null || classFileList.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFileList.iterator();
}
private Iterator getClassesIn(IContainer classContainer) throws CoreException {
IResource[] resources= classContainer.members();
List files= new ArrayList(resources.length);
for (int i= 0; i < resources.length; i++)
if (resources[i].getType() == IResource.FILE && isClassFile(resources[i]))
files.add(resources[i]);
return files.iterator();
}
/**
* Answers whether the given resource is a Java file.
* The resource must be a file whose file name ends with ".java".
*
* @return a <code>true<code> if the given resource is a Java file
*/
boolean isJavaFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("java"); //$NON-NLS-1$
}
/**
* Answers whether the given resource is a class file.
* The resource must be a file whose file name ends with ".class".
*
* @return a <code>true<code> if the given resource is a class file
*/
boolean isClassFile(IResource file) {
return file != null
&& file.getType() == IFile.FILE
&& file.getFileExtension() != null
&& file.getFileExtension().equalsIgnoreCase("class"); //$NON-NLS-1$
}
/*
* Builds and returns a map that has the class files
* for each java file in a given directory
*/
private Map buildJavaToClassMap(IContainer container) throws CoreException {
if (!isCompilerGeneratingSourceFileAttribute())
return null;
if (container == null || !container.isAccessible())
return new HashMap(0);
/*
* XXX: Bug 6584: Need a way to get class files for a java file (or CU)
*/
org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader cfReader= null;
IResource[] members= container.members();
Map map= new HashMap(members.length);
for (int i= 0; i < members.length; i++) {
if (isClassFile(members[i])) {
IFile classFile= (IFile)members[i];
IPath location= classFile.getLocation();
if (location != null) {
File file= location.toFile();
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(location.toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", file), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", file), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
/*
* Can't fully build the map because one or more
* class file does not contain the name of its
* source file.
*/
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", file), null); //$NON-NLS-1$
return null;
}
String javaName= new String(cfReader.sourceFileName());
Object classFiles= map.get(javaName);
if (classFiles == null) {
classFiles= new ArrayList(3);
map.put(javaName, classFiles);
}
((ArrayList)classFiles).add(classFile);
}
}
}
}
return map;
}
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a folder resource handle for the folder with the given workspace path.
*
* @param folderPath the path of the folder to create a handle for
* @return the new folder resource handle
*/
protected IFolder createFolderHandle(IPath folderPath) {
if (folderPath.isValidPath(folderPath.toString()) && folderPath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFolder(folderPath);
else
return null;
}
/**
* Returns the status of this operation.
* The result is a status object containing individual
* status objects.
*
* @return the status of this operation
*/
public IStatus getStatus() {
String message= null;
switch (fStatus.getSeverity()) {
case IStatus.OK:
message= ""; //$NON-NLS-1$
break;
case IStatus.INFO:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithInfo"); //$NON-NLS-1$
break;
case IStatus.WARNING:
message= JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"); //$NON-NLS-1$
break;
case IStatus.ERROR:
if (fJarPackages.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
break;
default:
// defensive code in case new severity is defined
message= ""; //$NON-NLS-1$
break;
}
fStatus.setMessage(message);
return fStatus;
}
/**
* Answer a boolean indicating whether the passed child is a descendant
* of one or more members of the passed resources collection
*
* @param resources a List contain potential parents
* @param child the resource to test
* @return a <code>boolean</code> indicating if the child is a descendant
*/
protected boolean isDescendant(List resources, IResource child) {
if (child.getType() == IResource.PROJECT)
return false;
IResource parent= child.getParent();
if (resources.contains(parent))
return true;
return isDescendant(resources, parent);
}
protected boolean canBeExported(boolean hasErrors, boolean hasWarnings) throws CoreException {
return (!hasErrors && !hasWarnings)
|| (hasErrors && fJarPackage.areErrorsExported())
|| (hasWarnings && fJarPackage.exportWarnings());
}
protected void reportPossibleCompileProblems(IFile file, boolean hasErrors, boolean hasWarnings, boolean canBeExported) {
if (hasErrors) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileErrors", file.getFullPath()), null); //$NON-NLS-1$
}
if (hasWarnings) {
if (canBeExported)
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.exportedWithCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
else
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.notExportedDueToCompileWarnings", file.getFullPath()), null); //$NON-NLS-1$
}
}
/**
* Exports the resources as specified by the JAR package.
*
* @param progressMonitor the progress monitor that displays the progress
* @see #getStatus()
*/
protected void execute(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
int count= fJarPackages.length;
progressMonitor.beginTask("", count); //$NON-NLS-1$
try {
for (int i= 0; i < count; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
fJarPackage= fJarPackages[i];
if (fJarPackage != null)
singleRun(subProgressMonitor);
}
} finally {
progressMonitor.done();
}
}
public void singleRun(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
try {
if (!preconditionsOK())
throw new InvocationTargetException(null, JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailedSeeDetails")); //$NON-NLS-1$
int totalWork= countSelectedElements();
if (!isAutoBuilding() && fJarPackage.isBuildingIfNeeded() && fJarPackage.areClassFilesExported()) {
int subMonitorTicks= totalWork/10;
totalWork += subMonitorTicks;
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, subMonitorTicks, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK);
buildProjects(subProgressMonitor);
} else
progressMonitor.beginTask("", totalWork); //$NON-NLS-1$
fJarWriter= fJarPackage.createJarWriter(fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (CoreException ex) {
addToStatus(ex);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (CoreException ex) {
addToStatus(ex);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getElements() == null || fJarPackage.getElements().length == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getAbsoluteJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
File targetFile= fJarPackage.getAbsoluteJarLocation().toFile();
if (targetFile.exists() && !targetFile.canWrite()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.jarFileExistsAndNotWritable"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isManifestAccessible()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.manifestDoesNotExist"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(new BusyIndicatorRunnableContext())) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidMainClass"), null); //$NON-NLS-1$
return false;
}
if (fParentShell == null)
// no checking if shell is null
return true;
IFile[] unsavedFiles= getUnsavedFiles();
if (unsavedFiles.length > 0)
return saveModifiedResourcesIfUserConfirms(unsavedFiles);
return true;
}
/**
* Returns the files which are not saved and which are
* part of the files being exported.
*
* @return an array of unsaved files
*/
private IFile[] getUnsavedFiles() {
IEditorPart[] dirtyEditors= getDirtyEditors(fParentShell);
Set unsavedFiles= new HashSet(dirtyEditors.length);
if (dirtyEditors.length > 0) {
List selection= JarPackagerUtil.asResources(fJarPackage.getElements());
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (JarPackagerUtil.contains(selection, dirtyFile)) {
unsavedFiles.add(dirtyFile);
}
}
}
}
return (IFile[])unsavedFiles.toArray(new IFile[unsavedFiles.size()]);
}
/**
* Asks the user to confirm to save the modified resources.
*
* @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= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
// Ask user to confirm saving of all files
final ConfirmSaveModifiedResourcesDialog dlg= new ConfirmSaveModifiedResourcesDialog(fParentShell, 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;
}
/**
* Asks to confirm to save the modified resources
* and save them if OK is pressed.
*
* @return true if user pressed OK and save was successful.
*/
private boolean saveModifiedResourcesIfUserConfirms(IFile[] dirtyFiles) {
if (confirmSaveModifiedResources(dirtyFiles))
return saveModifiedResources(dirtyFiles);
// Report unsaved files
for (int i= 0; i < dirtyFiles.length; i++)
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFiles[i].getFullPath()), null); //$NON-NLS-1$
return false;
}
/**
* Save all of the editors in the workbench.
*
* @return true if successful.
*/
private boolean saveModifiedResources(final IFile[] dirtyFiles) {
// Get display for further UI operations
Display display= fParentShell.getDisplay();
if (display == null || display.isDisposed())
return false;
final boolean[] retVal= new boolean[1];
Runnable runnable= new Runnable() {
public void run() {
try {
new ProgressMonitorDialog(fParentShell).run(false, false, createSaveModifiedResourcesRunnable(dirtyFiles));
retVal[0]= true;
} catch (InvocationTargetException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingModifiedResources"), ex); //$NON-NLS-1$
JavaPlugin.log(ex);
retVal[0]= false;
} catch (InterruptedException ex) {
Assert.isTrue(false); // Can't happen. Operation isn't cancelable.
retVal[0]= false;
}
}
};
display.syncExec(runnable);
return retVal[0];
}
private IRunnableWithProgress createSaveModifiedResourcesRunnable(final IFile[] dirtyFiles) {
return new IRunnableWithProgress() {
public void run(final IProgressMonitor pm) {
IEditorPart[] editorsToSave= getDirtyEditors(fParentShell);
pm.beginTask(JarPackagerMessages.getString("JarFileExportOperation.savingModifiedResources"), editorsToSave.length); //$NON-NLS-1$
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();
}
}
};
}
protected void saveFiles() {
// Save the manifest
if (fJarPackage.areClassFilesExported() && fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
try {
saveManifest();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingManifest"), ex); //$NON-NLS-1$
}
}
// Save the description
if (fJarPackage.isDescriptionSaved()) {
try {
saveDescription();
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorSavingDescription"), ex); //$NON-NLS-1$
}
}
}
private IEditorPart[] getDirtyEditors(Shell parent) {
Display display= parent.getDisplay();
final Object[] result= new Object[1];
display.syncExec(
new Runnable() {
public void run() {
result[0]= JavaPlugin.getDirtyEditors();
}
}
);
return (IEditorPart[])result[0];
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
IJarDescriptionWriter writer= fJarPackage.createJarDescriptionWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
writer.write(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
IFile descriptionFile= fJarPackage.getDescriptionFile();
if (descriptionFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, descriptionFile.getFullPath().toString()))
descriptionFile.setContents(fileInput, true, true, null);
} else
descriptionFile.create(fileInput, true, null);
} finally {
if (fileInput != null)
fileInput.close();
if (writer != null)
writer.close();
}
}
protected void saveManifest() throws CoreException, IOException {
ByteArrayOutputStream manifestOutput= new ByteArrayOutputStream();
ByteArrayInputStream fileInput= null;
try {
Manifest manifest= fJarPackage.getManifestProvider().create(fJarPackage);
manifest.write(manifestOutput);
fileInput= new ByteArrayInputStream(manifestOutput.toByteArray());
IFile manifestFile= fJarPackage.getManifestFile();
if (manifestFile.isAccessible()) {
if (fJarPackage.allowOverwrite() || JarPackagerUtil.askForOverwritePermission(fParentShell, manifestFile.getFullPath().toString()))
manifestFile.setContents(fileInput, true, true, null);
} else
manifestFile.create(fileInput, true, null);
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private boolean isCompilerGeneratingSourceFileAttribute() {
Object value= JavaCore.getOptions().get(JavaCore.COMPILER_SOURCE_FILE_ATTR);
if (value instanceof String)
return "generate".equalsIgnoreCase((String)value); //$NON-NLS-1$
else
return true; // default
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Object[] elements= fJarPackage.getElements();
for (int i= 0; i < elements.length; i++) {
IProject project= null;
Object element= elements[i];
if (element instanceof IResource)
project= ((IResource)element).getProject();
else if (element instanceof IJavaElement)
project= ((IJavaElement)element).getJavaProject().getProject();
if (project != null && !builtProjects.contains(project)) {
try {
project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, progressMonitor);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringProjectBuild", project.getFullPath()); //$NON-NLS-1$
addError(message, ex);
} finally {
// don't try to build same project a second time even if it failed
builtProjects.add(project);
}
}
}
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileErrors(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_ERROR)
return true;
}
return false;
}
/**
* Tells whether the given resource (or its children) have compile errors.
* The method acts on the current build state and does not recompile.
*
* @param resource the resource to check for errors
* @return <code>true</code> if the resource (and its children) are error free
* @throws import org.eclipse.core.runtime.CoreException if there's a marker problem
*/
private boolean hasCompileWarnings(IResource resource) throws CoreException {
IMarker[] problemMarkers= resource.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER, true, IResource.DEPTH_INFINITE);
for (int i= 0; i < problemMarkers.length; i++) {
if (problemMarkers[i].getAttribute(IMarker.SEVERITY, -1) == IMarker.SEVERITY_WARNING)
return true;
}
return false;
}
private boolean mustUseSourceFolderHierarchy() {
return fJarPackage.useSourceFolderHierarchy() && fJarPackage.areJavaFilesExported() && !fJarPackage.areClassFilesExported();
}
}
|
37,131 |
Bug 37131 [content assist] "Error accessing compilation unit" when using code assist for files not contained in a Java project
|
Steps to reproduce: 1) Set up a CVS repository connection. 2) Locate an existing Java project in the CVS repository. Right click on the HEAD branch of the project and choose "Check Out as Project". 3) Navigate to the Resource perspective and open a Java source file in the newly created project. In my project, all source files are found under the "src" subdirectory. 4) Navigate within the source file to any function. Start typing the following (slowly) to trigger the code assist functionality: System. 5) An error popup is shown. The title of the error window is "Error Accessing Compilation Unit", and the message shown in the error window is "Cannot access compilation unit. Reason: <project_name> does not exist." where "<project_name>" is the name of the checked out project in step 2. This message appears every time the code assist functionality is invoked, which makes it difficult to edit Java code in a CVS project.
|
resolved fixed
|
1aa1830
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T12:47:48Z | 2003-05-01T14:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProcessor.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.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationExtension;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.internal.corext.template.ContextType;
import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.text.JavaCodeReader;
import org.eclipse.jdt.internal.ui.text.template.TemplateEngine;
import org.eclipse.jdt.internal.ui.text.template.TemplateProposal;
/**
* Java completion processor.
*/
public class JavaCompletionProcessor implements IContentAssistProcessor {
private static class ContextInformationWrapper implements IContextInformation, IContextInformationExtension {
private final IContextInformation fContextInformation;
private int fPosition;
public ContextInformationWrapper(IContextInformation contextInformation) {
fContextInformation= contextInformation;
}
/*
* @see IContextInformation#getContextDisplayString()
*/
public String getContextDisplayString() {
return fContextInformation.getContextDisplayString();
}
/*
* @see IContextInformation#getImage()
*/
public Image getImage() {
return fContextInformation.getImage();
}
/*
* @see IContextInformation#getInformationDisplayString()
*/
public String getInformationDisplayString() {
return fContextInformation.getInformationDisplayString();
}
/*
* @see IContextInformationExtension#getContextInformationPosition()
*/
public int getContextInformationPosition() {
return fPosition;
}
public void setContextInformationPosition(int position) {
fPosition= position;
}
};
private final static String VISIBILITY= JavaCore.CODEASSIST_VISIBILITY_CHECK;
private final static String ENABLED= "enabled"; //$NON-NLS-1$
private final static String DISABLED= "disabled"; //$NON-NLS-1$
protected IWorkingCopyManager fManager;
private IEditorPart fEditor;
private ResultCollector fCollector;
private IContextInformationValidator fValidator;
private char[] fProposalAutoActivationSet;
private JavaCompletionProposalComparator fComparator;
private boolean fAllowAddImports;
private TemplateEngine fTemplateEngine;
private ExperimentalResultCollector fExperimentalCollector;
private int fNumberOfComputedResults= 0;
public JavaCompletionProcessor(IEditorPart editor) {
fEditor= editor;
fCollector= new ResultCollector();
fManager= JavaPlugin.getDefault().getWorkingCopyManager();
ContextType contextType= ContextTypeRegistry.getInstance().getContextType("java"); //$NON-NLS-1$
if (contextType != null)
fTemplateEngine= new TemplateEngine(contextType);
fExperimentalCollector= new ExperimentalResultCollector();
fAllowAddImports= true;
fComparator= new JavaCompletionProposalComparator();
}
/**
* Sets this processor's set of characters triggering the activation of the
* completion proposal computation.
*
* @param activationSet the activation set
*/
public void setCompletionProposalAutoActivationCharacters(char[] activationSet) {
fProposalAutoActivationSet= activationSet;
}
/**
* Tells this processor to restrict its proposal to those element
* visible in the actual invocation context.
*
* @param restrict <code>true</code> if proposals should be restricted
*/
public void restrictProposalsToVisibility(boolean restrict) {
Hashtable options= JavaCore.getOptions();
Object value= options.get(VISIBILITY);
if (value instanceof String) {
String newValue= restrict ? ENABLED : DISABLED;
if ( !newValue.equals((String) value)) {
options.put(VISIBILITY, newValue);
JavaCore.setOptions(options);
}
}
}
/**
* Tells this processor to order the proposals alphabetically.
*
* @param order <code>true</code> if proposals should be ordered.
*/
public void orderProposalsAlphabetically(boolean order) {
fComparator.setOrderAlphabetically(order);
}
/**
* Tells this processor to restrict is proposals to those
* starting with matching cases.
*
* @param restrict <code>true</code> if proposals should be restricted
*/
public void restrictProposalsToMatchingCases(boolean restrict) {
// not yet supported
}
/**
* Tells this processor to add import statement for proposals that have
* a fully qualified type name
*
* @param restrict <code>true</code> if import can be added
*/
public void allowAddingImports(boolean allowAddingImports) {
fAllowAddImports= allowAddingImports;
}
/**
* @see IContentAssistProcessor#getErrorMessage()
*/
public String getErrorMessage() {
if (fNumberOfComputedResults == 0) {
String errorMsg= fCollector.getErrorMessage();
if (errorMsg == null || errorMsg.trim().length() == 0)
errorMsg= JavaUIMessages.getString("JavaEditor.codeassist.noCompletions"); //$NON-NLS-1$
return errorMsg;
}
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES))
return fExperimentalCollector.getErrorMessage();
return fCollector.getErrorMessage();
}
/**
* @see IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator() {
if (fValidator == null)
fValidator= new JavaParameterListValidator();
return fValidator;
}
/**
* @see IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
/**
* @see IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters() {
return fProposalAutoActivationSet;
}
private boolean looksLikeMethod(JavaCodeReader reader) throws IOException {
int curr= reader.read();
while (curr != JavaCodeReader.EOF && Character.isWhitespace((char) curr))
curr= reader.read();
if (curr == JavaCodeReader.EOF)
return false;
return Character.isJavaIdentifierPart((char) curr) || Character.isJavaIdentifierStart((char) curr);
}
private int guessContextInformationPosition(ITextViewer viewer, int offset) {
int contextPosition= offset;
IDocument document= viewer.getDocument();
try {
JavaCodeReader reader= new JavaCodeReader();
reader.configureBackwardReader(document, offset, true, true);
int nestingLevel= 0;
int curr= reader.read();
while (curr != JavaCodeReader.EOF) {
if (')' == (char) curr)
++ nestingLevel;
else if ('(' == (char) curr) {
-- nestingLevel;
if (nestingLevel < 0) {
int start= reader.getOffset();
if (looksLikeMethod(reader))
return start + 1;
}
}
curr= reader.read();
}
} catch (IOException e) {
}
return contextPosition;
}
private List addContextInformations(ITextViewer viewer, int offset) {
ICompletionProposal[] proposals= internalComputeCompletionProposals(viewer, offset, -1);
List result= new ArrayList();
for (int i= 0; i < proposals.length; i++) {
IContextInformation contextInformation= proposals[i].getContextInformation();
if (contextInformation != null) {
ContextInformationWrapper wrapper= new ContextInformationWrapper(contextInformation);
wrapper.setContextInformationPosition(offset);
result.add(wrapper);
}
}
return result;
}
/**
* @see IContentAssistProcessor#computeContextInformation(ITextViewer, int)
*/
public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
int contextInformationPosition= guessContextInformationPosition(viewer, offset);
List result= addContextInformations(viewer, contextInformationPosition);
return (IContextInformation[]) result.toArray(new IContextInformation[result.size()]);
}
/**
* Order the given proposals.
*/
private ICompletionProposal[] order(ICompletionProposal[] proposals) {
Arrays.sort(proposals, fComparator);
return proposals;
}
/**
* @see IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)
*/
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
int contextInformationPosition= guessContextInformationPosition(viewer, offset);
return internalComputeCompletionProposals(viewer, offset, contextInformationPosition);
}
private ICompletionProposal[] internalComputeCompletionProposals(ITextViewer viewer, int offset, int contextOffset) {
ICompilationUnit unit= fManager.getWorkingCopy(fEditor.getEditorInput());
IJavaCompletionProposal[] results;
ResultCollector collector;
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES)) {
collector= fExperimentalCollector;
} else {
collector= fCollector;
}
try {
if (unit != null) {
collector.setPreventEating(false);
collector.reset(offset, contextOffset, unit.getJavaProject(), fAllowAddImports ? unit : null);
collector.setViewer(viewer);
Point selection= viewer.getSelectedRange();
if (selection.y > 0)
collector.setReplacementLength(selection.y);
unit.codeComplete(offset, collector);
}
} catch (JavaModelException x) {
Shell shell= viewer.getTextWidget().getShell();
ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$
}
results= collector.getResults();
if (fTemplateEngine != null) {
try {
fTemplateEngine.reset();
fTemplateEngine.complete(viewer, offset, unit);
} catch (JavaModelException x) {
Shell shell= viewer.getTextWidget().getShell();
ErrorDialog.openError(shell, JavaTextMessages.getString("CompletionProcessor.error.accessing.title"), JavaTextMessages.getString("CompletionProcessor.error.accessing.message"), x.getStatus()); //$NON-NLS-2$ //$NON-NLS-1$
}
TemplateProposal[] templateResults= fTemplateEngine.getResults();
// update relavance of template proposals that match with a keyword
JavaCompletionProposal[] keyWordResults= collector.getKeywordCompletions();
for (int i= 0; i < keyWordResults.length; i++) {
String keyword= keyWordResults[i].getReplacementString();
for (int k= 0; k < templateResults.length; k++) {
TemplateProposal curr= templateResults[k];
if (keyword.equals(curr.getTemplate().getName())) {
curr.setRelevance(keyWordResults[i].getRelevance());
}
}
}
// concatenate arrays
IJavaCompletionProposal[] total= new IJavaCompletionProposal[results.length + templateResults.length];
System.arraycopy(templateResults, 0, total, 0, templateResults.length);
System.arraycopy(results, 0, total, templateResults.length, results.length);
results= total;
}
fNumberOfComputedResults= (results == null ? 0 : results.length);
/*
* Order here and not in result collector to make sure that the order
* applies to all proposals and not just those of the compilation unit.
*/
return order(results);
}
}
|
34,124 |
Bug 34124 [implementation] Java outline viewer does not use element map
| null |
resolved fixed
|
fc5b65a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T12:54:18Z | 2003-03-07T18:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.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.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.Menu;
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.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.Assert;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.IPostSelectionProvider;
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.LabelProviderChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.model.WorkbenchAdapter;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.ProblemsLabelDecorator.ProblemsLabelChangedEvent;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.actions.AbstractToggleLinkingAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The content outline page of the Java editor. The viewer implements a proprietary
* update mechanism based on Java model deltas. It does not react on domain changes.
* It is specified to show the content of ICompilationUnits and IClassFiles.
* Pulishes its context menu under <code>JavaPlugin.getDefault().getPluginId() + ".outline"</code>.
*/
public class JavaOutlinePage extends Page implements IContentOutlinePage, IAdaptable , IPostSelectionProvider {
static Object[] NO_CHILDREN= new Object[0];
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
if (getControl() == null)
return;
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
ICompilationUnit cu= (ICompilationUnit) fInput;
IJavaElement base= cu;
if (fTopLevelTypeOnly) {
base= getMainType(cu);
if (base == null) {
if (fOutlineViewer != null)
fOutlineViewer.refresh(true);
return;
}
}
IJavaElementDelta delta= findElement(base, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(IJavaElement unit, IJavaElementDelta delta) {
if (delta == null || unit == null)
return null;
IJavaElement element= delta.getElement();
if (unit.equals(element))
return delta;
if (element.getElementType() > IJavaElement.CLASS_FILE)
return null;
IJavaElementDelta[] children= delta.getAffectedChildren();
if (children == null || children.length == 0)
return null;
for (int i= 0; i < children.length; i++) {
IJavaElementDelta d= findElement(unit, children[i]);
if (d != null)
return d;
}
return null;
}
};
static class NoClassElement extends WorkbenchAdapter implements IAdaptable {
/*
* @see java.lang.Object#toString()
*/
public String toString() {
return JavaEditorMessages.getString("JavaOutlinePage.error.NoTopLevelType"); //$NON-NLS-1$
}
/*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
*/
public Object getAdapter(Class clas) {
if (clas == IWorkbenchAdapter.class)
return this;
return null;
}
}
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private Object[] NO_CLASS= new Object[] {new NoClassElement()};
private ElementChangedListener fListener;
protected boolean matches(IJavaElement element) {
if (element.getElementType() == IJavaElement.METHOD) {
String name= element.getElementName();
return (name != null && name.indexOf('<') >= 0);
}
return false;
}
protected IJavaElement[] filter(IJavaElement[] children) {
boolean initializers= false;
for (int i= 0; i < children.length; i++) {
if (matches(children[i])) {
initializers= true;
break;
}
}
if (!initializers)
return children;
Vector v= new Vector();
for (int i= 0; i < children.length; i++) {
if (matches(children[i]))
continue;
v.addElement(children[i]);
}
IJavaElement[] result= new IJavaElement[v.size()];
v.copyInto(result);
return result;
}
public Object[] getChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
return filter(c.getChildren());
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return NO_CHILDREN;
}
public Object[] getElements(Object parent) {
if (fTopLevelTypeOnly) {
if (parent instanceof ICompilationUnit) {
try {
IType type= getMainType((ICompilationUnit) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
} else if (parent instanceof IClassFile) {
try {
IType type= getMainType((IClassFile) parent);
return type != null ? type.getChildren() : NO_CLASS;
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return getChildren(parent);
}
public Object getParent(Object child) {
if (child instanceof IJavaElement) {
IJavaElement e= (IJavaElement) child;
return e.getParent();
}
return null;
}
public boolean hasChildren(Object parent) {
if (parent instanceof IParent) {
IParent c= (IParent) parent;
try {
IJavaElement[] children= filter(c.getChildren());
return (children != null && children.length > 0);
} catch (JavaModelException x) {
JavaPlugin.log(x);
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
boolean isCU= (newInput instanceof ICompilationUnit);
if (isCU && fListener == null) {
fListener= new ElementChangedListener();
JavaCore.addElementChangedListener(fListener);
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
}
};
class JavaOutlineViewer extends TreeViewer {
/**
* Indicates an item which has been reused. At the point of
* its reuse it has been expanded. This field is used to
* communicate between <code>internalExpandToLevel</code> and
* <code>reuseTreeItem</code>.
*/
private Item fReusedExpandedItem;
private boolean fReorderedMembers;
public JavaOutlineViewer(Tree tree) {
super(tree);
setAutoExpandLevel(ALL_LEVELS);
}
/**
* Investigates the given element change event and if affected incrementally
* updates the outline.
*/
public void reconcile(IJavaElementDelta delta) {
fReorderedMembers= false;
if (getSorter() == null) {
if (fTopLevelTypeOnly
&& delta.getElement() instanceof IType
&& (delta.getKind() & IJavaElementDelta.ADDED) != 0)
{
refresh(true);
} else {
Widget w= findItem(fInput);
if (w != null && !w.isDisposed())
update(w, delta);
if (fReorderedMembers) {
refresh(false);
fReorderedMembers= false;
}
}
} else {
// just for now
refresh(true);
}
}
/*
* @see TreeViewer#internalExpandToLevel
*/
protected void internalExpandToLevel(Widget node, int level) {
if (node instanceof Item) {
Item i= (Item) node;
if (i.getData() instanceof IJavaElement) {
IJavaElement je= (IJavaElement) i.getData();
if (je.getElementType() == IJavaElement.IMPORT_CONTAINER || isInnerType(je)) {
if (i != fReusedExpandedItem) {
setExpanded(i, false);
return;
}
}
}
}
super.internalExpandToLevel(node, level);
}
protected void reuseTreeItem(Item item, Object element) {
// remove children
Item[] c= getChildren(item);
if (c != null && c.length > 0) {
if (getExpanded(item))
fReusedExpandedItem= item;
for (int k= 0; k < c.length; k++) {
if (c[k].getData() != null)
disassociate(c[k]);
c[k].dispose();
}
}
updateItem(item, element);
updatePlus(item, element);
internalExpandToLevel(item, ALL_LEVELS);
fReusedExpandedItem= null;
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return ((IMethod)element).isMainMethod();
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus());
}
}
return "main".equals(element.getElementName()); //$NON-NLS-1$
}
return false;
}
protected ISourceRange getSourceRange(IJavaElement element) throws JavaModelException {
if (element instanceof ISourceReference)
return ((ISourceReference) element).getSourceRange();
if (element instanceof IMember && !(element instanceof IInitializer))
return ((IMember) element).getNameRange();
return null;
}
protected boolean overlaps(ISourceRange range, int start, int end) {
return start <= (range.getOffset() + range.getLength() - 1) && range.getOffset() <= end;
}
protected boolean filtered(IJavaElement parent, IJavaElement child) {
Object[] result= new Object[] { child };
ViewerFilter[] filters= getFilters();
for (int i= 0; i < filters.length; i++) {
result= filters[i].filter(this, parent, result);
if (result.length == 0)
return true;
}
return false;
}
protected void update(Widget w, IJavaElementDelta delta) {
Item item;
IJavaElement parent= delta.getElement();
IJavaElementDelta[] affected= delta.getAffectedChildren();
Item[] children= getChildren(w);
boolean doUpdateParent= false;
boolean doUpdateParentsPlus= false;
Vector deletions= new Vector();
Vector additions= new Vector();
for (int i= 0; i < affected.length; i++) {
IJavaElementDelta affectedDelta= affected[i];
IJavaElement affectedElement= affectedDelta.getElement();
int status= affected[i].getKind();
// find tree item with affected element
int j;
for (j= 0; j < children.length; j++)
if (affectedElement.equals(children[j].getData()))
break;
if (j == children.length) {
// remove from collapsed parent
if ((status & IJavaElementDelta.REMOVED) != 0) {
doUpdateParentsPlus= true;
continue;
}
// addition
if ((status & IJavaElementDelta.CHANGED) != 0 &&
(affectedDelta.getFlags() & IJavaElementDelta.F_MODIFIERS) != 0 &&
!filtered(parent, affectedElement))
{
additions.addElement(affectedDelta);
}
continue;
}
item= children[j];
// removed
if ((status & IJavaElementDelta.REMOVED) != 0) {
deletions.addElement(item);
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
// changed
} else if ((status & IJavaElementDelta.CHANGED) != 0) {
int change= affectedDelta.getFlags();
doUpdateParent= doUpdateParent || mustUpdateParent(affectedDelta, affectedElement);
if ((change & IJavaElementDelta.F_MODIFIERS) != 0) {
if (filtered(parent, affectedElement))
deletions.addElement(item);
else
updateItem(item, affectedElement);
}
if ((change & IJavaElementDelta.F_CONTENT) != 0)
updateItem(item, affectedElement);
if ((change & IJavaElementDelta.F_CHILDREN) != 0)
update(item, affectedDelta);
if ((change & IJavaElementDelta.F_REORDER) != 0)
fReorderedMembers= true;
}
}
// find all elements to add
IJavaElementDelta[] add= delta.getAddedChildren();
if (additions.size() > 0) {
IJavaElementDelta[] tmp= new IJavaElementDelta[add.length + additions.size()];
System.arraycopy(add, 0, tmp, 0, add.length);
for (int i= 0; i < additions.size(); i++)
tmp[i + add.length]= (IJavaElementDelta) additions.elementAt(i);
add= tmp;
}
// add at the right position
go2: for (int i= 0; i < add.length; i++) {
try {
IJavaElement e= add[i].getElement();
if (filtered(parent, e))
continue go2;
doUpdateParent= doUpdateParent || mustUpdateParent(add[i], e);
ISourceRange rng= getSourceRange(e);
int start= rng.getOffset();
int end= start + rng.getLength() - 1;
Item last= null;
item= null;
children= getChildren(w);
for (int j= 0; j < children.length; j++) {
item= children[j];
IJavaElement r= (IJavaElement) item.getData();
if (r == null) {
// parent node collapsed and not be opened before -> do nothing
continue go2;
}
try {
rng= getSourceRange(r);
if (overlaps(rng, start, end)) {
// be tolerant if the delta is not correct, or if
// the tree has been updated other than by a delta
reuseTreeItem(item, e);
continue go2;
} else if (rng.getOffset() > start) {
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, (Object) e);
} else {
// nothing to reuse
createTreeItem(w, (Object) e, j);
}
continue go2;
}
} catch (JavaModelException x) {
// stumbled over deleted element
}
last= item;
}
// add at the end of the list
if (last != null && deletions.contains(last)) {
// reuse item
deletions.removeElement(last);
reuseTreeItem(last, e);
} else {
// nothing to reuse
createTreeItem(w, e, -1);
}
} catch (JavaModelException x) {
// the element to be added is not present -> don't add it
}
}
// remove items which haven't been reused
Enumeration e= deletions.elements();
while (e.hasMoreElements()) {
item= (Item) e.nextElement();
disassociate(item);
item.dispose();
}
if (doUpdateParent)
updateItem(w, delta.getElement());
if (!doUpdateParent && doUpdateParentsPlus && w instanceof Item)
updatePlus((Item)w, delta.getElement());
}
/*
* @see ContentViewer#handleLabelProviderChanged(LabelProviderChangedEvent)
*/
protected void handleLabelProviderChanged(LabelProviderChangedEvent event) {
Object input= getInput();
if (event instanceof ProblemsLabelChangedEvent) {
ProblemsLabelChangedEvent e= (ProblemsLabelChangedEvent) event;
if (e.isMarkerChange() && input instanceof ICompilationUnit) {
return; // marker changes can be ignored
}
}
// look if the underlying resource changed
Object[] changed= event.getElements();
if (changed != null) {
IResource resource= getUnderlyingResource();
if (resource != null) {
for (int i= 0; i < changed.length; i++) {
if (changed[i] != null && changed[i].equals(resource)) {
// change event to a full refresh
event= new LabelProviderChangedEvent((IBaseLabelProvider) event.getSource());
break;
}
}
}
}
super.handleLabelProviderChanged(event);
}
private IResource getUnderlyingResource() {
Object input= getInput();
if (input instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit) input;
if (cu.isWorkingCopy()) {
return cu.getOriginalElement().getResource();
} else {
return cu.getResource();
}
} else if (input instanceof IClassFile) {
return ((IClassFile) input).getResource();
}
return null;
}
};
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.LEXICAL_SORTING_OUTLINE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.Sort.description")); //$NON-NLS-1$
boolean checked= JavaPlugin.getDefault().getPreferenceStore().getBoolean("LexicalSortingAction.isChecked"); //$NON-NLS-1$
valueChanged(checked, false);
}
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.setSorter(on ? fSorter : null); }
});
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
};
class ClassOnlyAction extends Action {
public ClassOnlyAction() {
super();
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GO_INTO_TOP_LEVEL_TYPE_ACTION);
setText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("JavaOutlinePage.GoIntoTopLevelType.description")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "gointo_toplevel_type.gif"); //$NON-NLS-1$
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
boolean showclass= preferenceStore.getBoolean("GoIntoTopLevelTypeAction.isChecked"); //$NON-NLS-1$
setTopLevelTypeOnly(showclass);
}
/*
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
setTopLevelTypeOnly(!fTopLevelTypeOnly);
}
private void setTopLevelTypeOnly(boolean show) {
fTopLevelTypeOnly= show;
setChecked(show);
fOutlineViewer.refresh(false);
IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore();
preferenceStore.setValue("GoIntoTopLevelTypeAction.isChecked", show); //$NON-NLS-1$
}
};
/**
* This action toggles whether this Java Outline page links
* its selection to the active editor.
*
* @since 3.0
*/
public class ToggleLinkingAction extends AbstractToggleLinkingAction {
JavaOutlinePage fJavaOutlinePage;
/**
* Constructs a new action.
*/
public ToggleLinkingAction(JavaOutlinePage outlinePage) {
boolean isLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE);
setChecked(isLinkingEnabled);
fJavaOutlinePage= outlinePage;
}
/**
* Runs the action.
*/
public void run() {
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, isChecked());
}
}
/** A flag to show contents of top level type only */
private boolean fTopLevelTypeOnly;
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private ListenerList fPostSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private TogglePresentationAction fTogglePresentation;
private GotoErrorAction fPreviousError;
private GotoErrorAction fNextError;
private TextEditorAction fShowJavadoc;
private TextOperationAction fUndo;
private TextOperationAction fRedo;
private ToggleLinkingAction fToggleLinkingAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private IPropertyChangeListener fPropertyChangeListener;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
fTogglePresentation= new TogglePresentationAction();
fPreviousError= new GotoErrorAction("PreviousError.", false); //$NON-NLS-1$
fPreviousError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_PREV_ERROR);
fNextError= new GotoErrorAction("NextError.", true); //$NON-NLS-1$
fNextError.setImageDescriptor(JavaPluginImages.DESC_TOOL_GOTO_NEXT_ERROR);
fShowJavadoc= (TextEditorAction) fEditor.getAction("ShowJavaDoc"); //$NON-NLS-1$
fUndo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.UNDO);
fRedo= (TextOperationAction) fEditor.getAction(ITextEditorActionConstants.REDO);
fTogglePresentation.setEditor(editor);
fPreviousError.setEditor(editor);
fNextError.setEditor(editor);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
/**
* Returns the primary type of a compilation unit (has the same
* name as the compilation unit).
*
* @param compilationUnit the compilation unit
* @return returns the primary type of the compilation unit, or
* <code>null</code> if is does not have one
*/
protected 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
*/
protected IType getMainType(IClassFile classFile) {
try {
IType type= classFile.getType();
return type != null && type.exists() ? type : null;
} catch (JavaModelException e) {
return null;
}
}
/* (non-Javadoc)
* Method declared on Page
*/
public void init(IPageSite pageSite) {
super.init(pageSite);
}
private void doPropertyChange(PropertyChangeEvent event) {
if (fOutlineViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fOutlineViewer.refresh(false);
}
}
}
/*
* @see ISelectionProvider#addSelectionChangedListener(ISelectionChangedListener)
*/
public void addSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addSelectionChangedListener(listener);
else
fSelectionChangedListeners.add(listener);
}
/*
* @see ISelectionProvider#removeSelectionChangedListener(ISelectionChangedListener)
*/
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removeSelectionChangedListener(listener);
else
fSelectionChangedListeners.remove(listener);
}
/*
* @see ISelectionProvider#setSelection(ISelection)
*/
public void setSelection(ISelection selection) {
if (fOutlineViewer != null)
fOutlineViewer.setSelection(selection);
}
/*
* @see ISelectionProvider#getSelection()
*/
public ISelection getSelection() {
if (fOutlineViewer == null)
return StructuredSelection.EMPTY;
return fOutlineViewer.getSelection();
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#addPostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.addPostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.add(listener);
}
/*
* @see org.eclipse.jface.text.IPostSelectionProvider#removePostSelectionChangedListener(org.eclipse.jface.viewers.ISelectionChangedListener)
*/
public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
if (fOutlineViewer != null)
fOutlineViewer.removePostSelectionChangedListener(listener);
else
fPostSelectionChangedListeners.remove(listener);
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
toolBarManager.add(new ClassOnlyAction());
toolBarManager.add(new LexicalSortingAction());
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer"); //$NON-NLS-1$
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
fToggleLinkingAction= new ToggleLinkingAction(this);
toolBarManager.add(fToggleLinkingAction);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
AppearanceAwareLabelProvider lprovider= new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
fOutlineViewer= new JavaOutlineViewer(tree);
initDragAndDrop();
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingJavaLabelProvider(lprovider));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
listeners= fPostSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fPostSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addPostSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager m) {
contextMenuAboutToShow(m);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
IPageSite site= getSite();
site.registerContextMenu(JavaPlugin.getPluginId() + ".outline", manager, fOutlineViewer); //$NON-NLS-1$
site.setSelectionProvider(fOutlineViewer);
// we must create the groups after we have set the selection provider to the site
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
// register global actions
IActionBars bars= site.getActionBars();
bars.setGlobalActionHandler(ITextEditorActionConstants.UNDO, fUndo);
bars.setGlobalActionHandler(ITextEditorActionConstants.REDO, fRedo);
bars.setGlobalActionHandler(ITextEditorActionConstants.PREVIOUS, fPreviousError);
bars.setGlobalActionHandler(ITextEditorActionConstants.NEXT, fNextError);
bars.setGlobalActionHandler(JdtActionConstants.SHOW_JAVA_DOC, fShowJavadoc);
bars.setGlobalActionHandler(IJavaEditorActionConstants.TOGGLE_PRESENTATION, fTogglePresentation);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=18968
bars.setGlobalActionHandler(IJavaEditorActionConstants.PREVIOUS_ERROR, fPreviousError);
bars.setGlobalActionHandler(IJavaEditorActionConstants.NEXT_ERROR, fNextError);
fActionGroups.fillActionBars(bars);
IStatusLineManager statusLineManager= bars.getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addPostSelectionChangedListener(updater);
}
registerToolbarActions();
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyReleased(e);
}
});
}
public void dispose() {
if (fEditor == null)
return;
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
fEditor.outlinePageClosed();
fEditor= null;
fSelectionChangedListeners.clear();
fSelectionChangedListeners= null;
fPostSelectionChangedListeners.clear();
fPostSelectionChangedListeners= null;
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
fTogglePresentation.setEditor(null);
fPreviousError.setEditor(null);
fNextError.setEditor(null);
fOutlineViewer= null;
super.dispose();
}
public Control getControl() {
if (fOutlineViewer != null)
return fOutlineViewer.getControl();
return null;
}
public void setInput(IJavaElement inputElement) {
fInput= inputElement;
if (fOutlineViewer != null)
fOutlineViewer.setInput(fInput);
}
public void select(ISourceReference reference) {
if (fOutlineViewer != null) {
ISelection s= fOutlineViewer.getSelection();
if (s instanceof IStructuredSelection) {
IStructuredSelection ss= (IStructuredSelection) s;
List elements= ss.toList();
if (!elements.contains(reference)) {
s= (reference == null ? StructuredSelection.EMPTY : new StructuredSelection(reference));
fOutlineViewer.setSelection(s, true);
}
}
}
}
public void setAction(String actionID, IAction action) {
Assert.isNotNull(actionID);
if (action == null)
fActions.remove(actionID);
else
fActions.put(actionID, action);
}
public IAction getAction(String actionID) {
Assert.isNotNull(actionID);
return (IAction) fActions.get(actionID);
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES };
}
};
}
if (key == IShowInTarget.class) {
return getShowInTarget();
}
return null;
}
/**
* Convenience method to add the action installed under the given actionID to the
* specified group of the menu.
*/
protected void addAction(IMenuManager menu, String group, String actionID) {
IAction action= getAction(actionID);
if (action != null) {
if (action instanceof IUpdate)
((IUpdate) action).update();
if (action.isEnabled()) {
IMenuManager subMenu= menu.findMenuUsingPath(group);
if (subMenu != null)
subMenu.add(action);
else
menu.appendToGroup(group, action);
}
}
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection)getSelection();
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
}
/*
* @see Page#setFocus()
*/
public void setFocus() {
if (fOutlineViewer != null)
fOutlineViewer.getControl().setFocus();
}
/**
* Checkes whether a given Java element is an inner type.
*/
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;
}
/**
* Handles key events in viewer.
*/
private void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
}
if (action != null && action.isEnabled())
action.run();
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
/**
* Returns the <code>IShowInTarget</code> for this view.
*/
protected IShowInTarget getShowInTarget() {
return new IShowInTarget() {
public boolean show(ShowInContext context) {
ISelection sel= context.getSelection();
if (sel instanceof ITextSelection) {
ITextSelection tsel= (ITextSelection) sel;
int offset= tsel.getOffset();
IJavaElement element= fEditor.getElementAt(offset);
if (element != null) {
setSelection(new StructuredSelection(element));
return true;
}
}
return false;
}
};
}
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance()
};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fOutlineViewer)
};
fOutlineViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fOutlineViewer)
};
fOutlineViewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(fOutlineViewer, dragListeners));
}
}
|
40,347 |
Bug 40347 [misc] Renaming a project with an open editor fills log
|
I20030716+plugin-export 1) have a Java file open in the Java editor 2) rename the enclosing project -> exception in log but no stacktrace
|
resolved fixed
|
2e0502d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T16:06:43Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitDocumentProvider.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.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultLineTracker;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationModelEvent;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelListener;
import org.eclipse.jface.text.source.IAnnotationModelListenerExtension;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.editors.text.FileDocumentProvider;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.AbstractMarkerAnnotationModel;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceMarkerAnnotationModel;
import org.eclipse.jdt.core.IBufferFactory;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaModelStatusConstants;
import org.eclipse.jdt.core.IProblemRequestor;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
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.text.correction.JavaCorrectionProcessor;
import org.eclipse.jdt.internal.ui.text.java.IProblemRequestorExtension;
public class CompilationUnitDocumentProvider extends FileDocumentProvider {
/**
* Here for visibility issues only.
*/
protected class _FileSynchronizer extends FileSynchronizer {
public _FileSynchronizer(IFileEditorInput fileEditorInput) {
super(fileEditorInput);
}
};
/**
* Bundle of all required informations to allow working copy management.
*/
protected class CompilationUnitInfo extends FileInfo {
ICompilationUnit fCopy;
public CompilationUnitInfo(IDocument document, IAnnotationModel model, _FileSynchronizer fileSynchronizer, ICompilationUnit copy) {
super(document, model, fileSynchronizer);
fCopy= copy;
}
public void setModificationStamp(long timeStamp) {
fModificationStamp= timeStamp;
}
};
/**
* Annotation representating an <code>IProblem</code>.
*/
static protected class ProblemAnnotation extends Annotation implements IJavaAnnotation {
private static Image fgQuickFixImage;
private static Image fgQuickFixErrorImage;
private static boolean fgQuickFixImagesInitialized= false;
private ICompilationUnit fCompilationUnit;
private List fOverlaids;
private IProblem fProblem;
private Image fImage;
private boolean fQuickFixImagesInitialized= false;
private AnnotationType fType;
public ProblemAnnotation(IProblem problem, ICompilationUnit cu) {
fProblem= problem;
fCompilationUnit= cu;
setLayer(MarkerAnnotation.PROBLEM_LAYER + 1);
if (IProblem.Task == fProblem.getID())
fType= AnnotationType.TASK;
else if (fProblem.isWarning())
fType= AnnotationType.WARNING;
else
fType= AnnotationType.ERROR;
}
private void initializeImages() {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=18936
if (!fQuickFixImagesInitialized) {
if (indicateQuixFixableProblems() && JavaCorrectionProcessor.hasCorrections(this)) {
if (!fgQuickFixImagesInitialized) {
fgQuickFixImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_PROBLEM);
fgQuickFixErrorImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_FIXABLE_ERROR);
fgQuickFixImagesInitialized= true;
}
if (fType == AnnotationType.ERROR)
fImage= fgQuickFixErrorImage;
else
fImage= fgQuickFixImage;
}
fQuickFixImagesInitialized= true;
}
}
private boolean indicateQuixFixableProblems() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CORRECTION_INDICATION);
}
/*
* @see Annotation#paint
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
initializeImages();
if (fImage != null)
drawImage(fImage, gc, canvas, r, SWT.CENTER, SWT.TOP);
}
/*
* @see IJavaAnnotation#getImage(Display)
*/
public Image getImage(Display display) {
initializeImages();
return fImage;
}
/*
* @see IJavaAnnotation#getMessage()
*/
public String getMessage() {
return fProblem.getMessage();
}
/*
* @see IJavaAnnotation#isTemporary()
*/
public boolean isTemporary() {
return true;
}
/*
* @see IJavaAnnotation#getArguments()
*/
public String[] getArguments() {
return isProblem() ? fProblem.getArguments() : null;
}
/*
* @see IJavaAnnotation#getId()
*/
public int getId() {
return isProblem() ? fProblem.getID() : -1;
}
/*
* @see IJavaAnnotation#isProblem()
*/
public boolean isProblem() {
return fType == AnnotationType.WARNING || fType == AnnotationType.ERROR;
}
/*
* @see IJavaAnnotation#isRelevant()
*/
public boolean isRelevant() {
return true;
}
/*
* @see IJavaAnnotation#hasOverlay()
*/
public boolean hasOverlay() {
return false;
}
/*
* @see IJavaAnnotation#addOverlaid(IJavaAnnotation)
*/
public void addOverlaid(IJavaAnnotation annotation) {
if (fOverlaids == null)
fOverlaids= new ArrayList(1);
fOverlaids.add(annotation);
}
/*
* @see IJavaAnnotation#removeOverlaid(IJavaAnnotation)
*/
public void removeOverlaid(IJavaAnnotation annotation) {
if (fOverlaids != null) {
fOverlaids.remove(annotation);
if (fOverlaids.size() == 0)
fOverlaids= null;
}
}
/*
* @see IJavaAnnotation#getOverlaidIterator()
*/
public Iterator getOverlaidIterator() {
if (fOverlaids != null)
return fOverlaids.iterator();
return null;
}
public AnnotationType getAnnotationType() {
return fType;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.javaeditor.IJavaAnnotation#getCompilationUnit()
*/
public ICompilationUnit getCompilationUnit() {
return fCompilationUnit;
}
};
/**
* Internal structure for mapping positions to some value.
* The reason for this specific structure is that positions can
* change over time. Thus a lookup is based on value and not
* on hash value.
*/
protected static class ReverseMap {
static class Entry {
Position fPosition;
Object fValue;
};
private List fList= new ArrayList(2);
private int fAnchor= 0;
public ReverseMap() {
}
public Object get(Position position) {
Entry entry;
// behind anchor
int length= fList.size();
for (int i= fAnchor; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
// before anchor
for (int i= 0; i < fAnchor; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position)) {
fAnchor= i;
return entry.fValue;
}
}
return null;
}
private int getIndex(Position position) {
Entry entry;
int length= fList.size();
for (int i= 0; i < length; i++) {
entry= (Entry) fList.get(i);
if (entry.fPosition.equals(position))
return i;
}
return -1;
}
public void put(Position position, Object value) {
int index= getIndex(position);
if (index == -1) {
Entry entry= new Entry();
entry.fPosition= position;
entry.fValue= value;
fList.add(entry);
} else {
Entry entry= (Entry) fList.get(index);
entry.fValue= value;
}
}
public void remove(Position position) {
int index= getIndex(position);
if (index > -1)
fList.remove(index);
}
public void clear() {
fList.clear();
}
};
/**
* Annotation model dealing with java marker annotations and temporary problems.
* Also acts as problem requestor for its compilation unit. Initialiy inactive. Must explicitly be
* activated.
*/
protected class CompilationUnitAnnotationModel extends ResourceMarkerAnnotationModel implements IProblemRequestor, IProblemRequestorExtension {
private IFileEditorInput fInput;
private List fCollectedProblems;
private List fGeneratedAnnotations;
private IProgressMonitor fProgressMonitor;
private boolean fIsActive= false;
private ReverseMap fReverseMap= new ReverseMap();
private List fPreviouslyOverlaid= null;
private List fCurrentlyOverlaid= new ArrayList();
private CompilationUnitAnnotationModelEvent fCurrentEvent;
public CompilationUnitAnnotationModel(IFileEditorInput input) {
super(input.getFile());
fInput= input;
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
protected MarkerAnnotation createMarkerAnnotation(IMarker marker) {
return new JavaMarkerAnnotation(marker);
}
protected Position createPositionFromProblem(IProblem problem) {
int start= problem.getSourceStart();
if (start < 0)
return null;
int length= problem.getSourceEnd() - problem.getSourceStart() + 1;
if (length < 0)
return null;
return new Position(start, length);
}
protected void update(IMarkerDelta[] markerDeltas) {
super.update(markerDeltas);
if (markerDeltas != null && markerDeltas.length > 0) {
try {
ICompilationUnit workingCopy = getWorkingCopy(fInput);
if (workingCopy != null)
workingCopy.reconcile(true, null);
} catch (JavaModelException ex) {
handleCoreException(ex, ex.getMessage());
}
}
}
/*
* @see IProblemRequestor#beginReporting()
*/
public void beginReporting() {
ICompilationUnit unit= getWorkingCopy(fInput);
if (unit != null && unit.getJavaProject().isOnClasspath(unit))
fCollectedProblems= new ArrayList();
else
fCollectedProblems= null;
}
/*
* @see IProblemRequestor#acceptProblem(IProblem)
*/
public void acceptProblem(IProblem problem) {
if (isActive())
fCollectedProblems.add(problem);
}
/*
* @see IProblemRequestor#endReporting()
*/
public void endReporting() {
if (!isActive())
return;
if (fProgressMonitor != null && fProgressMonitor.isCanceled())
return;
boolean isCanceled= false;
boolean temporaryProblemsChanged= false;
synchronized (fAnnotations) {
fPreviouslyOverlaid= fCurrentlyOverlaid;
fCurrentlyOverlaid= new ArrayList();
if (fGeneratedAnnotations.size() > 0) {
temporaryProblemsChanged= true;
removeAnnotations(fGeneratedAnnotations, false, true);
fGeneratedAnnotations.clear();
}
if (fCollectedProblems != null && fCollectedProblems.size() > 0) {
ICompilationUnit cu= getWorkingCopy(fInput);
Iterator e= fCollectedProblems.iterator();
while (e.hasNext()) {
IProblem problem= (IProblem) e.next();
if (fProgressMonitor != null && fProgressMonitor.isCanceled()) {
isCanceled= true;
break;
}
Position position= createPositionFromProblem(problem);
if (position != null) {
ProblemAnnotation annotation= new ProblemAnnotation(problem, cu);
overlayMarkers(position, annotation);
fGeneratedAnnotations.add(annotation);
addAnnotation(annotation, position, false);
temporaryProblemsChanged= true;
}
}
fCollectedProblems.clear();
}
removeMarkerOverlays(isCanceled);
fPreviouslyOverlaid.clear();
fPreviouslyOverlaid= null;
}
if (temporaryProblemsChanged)
fireModelChanged();
}
private void removeMarkerOverlays(boolean isCanceled) {
if (isCanceled) {
fCurrentlyOverlaid.addAll(fPreviouslyOverlaid);
} else if (fPreviouslyOverlaid != null) {
Iterator e= fPreviouslyOverlaid.iterator();
while (e.hasNext()) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) e.next();
annotation.setOverlay(null);
}
}
}
/**
* Overlays value with problem annotation.
* @param problemAnnotation
*/
private void setOverlay(Object value, ProblemAnnotation problemAnnotation) {
if (value instanceof JavaMarkerAnnotation) {
JavaMarkerAnnotation annotation= (JavaMarkerAnnotation) value;
if (annotation.isProblem()) {
annotation.setOverlay(problemAnnotation);
fPreviouslyOverlaid.remove(annotation);
fCurrentlyOverlaid.add(annotation);
}
}
}
private void overlayMarkers(Position position, ProblemAnnotation problemAnnotation) {
Object value= getAnnotations(position);
if (value instanceof List) {
List list= (List) value;
for (Iterator e = list.iterator(); e.hasNext();)
setOverlay(e.next(), problemAnnotation);
} else {
setOverlay(value, problemAnnotation);
}
}
/**
* Tells this annotation model to collect temporary problems from now on.
*/
private void startCollectingProblems() {
fCollectedProblems= new ArrayList();
fGeneratedAnnotations= new ArrayList();
}
/**
* Tells this annotation model to no longer collect temporary problems.
*/
private void stopCollectingProblems() {
if (fGeneratedAnnotations != null) {
removeAnnotations(fGeneratedAnnotations, true, true);
fGeneratedAnnotations.clear();
}
fCollectedProblems= null;
fGeneratedAnnotations= null;
}
/*
* @see AnnotationModel#fireModelChanged()
*/
protected void fireModelChanged() {
fireModelChanged(fCurrentEvent);
fCurrentEvent= new CompilationUnitAnnotationModelEvent(this, getResource());
}
/*
* @see IProblemRequestor#isActive()
*/
public boolean isActive() {
return fIsActive && (fCollectedProblems != null);
}
/*
* @see IProblemRequestorExtension#setProgressMonitor(IProgressMonitor)
*/
public void setProgressMonitor(IProgressMonitor monitor) {
fProgressMonitor= monitor;
}
/*
* @see IProblemRequestorExtension#setIsActive(boolean)
*/
public void setIsActive(boolean isActive) {
if (fIsActive != isActive) {
fIsActive= isActive;
if (fIsActive)
startCollectingProblems();
else
stopCollectingProblems();
}
}
private Object getAnnotations(Position position) {
return fReverseMap.get(position);
}
/*
* @see AnnotationModel#addAnnotation(Annotation, Position, boolean)
*/
protected void addAnnotation(Annotation annotation, Position position, boolean fireModelChanged) {
fCurrentEvent.annotationAdded(annotation);
super.addAnnotation(annotation, position, fireModelChanged);
Object cached= fReverseMap.get(position);
if (cached == null)
fReverseMap.put(position, annotation);
else if (cached instanceof List) {
List list= (List) cached;
list.add(annotation);
} else if (cached instanceof Annotation) {
List list= new ArrayList(2);
list.add(cached);
list.add(annotation);
fReverseMap.put(position, list);
}
}
/*
* @see AnnotationModel#removeAllAnnotations(boolean)
*/
protected void removeAllAnnotations(boolean fireModelChanged) {
for (Iterator iter= getAnnotationIterator(); iter.hasNext();) {
fCurrentEvent.annotationRemoved((Annotation) iter.next());
}
super.removeAllAnnotations(fireModelChanged);
fReverseMap.clear();
}
/*
* @see AnnotationModel#removeAnnotation(Annotation, boolean)
*/
protected void removeAnnotation(Annotation annotation, boolean fireModelChanged) {
fCurrentEvent.annotationRemoved(annotation);
Position position= getPosition(annotation);
Object cached= fReverseMap.get(position);
if (cached instanceof List) {
List list= (List) cached;
list.remove(annotation);
if (list.size() == 1) {
fReverseMap.put(position, list.get(0));
list.clear();
}
} else if (cached instanceof Annotation) {
fReverseMap.remove(position);
}
super.removeAnnotation(annotation, fireModelChanged);
}
};
protected static class GlobalAnnotationModelListener implements IAnnotationModelListener, IAnnotationModelListenerExtension {
private ListenerList fListenerList;
public GlobalAnnotationModelListener() {
fListenerList= new ListenerList();
}
/**
* @see IAnnotationModelListener#modelChanged(IAnnotationModel)
*/
public void modelChanged(IAnnotationModel model) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
((IAnnotationModelListener) listeners[i]).modelChanged(model);
}
}
/**
* @see IAnnotationModelListenerExtension#modelChanged(AnnotationModelEvent)
*/
public void modelChanged(AnnotationModelEvent event) {
Object[] listeners= fListenerList.getListeners();
for (int i= 0; i < listeners.length; i++) {
Object curr= listeners[i];
if (curr instanceof IAnnotationModelListenerExtension) {
((IAnnotationModelListenerExtension) curr).modelChanged(event);
}
}
}
public void addListener(IAnnotationModelListener listener) {
fListenerList.add(listener);
}
public void removeListener(IAnnotationModelListener listener) {
fListenerList.remove(listener);
}
};
/**
* Document that can also be used by a background reconciler.
*/
protected static class PartiallySynchronizedDocument extends Document {
/*
* @see IDocumentExtension#startSequentialRewrite(boolean)
*/
synchronized public void startSequentialRewrite(boolean normalized) {
super.startSequentialRewrite(normalized);
}
/*
* @see IDocumentExtension#stopSequentialRewrite()
*/
synchronized public void stopSequentialRewrite() {
super.stopSequentialRewrite();
}
/*
* @see IDocument#get()
*/
synchronized public String get() {
return super.get();
}
/*
* @see IDocument#get(int, int)
*/
synchronized public String get(int offset, int length) throws BadLocationException {
return super.get(offset, length);
}
/*
* @see IDocument#getChar(int)
*/
synchronized public char getChar(int offset) throws BadLocationException {
return super.getChar(offset);
}
/*
* @see IDocument#replace(int, int, String)
*/
synchronized public void replace(int offset, int length, String text) throws BadLocationException {
super.replace(offset, length, text);
}
/*
* @see IDocument#set(String)
*/
synchronized public void set(String text) {
super.set(text);
}
};
/* Preference key for temporary problems */
private final static String HANDLE_TEMPORARY_PROBLEMS= PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS;
/** The buffer factory */
private IBufferFactory fBufferFactory= new CustomBufferFactory();
/** Indicates whether the save has been initialized by this provider */
private boolean fIsAboutToSave= false;
/** The save policy used by this provider */
private ISavePolicy fSavePolicy;
/** Internal property changed listener */
private IPropertyChangeListener fPropertyListener;
/** annotation model listener added to all created CU annotation models */
private GlobalAnnotationModelListener fGlobalAnnotationModelListener;
/**
* Constructor
*/
public CompilationUnitDocumentProvider() {
fPropertyListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (HANDLE_TEMPORARY_PROBLEMS.equals(event.getProperty()))
enableHandlingTemporaryProblems();
}
};
fGlobalAnnotationModelListener= new GlobalAnnotationModelListener();
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(fPropertyListener);
}
/**
* Sets the document provider's save policy.
*/
public void setSavePolicy(ISavePolicy savePolicy) {
fSavePolicy= savePolicy;
}
/**
* Creates a compilation unit from the given file.
*
* @param file the file from which to create the compilation unit
*/
protected ICompilationUnit createCompilationUnit(IFile file) {
Object element= JavaCore.create(file);
if (element instanceof ICompilationUnit)
return (ICompilationUnit) element;
return null;
}
/**
* Creates a line tracker working with the same line delimiters as the document
* of the given element. Assumes the element to be managed by this document provider.
*
* @param element the element serving as blue print
* @return a line tracker based on the same line delimiters as the element's document
*/
public ILineTracker createLineTracker(Object element) {
return new DefaultLineTracker();
}
/*
* @see AbstractDocumentProvider#createElementInfo(Object)
*/
protected ElementInfo createElementInfo(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
return super.createElementInfo(element);
IFileEditorInput input= (IFileEditorInput) element;
ICompilationUnit original= createCompilationUnit(input.getFile());
if (original != null) {
try {
try {
refreshFile(input.getFile());
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.createElementInfo")); //$NON-NLS-1$
}
IAnnotationModel m= createCompilationUnitAnnotationModel(input);
IProblemRequestor r= m instanceof IProblemRequestor ? (IProblemRequestor) m : null;
ICompilationUnit c= null;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
original.becomeWorkingCopy(r, getProgressMonitor());
c= original;
} else {
c= (ICompilationUnit) original.getSharedWorkingCopy(getProgressMonitor(), fBufferFactory, r);
}
DocumentAdapter a= null;
try {
a= (DocumentAdapter) c.getBuffer();
} catch (ClassCastException x) {
IStatus status= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IJavaStatusConstants.TEMPLATE_IO_EXCEPTION, "Shared working copy has wrong buffer", x); //$NON-NLS-1$
throw new CoreException(status);
}
_FileSynchronizer f= new _FileSynchronizer(input);
f.install();
CompilationUnitInfo info= new CompilationUnitInfo(a.getDocument(), m, f, c);
info.setModificationStamp(computeModificationStamp(input.getFile()));
info.fStatus= a.getStatus();
info.fEncoding= getPersistedEncoding(input);
if (r instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) r;
extension.setIsActive(isHandlingTemporaryProblems());
}
m.addAnnotationModelListener(fGlobalAnnotationModelListener);
return info;
} catch (JavaModelException x) {
throw new CoreException(x.getStatus());
}
} else {
return super.createElementInfo(element);
}
}
/*
* @see AbstractDocumentProvider#disposeElementInfo(Object, ElementInfo)
*/
protected void disposeElementInfo(Object element, ElementInfo info) {
if (info instanceof CompilationUnitInfo) {
CompilationUnitInfo cuInfo= (CompilationUnitInfo) info;
if (JavaPlugin.USE_WORKING_COPY_OWNERS) {
try {
cuInfo.fCopy.discardWorkingCopy();
} catch (JavaModelException x) {
handleCoreException(x, x.getMessage());
}
} else {
cuInfo.fCopy.destroy();
}
cuInfo.fModel.removeAnnotationModelListener(fGlobalAnnotationModelListener);
}
super.disposeElementInfo(element, info);
}
/*
* @see AbstractDocumentProvider#doSaveDocument(IProgressMonitor, Object, IDocument, boolean)
*/
protected void doSaveDocument(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
// update structure, assumes lock on info.fCopy
info.fCopy.reconcile();
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource == null) {
// underlying resource has been deleted, just recreate file, ignore the rest
super.doSaveDocument(monitor, element, document, overwrite);
return;
}
if (resource != null && !overwrite)
checkSynchronizationState(info.fModificationStamp, resource);
if (fSavePolicy != null)
fSavePolicy.preSave(info.fCopy);
// inform about the upcoming content change
fireElementStateChanging(element);
try {
fIsAboutToSave= true;
// commit working copy
if (JavaPlugin.USE_WORKING_COPY_OWNERS)
info.fCopy.commitWorkingCopy(overwrite, monitor);
else
info.fCopy.commit(overwrite, monitor);
} catch (CoreException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} catch (RuntimeException x) {
// inform about the failure
fireElementStateChangeFailed(element);
throw x;
} finally {
fIsAboutToSave= false;
}
// If here, the dirty state of the editor will change to "not dirty".
// Thus, the state changing flag will be reset.
AbstractMarkerAnnotationModel model= (AbstractMarkerAnnotationModel) info.fModel;
model.updateMarkers(info.fDocument);
if (resource != null)
info.setModificationStamp(computeModificationStamp(resource));
if (fSavePolicy != null) {
ICompilationUnit unit= fSavePolicy.postSave(original);
if (unit != null) {
IResource r= unit.getResource();
IMarker[] markers= r.findMarkers(IMarker.MARKER, true, IResource.DEPTH_ZERO);
if (markers != null && markers.length > 0) {
for (int i= 0; i < markers.length; i++)
model.updateMarker(markers[i], info.fDocument, null);
}
}
}
} else {
super.doSaveDocument(monitor, element, document, overwrite);
}
}
/**
* Replaces createAnnotionModel of the super class.
*/
protected IAnnotationModel createCompilationUnitAnnotationModel(Object element) throws CoreException {
if ( !(element instanceof IFileEditorInput))
throw new CoreException(JavaUIStatus.createError(
IJavaModelStatusConstants.INVALID_RESOURCE_TYPE, "", null)); //$NON-NLS-1$
IFileEditorInput input= (IFileEditorInput) element;
return new CompilationUnitAnnotationModel(input);
}
protected void initializeDocument(IDocument document) {
if (document != null) {
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
}
}
/*
* @see AbstractDocumentProvider#createDocument(Object)
*/
protected IDocument createDocument(Object element) throws CoreException {
if (element instanceof IEditorInput) {
Document document= new PartiallySynchronizedDocument();
if (setDocumentContent(document, (IEditorInput) element, getEncoding(element))) {
initializeDocument(document);
return document;
}
}
return null;
}
/*
* @see AbstractDocumentProvider#resetDocument(Object)
*/
public void resetDocument(Object element) throws CoreException {
if (element == null)
return;
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
IDocument document;
IStatus status= null;
try {
ICompilationUnit original= (ICompilationUnit) info.fCopy.getOriginalElement();
IResource resource= original.getResource();
if (resource instanceof IFile) {
IFile file= (IFile) resource;
try {
refreshFile(file);
} catch (CoreException x) {
handleCoreException(x, JavaEditorMessages.getString("CompilationUnitDocumentProvider.error.resetDocument")); //$NON-NLS-1$
}
IFileEditorInput input= new FileEditorInput(file);
document= super.createDocument(input);
} else {
document= new Document();
}
} catch (CoreException x) {
document= new Document();
status= x.getStatus();
}
fireElementContentAboutToBeReplaced(element);
removeUnchangedElementListeners(element, info);
info.fDocument.set(document.get());
info.fCanBeSaved= false;
info.fStatus= status;
addUnchangedElementListeners(element, info);
fireElementContentReplaced(element);
fireElementDirtyStateChanged(element, false);
} else {
super.resetDocument(element);
}
}
/**
* Saves the content of the given document to the given element.
* This is only performed when this provider initiated the save.
*
* @param monitor the progress monitor
* @param element the element to which to save
* @param document the document to save
* @param overwrite <code>true</code> if the save should be enforced
*/
public void saveDocumentContent(IProgressMonitor monitor, Object element, IDocument document, boolean overwrite) throws CoreException {
if (!fIsAboutToSave)
return;
if (element instanceof IFileEditorInput) {
IFileEditorInput input= (IFileEditorInput) element;
try {
String encoding= getEncoding(element);
if (encoding == null)
encoding= ResourcesPlugin.getEncoding();
InputStream stream= new ByteArrayInputStream(document.get().getBytes(encoding));
IFile file= input.getFile();
file.setContents(stream, overwrite, true, monitor);
} catch (IOException x) {
IStatus s= new Status(IStatus.ERROR, JavaUI.ID_PLUGIN, IStatus.OK, x.getMessage(), x);
throw new CoreException(s);
}
}
}
/**
* Returns the underlying resource for the given element.
*
* @param the element
* @return the underlying resource of the given element
*/
public IResource getUnderlyingResource(Object element) {
if (element instanceof IFileEditorInput) {
IFileEditorInput input= (IFileEditorInput) element;
return input.getFile();
}
return null;
}
/**
* Returns the working copy this document provider maintains for the given
* element.
*
* @param element the given element
* @return the working copy for the given element
*/
ICompilationUnit getWorkingCopy(IEditorInput element) {
ElementInfo elementInfo= getElementInfo(element);
if (elementInfo instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo) elementInfo;
return info.fCopy;
}
return null;
}
/**
* Gets the BufferFactory.
*/
public IBufferFactory getBufferFactory() {
return fBufferFactory;
}
/**
* Shuts down this document provider.
*/
public void shutdown() {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyListener);
Iterator e= getConnectedElements();
while (e.hasNext())
disconnect(e.next());
}
/**
* Returns the preference whether handling temporary problems is enabled.
*/
protected boolean isHandlingTemporaryProblems() {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
return store.getBoolean(HANDLE_TEMPORARY_PROBLEMS);
}
/**
* Switches the state of problem acceptance according to the value in the preference store.
*/
protected void enableHandlingTemporaryProblems() {
boolean enable= isHandlingTemporaryProblems();
for (Iterator iter= getConnectedElements(); iter.hasNext();) {
ElementInfo element= getElementInfo(iter.next());
if (element instanceof CompilationUnitInfo) {
CompilationUnitInfo info= (CompilationUnitInfo)element;
if (info.fModel instanceof IProblemRequestorExtension) {
IProblemRequestorExtension extension= (IProblemRequestorExtension) info.fModel;
extension.setIsActive(enable);
}
}
}
}
/**
* Adds a listener that reports changes from all compilation unit annotation models.
*/
public void addGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.addListener(listener);
}
/**
* Removes the listener.
*/
public void removeGlobalAnnotationModelListener(IAnnotationModelListener listener) {
fGlobalAnnotationModelListener.removeListener(listener);
}
/**
* Returns whether the given element is connected to this document provider.
*
* @param element the element
* @return <code>true</code> if the element is connected, <code>false</code> otherwise
*/
boolean isConnected(Object element) {
return getElementInfo(element) != null;
}
}
|
40,347 |
Bug 40347 [misc] Renaming a project with an open editor fills log
|
I20030716+plugin-export 1) have a Java file open in the Java editor 2) rename the enclosing project -> exception in log but no stacktrace
|
resolved fixed
|
2e0502d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T16:06:43Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IAutoEditStrategy;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ILineTracker;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.IWidgetTokenKeeper;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.WorkspaceModifyOperation;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.editors.text.IStorageDocumentProvider;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.ContentAssistAction;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup;
import org.eclipse.jdt.internal.ui.text.ContentAssistPreference;
import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant;
import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant;
import org.eclipse.jdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI;
import org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitFlags;
/**
* Java specific text editor.
*/
public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant {
/**
* Text operation code for requesting correction assist to show correction
* proposals for the current position.
*/
public static final int CORRECTIONASSIST_PROPOSALS= 50;
interface ITextConverter {
void customizeDocumentCommand(IDocument document, DocumentCommand command);
};
class AdaptedSourceViewer extends JavaSourceViewer {
private List fTextConverters;
private boolean fIgnoreTextConverters= false;
private JavaCorrectionAssistant fCorrectionAssistant;
public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) {
super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles);
}
public IContentAssistant getContentAssistant() {
return fContentAssistant;
}
/*
* @see ITextOperationTarget#doOperation(int)
*/
public void doOperation(int operation) {
if (getTextWidget() == null)
return;
switch (operation) {
case CONTENTASSIST_PROPOSALS:
String msg= fContentAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case CORRECTIONASSIST_PROPOSALS:
msg= fCorrectionAssistant.showPossibleCompletions();
setStatusLineErrorMessage(msg);
return;
case UNDO:
fIgnoreTextConverters= true;
break;
case REDO:
fIgnoreTextConverters= true;
break;
}
super.doOperation(operation);
}
/*
* @see ITextOperationTarget#canDoOperation(int)
*/
public boolean canDoOperation(int operation) {
if (operation == CORRECTIONASSIST_PROPOSALS)
return isEditable();
return super.canDoOperation(operation);
}
/*
* @see TextViewer#handleDispose()
*/
protected void handleDispose() {
if (fCorrectionAssistant != null) {
fCorrectionAssistant.uninstall();
fCorrectionAssistant= null;
}
super.handleDispose();
}
public void insertTextConverter(ITextConverter textConverter, int index) {
throw new UnsupportedOperationException();
}
public void addTextConverter(ITextConverter textConverter) {
if (fTextConverters == null) {
fTextConverters= new ArrayList(1);
fTextConverters.add(textConverter);
} else if (!fTextConverters.contains(textConverter))
fTextConverters.add(textConverter);
}
public void removeTextConverter(ITextConverter textConverter) {
if (fTextConverters != null) {
fTextConverters.remove(textConverter);
if (fTextConverters.size() == 0)
fTextConverters= null;
}
}
/*
* @see TextViewer#customizeDocumentCommand(DocumentCommand)
*/
protected void customizeDocumentCommand(DocumentCommand command) {
super.customizeDocumentCommand(command);
if (!fIgnoreTextConverters && fTextConverters != null) {
for (Iterator e = fTextConverters.iterator(); e.hasNext();)
((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command);
}
fIgnoreTextConverters= false;
}
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
public void updateIndentationPrefixes() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(this);
for (int i= 0; i < types.length; i++) {
String[] prefixes= configuration.getIndentPrefixes(this, types[i]);
if (prefixes != null && prefixes.length > 0)
setIndentPrefixes(prefixes, types[i]);
}
}
/*
* @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper)
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester);
}
/*
* @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int)
* @since 3.0
*/
public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) {
if (WorkbenchHelp.isContextHelpDisplayed())
return false;
return super.requestWidgetToken(requester, priority);
}
/*
* @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration)
*/
public void configure(SourceViewerConfiguration configuration) {
super.configure(configuration);
fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this);
fCorrectionAssistant.install(this);
IAutoEditStrategy smartSemi= new SmartSemicolonAutoEditStrategy();
prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE);
}
};
static class TabConverter implements ITextConverter {
private int fTabRatio;
private ILineTracker fLineTracker;
public TabConverter() {
}
public void setNumberOfSpacesPerTab(int ratio) {
fTabRatio= ratio;
}
public void setLineTracker(ILineTracker lineTracker) {
fLineTracker= lineTracker;
}
private int insertTabString(StringBuffer buffer, int offsetInLine) {
if (fTabRatio == 0)
return 0;
int remainder= offsetInLine % fTabRatio;
remainder= fTabRatio - remainder;
for (int i= 0; i < remainder; i++)
buffer.append(' ');
return remainder;
}
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
String text= command.text;
if (text == null)
return;
int index= text.indexOf('\t');
if (index > -1) {
StringBuffer buffer= new StringBuffer();
fLineTracker.set(command.text);
int lines= fLineTracker.getNumberOfLines();
try {
for (int i= 0; i < lines; i++) {
int offset= fLineTracker.getLineOffset(i);
int endOffset= offset + fLineTracker.getLineLength(i);
String line= text.substring(offset, endOffset);
int position= 0;
if (i == 0) {
IRegion firstLine= document.getLineInformationOfOffset(command.offset);
position= command.offset - firstLine.getOffset();
}
int length= line.length();
for (int j= 0; j < length; j++) {
char c= line.charAt(j);
if (c == '\t') {
position += insertTabString(buffer, position);
} else {
buffer.append(c);
++ position;
}
}
}
command.text= buffer.toString();
} catch (BadLocationException x) {
}
}
}
};
private class ExitPolicy implements LinkedPositionUI.ExitPolicy {
final char fExitCharacter;
final char fEscapeCharacter;
final Stack fStack;
final int fSize;
public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) {
fExitCharacter= exitCharacter;
fEscapeCharacter= escapeCharacter;
fStack= stack;
fSize= fStack.size();
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int)
*/
public ExitFlags doExit(LinkedPositionManager manager, VerifyEvent event, int offset, int length) {
if (event.character == fExitCharacter) {
if (fSize == fStack.size() && !isMasked(offset)) {
if (manager.anyPositionIncludes(offset, length))
return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false);
else
return new ExitFlags(LinkedPositionUI.COMMIT, true);
}
}
switch (event.character) {
case '\b': {
Position p= manager.getFirstPosition();
if (p.offset == offset && p.length == length)
return new ExitFlags(0, false);
else
return null;
}
case '\n':
case '\r':
return new ExitFlags(LinkedPositionUI.COMMIT, true);
case ';':
if (getInsertMode() == SMART_INSERT)
return new ExitFlags(LinkedPositionUI.COMMIT, true);
// else fall through
default:
return null;
}
}
private boolean isMasked(int offset) {
IDocument document= getSourceViewer().getDocument();
try {
return fEscapeCharacter == document.getChar(offset - 1);
} catch (BadLocationException e) {
}
return false;
}
};
private static class BracketLevel {
int fOffset;
int fLength;
LinkedPositionManager fManager;
LinkedPositionUI fEditor;
};
private class BracketInserter implements VerifyKeyListener, LinkedPositionUI.ExitListener {
private boolean fCloseBrackets= true;
private boolean fCloseStrings= true;
private Stack fBracketLevelStack= new Stack();
public void setCloseBracketsEnabled(boolean enabled) {
fCloseBrackets= enabled;
}
public void setCloseStringsEnabled(boolean enabled) {
fCloseStrings= enabled;
}
private boolean hasIdentifierToTheRight(IDocument document, int offset) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end));
} catch (BadLocationException e) {
// be conservative
return true;
}
}
private boolean hasIdentifierToTheLeft(IDocument document, int offset) {
try {
int start= offset;
IRegion startLine= document.getLineInformationOfOffset(start);
int minStart= startLine.getOffset();
while (start != minStart && Character.isWhitespace(document.getChar(start - 1)))
--start;
return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1));
} catch (BadLocationException e) {
return true;
}
}
private boolean hasCharacterToTheRight(IDocument document, int offset, char character) {
try {
int end= offset;
IRegion endLine= document.getLineInformationOfOffset(end);
int maxEnd= endLine.getOffset() + endLine.getLength();
while (end != maxEnd && Character.isWhitespace(document.getChar(end)))
++end;
return end != maxEnd && document.getChar(end) == character;
} catch (BadLocationException e) {
// be conservative
return true;
}
}
/*
* @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
if (!event.doit || getInsertMode() != SMART_INSERT)
return;
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
final Point selection= sourceViewer.getSelectedRange();
final int offset= selection.x;
final int length= selection.y;
switch (event.character) {
case '(':
if (hasCharacterToTheRight(document, offset + length, '('))
return;
// fall through
case '[':
if (!fCloseBrackets)
return;
if (hasIdentifierToTheRight(document, offset + length))
return;
// fall through
case '\'':
if (event.character == '\'') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
// fall through
case '"':
if (event.character == '"') {
if (!fCloseStrings)
return;
if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length))
return;
}
try {
ITypedRegion partition= document.getPartition(offset);
if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset)
return;
if (!validateEditorInputState())
return;
final char character= event.character;
final char closingCharacter= getPeerCharacter(character);
final StringBuffer buffer= new StringBuffer();
buffer.append(character);
buffer.append(closingCharacter);
document.replace(offset, length, buffer.toString());
BracketLevel level= new BracketLevel();
fBracketLevelStack.push(level);
level.fManager= new LinkedPositionManager(document, fBracketLevelStack.size() > 1);
level.fManager.addPosition(offset + 1, 0);
level.fOffset= offset;
level.fLength= 2;
level.fEditor= new LinkedPositionUI(sourceViewer, level.fManager);
level.fEditor.setCancelListener(this);
level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack));
level.fEditor.setFinalCaretOffset(offset + 2);
level.fEditor.enter();
IRegion newSelection= level.fEditor.getSelectedRegion();
sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength());
event.doit= false;
} catch (BadLocationException e) {
}
break;
}
}
/*
* @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitListener#exit(boolean)
*/
public void exit(boolean accept) {
BracketLevel level= (BracketLevel) fBracketLevelStack.pop();
if (accept)
return;
// remove brackets
try {
final ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
document.replace(level.fOffset, level.fLength, null);
} catch (BadLocationException e) {
}
}
};
/** Preference key for code formatter tab size */
private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE;
/** Preference key for inserting spaces rather than tabs */
private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS;
/** Preference key for automatically closing strings */
private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS;
/** Preference key for automatically closing brackets and parenthesis */
private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS;
/** The editor's save policy */
protected ISavePolicy fSavePolicy;
/** Listener to annotation model changes that updates the error tick in the tab image */
private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater;
/** The editor's tab converter */
private TabConverter fTabConverter;
/** The remembered java element */
private IJavaElement fRememberedElement;
/** The remembered selection */
private ITextSelection fRememberedSelection;
/** The remembered java element offset */
private int fRememberedElementOffset;
/** The bracket inserter. */
private BracketInserter fBracketInserter= new BracketInserter();
/** The standard action groups added to the menu */
private GenerateActionGroup fGenerateActionGroup;
private CompositeActionGroup fContextMenuGroup;
/**
* Creates a new compilation unit editor.
*/
public CompilationUnitEditor() {
super();
setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider());
setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$
setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$
setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$
// don't set help contextId, we install our own help context
fSavePolicy= null;
fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this);
}
/*
* @see AbstractTextEditor#createActions()
*/
protected void createActions() {
super.createActions();
Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS);
setAction("CorrectionAssistProposal", action); //$NON-NLS-1$
markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION);
action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS);
setAction("ContentAssistProposal", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.CONTENT_ASSIST_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION);
setAction("ContentAssistContextInformation", action); //$NON-NLS-1$
markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT);
setAction("Comment", action); //$NON-NLS-1$
markAsStateDependentAction("Comment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT);
setAction("Uncomment", action); //$NON-NLS-1$
markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT);
setAction("Format", action); //$NON-NLS-1$
markAsStateDependentAction("Format", true); //$NON-NLS-1$
markAsSelectionDependentAction("Format", true); //$NON-NLS-1$
WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION);
fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT);
fActionGroups.addGroup(rg);
fActionGroups.addGroup(fGenerateActionGroup);
// We have to keep the context menu group separate to have better control over positioning
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {
fGenerateActionGroup,
rg,
new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)});
}
/*
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementAt(int offset) {
return getElementAt(offset, true);
}
/**
* Returns the most narrow element including the given offset. If <code>reconcile</code>
* is <code>true</code> the editor's input element is reconciled in advance. If it is
* <code>false</code> this method only returns a result if the editor's input element
* does not need to be reconciled.
*
* @param offset the offset included by the retrieved element
* @param reconcile <code>true</code> if working copy should be reconciled
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
if (reconcile) {
synchronized (unit) {
unit.reconcile();
}
return unit.getElementAt(offset);
} else if (unit.isConsistent())
return unit.getElementAt(offset);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/*
* @see JavaEditor#getCorrespondingElement(IJavaElement)
*/
protected IJavaElement getCorrespondingElement(IJavaElement element) {
try {
return EditorUtility.getWorkingCopy(element, true);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
return null;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager)
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/*
* @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput)
*/
protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) {
if (page != null) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
page.setInput(manager.getWorkingCopy(input));
}
}
/*
* @see AbstractTextEditor#performSaveOperation(WorkspaceModifyOperation, IProgressMonitor)
*/
protected void performSaveOperation(WorkspaceModifyOperation operation, IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(fSavePolicy);
}
try {
super.performSaveOperation(operation, progressMonitor);
} finally {
if (p instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cp= (CompilationUnitDocumentProvider) p;
cp.setSavePolicy(null);
}
}
}
/*
* @see AbstractTextEditor#doSaveAs
*/
public void doSaveAs() {
if (askIfNonWorkbenchEncodingIsOk()) {
super.doSaveAs();
}
}
/*
* @see AbstractTextEditor#doSave(IProgressMonitor)
*/
public void doSave(IProgressMonitor progressMonitor) {
IDocumentProvider p= getDocumentProvider();
if (p == null) {
// editor has been closed
return;
}
if (!askIfNonWorkbenchEncodingIsOk()) {
progressMonitor.setCanceled(true);
return;
}
if (p.isDeleted(getEditorInput())) {
if (isSaveAsAllowed()) {
/*
* 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors.
* Changed Behavior to make sure that if called inside a regular save (because
* of deletion of input element) there is a way to report back to the caller.
*/
performSaveAs(progressMonitor);
} else {
/*
* 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there
* Missing resources.
*/
Shell shell= getSite().getShell();
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$
}
} else {
setStatusLineErrorMessage(null);
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
synchronized (unit) {
performSaveOperation(createSaveOperation(false), progressMonitor);
}
} else
performSaveOperation(createSaveOperation(false), progressMonitor);
}
}
/**
* Asks the user if it is ok to store in non-workbench encoding.
* @return <true> if the user wants to continue
*/
private boolean askIfNonWorkbenchEncodingIsOk() {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof IStorageDocumentProvider) {
IEditorInput input= getEditorInput();
IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider;
String encoding= storageProvider.getEncoding(input);
String defaultEncoding= storageProvider.getDefaultEncoding();
if (encoding != null && !encoding.equals(defaultEncoding)) {
Shell shell= getSite().getShell();
String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$
String msg;
if (input != null)
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$
else
msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$
return MessageDialog.openQuestion(shell, title, msg);
}
}
return true;
}
public boolean isSaveAsAllowed() {
return true;
}
/**
* The compilation unit editor implementation of this <code>AbstractTextEditor</code>
* method asks the user for the workspace path of a file resource and saves the document
* there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295
*/
protected void performSaveAs(IProgressMonitor progressMonitor) {
Shell shell= getSite().getShell();
IEditorInput input = getEditorInput();
SaveAsDialog dialog= new SaveAsDialog(shell);
IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null;
if (original != null)
dialog.setOriginalFile(original);
dialog.create();
IDocumentProvider provider= getDocumentProvider();
if (provider == null) {
// editor has been programmatically closed while the dialog was open
return;
}
if (provider.isDeleted(input) && original != null) {
String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$
dialog.setErrorMessage(null);
dialog.setMessage(message, IMessageProvider.WARNING);
}
if (dialog.open() == Dialog.CANCEL) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IPath filePath= dialog.getResult();
if (filePath == null) {
if (progressMonitor != null)
progressMonitor.setCanceled(true);
return;
}
IWorkspace workspace= ResourcesPlugin.getWorkspace();
IFile file= workspace.getRoot().getFile(filePath);
final IEditorInput newInput= new FileEditorInput(file);
WorkspaceModifyOperation op= new WorkspaceModifyOperation() {
public void execute(final IProgressMonitor monitor) throws CoreException {
getDocumentProvider().saveDocument(monitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true);
}
};
boolean success= false;
try {
provider.aboutToChange(newInput);
new ProgressMonitorDialog(shell).run(false, true, op);
success= true;
} catch (InterruptedException x) {
} catch (InvocationTargetException x) {
Throwable t= x.getTargetException();
if (t instanceof CoreException) {
CoreException cx= (CoreException) t;
ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), cx.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$
} else {
MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title3"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message3") + t.getMessage()); //$NON-NLS-1$ //$NON-NLS-2$
}
} finally {
provider.changed(newInput);
if (success)
setInput(newInput);
}
if (progressMonitor != null)
progressMonitor.setCanceled(!success);
}
/*
* @see AbstractTextEditor#doSetInput(IEditorInput)
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
configureTabConverter();
}
private void configureTabConverter() {
if (fTabConverter != null) {
IDocumentProvider provider= getDocumentProvider();
if (provider instanceof CompilationUnitDocumentProvider) {
CompilationUnitDocumentProvider cup= (CompilationUnitDocumentProvider) provider;
fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput()));
}
}
}
private int getTabSize() {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
return preferences.getInt(CODE_FORMATTER_TAB_SIZE);
}
private void startTabConversion() {
if (fTabConverter == null) {
fTabConverter= new TabConverter();
configureTabConverter();
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.addTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
}
}
private void stopTabConversion() {
if (fTabConverter != null) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
asv.removeTextConverter(fTabConverter);
// http://dev.eclipse.org/bugs/show_bug.cgi?id=19270
asv.updateIndentationPrefixes();
fTabConverter= null;
}
}
private boolean isTabConversionEnabled() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(SPACES_FOR_TABS);
}
public void dispose() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter);
if (fJavaEditorErrorTickUpdater != null) {
fJavaEditorErrorTickUpdater.dispose();
fJavaEditorErrorTickUpdater= null;
}
if (fActionGroups != null) {
fActionGroups.dispose();
fActionGroups= null;
}
super.dispose();
}
/*
* @see AbstractTextEditor#createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
if (isTabConversionEnabled())
startTabConversion();
IPreferenceStore preferenceStore= getPreferenceStore();
boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS);
boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS);
fBracketInserter.setCloseBracketsEnabled(closeBrackets);
fBracketInserter.setCloseStringsEnabled(closeStrings);
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension)
((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter);
}
private static char getEscapeCharacter(char character) {
switch (character) {
case '"':
case '\'':
return '\\';
default:
return 0;
}
}
private static char getPeerCharacter(char character) {
switch (character) {
case '(':
return ')';
case ')':
return '(';
case '[':
return ']';
case ']':
return '[';
case '"':
return character;
case '\'':
return character;
default:
throw new IllegalArgumentException();
}
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CLOSE_BRACKETS.equals(p)) {
fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p));
return;
}
if (CLOSE_STRINGS.equals(p)) {
fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p));
return;
}
if (SPACES_FOR_TABS.equals(p)) {
if (isTabConversionEnabled())
startTabConversion();
else
stopTabConversion();
return;
}
IContentAssistant c= asv.getContentAssistant();
if (c instanceof ContentAssistant)
ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event);
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent)
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer();
if (asv != null) {
String p= event.getProperty();
if (CODE_FORMATTER_TAB_SIZE.equals(p)) {
asv.updateIndentationPrefixes();
if (fTabConverter != null)
fTabConverter.setNumberOfSpacesPerTab(getTabSize());
}
}
super.handlePreferencePropertyChanged(event);
}
/*
* @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles);
}
/*
* @see IReconcilingParticipant#reconciled()
*/
public void reconciled() {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
Shell shell= getSite().getShell();
if (shell != null && !shell.isDisposed()) {
shell.getDisplay().asyncExec(new Runnable() {
public void run() {
synchronizeOutlinePageSelection();
}
});
}
}
}
protected void updateStateDependentActions() {
super.updateStateDependentActions();
fGenerateActionGroup.editorStateChanged();
}
/**
* Returns the updated java element for the old java element.
*/
private IJavaElement findElement(IJavaElement element) {
if (element == null)
return null;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(getEditorInput());
if (unit != null) {
try {
synchronized (unit) {
unit.reconcile();
}
IJavaElement[] findings= unit.findElements(element);
if (findings != null && findings.length > 0)
return findings[0];
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
// nothing found, be tolerant and go on
}
}
return null;
}
/**
* Returns the offset of the given Java element.
*/
private int getOffset(IJavaElement element) {
if (element instanceof ISourceReference) {
ISourceReference sr= (ISourceReference) element;
try {
ISourceRange srcRange= sr.getSourceRange();
if (srcRange != null)
return srcRange.getOffset();
} catch (JavaModelException e) {
}
}
return -1;
}
/*
* @see AbstractTextEditor#rememberSelection()
*/
protected void rememberSelection() {
ISelectionProvider sp= getSelectionProvider();
fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection());
if (fRememberedSelection != null) {
fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true);
fRememberedElementOffset= getOffset(fRememberedElement);
}
}
/*
* @see AbstractTextEditor#restoreSelection()
*/
protected void restoreSelection() {
try {
if (getSourceViewer() == null || fRememberedSelection == null)
return;
IJavaElement newElement= findElement(fRememberedElement);
int newOffset= getOffset(newElement);
int delta= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0;
if (isValidSelection(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength()))
selectAndReveal(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength());
} finally {
fRememberedSelection= null;
fRememberedElement= null;
fRememberedElementOffset= -1;
}
}
private boolean isValidSelection(int offset, int length) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null) {
int end= offset + length;
int documentLength= document.getLength();
return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength;
}
}
return false;
}
/*
* @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput)
*/
protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) {
String oldExtension= ""; //$NON-NLS-1$
if (originalElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) originalElement).getFile();
if (file != null) {
String ext= file.getFileExtension();
if (ext != null)
oldExtension= ext;
}
}
String newExtension= ""; //$NON-NLS-1$
if (movedElement instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput) movedElement).getFile();
if (file != null)
newExtension= file.getFileExtension();
}
return oldExtension.equals(newExtension);
}
}
|
40,605 |
Bug 40605 Unnecessary cast not detected anymore
|
In 3.0M2 this was detected, but not in I20030722 anymore. public void foo(String s) { int r = ((Object) s).hashCode(); }
|
resolved wontfix
|
bb3b91b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-22T16:48:31Z | 2003-07-22T16:06:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (false) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testIndirectStaticAccess2"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fJProject1= ProjectTestSetup.getProject();
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testThisAccessToStaticField() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" E.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" Thread th= foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 0);
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionToSurroundingTry() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws ParseException {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (ParseException e1) {\n");
buf.append(" }\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testUncaughtExceptionOnSuper1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnSuper2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A() throws Exception {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() throws Exception {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) throws IOException {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public F(int i, Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(int i, Runnable runnable) {\n");
buf.append(" super(i, runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) throws IOException {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testNotVisibleConstructorInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private F() {\n");
buf.append(" }\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnhandledExceptionInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F() throws IOException{\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E() throws IOException {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount, fColor= fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount= 0;\n");
buf.append(" public void foo() {\n");
buf.append(" fCount= 1 + 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" boolean res= process();\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] i, j= new Object[0];\n");
buf.append(" i= j = null;\n");
buf.append(" i= (new Object[] { null, null });\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] j= new Object[0];\n");
buf.append(" j = null;\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int j= 0, i= 0; i < 3; i++) {\n");
buf.append(" j= i;\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int i= 0; i < 3; i++) {\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedParam() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo(Object str) {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateMethod() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append(" \n");
buf.append(" private void foo() {\n");
buf.append(" fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateConstructor() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" private E(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateType() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private class F {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = (int) i;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = i;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int r = ((Object) s).hashCode();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int r = s.hashCode();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast3() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = ((int) 1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = (1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testSuperfluousSemicolon() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s= 1;;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s= 1;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append(" public static final int CONST=1;\n");
buf.append("}\n");
other.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends other.A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public int foo(B b) {\n");
buf.append(" return B.CONST;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import other.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public int foo(B b) {\n");
buf.append(" return A.CONST;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append(" public static int foo() {\n");
buf.append(" return 1;\n");
buf.append(" }\n");
buf.append("}\n");
other.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends other.A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int foo() {\n");
buf.append(" return pack.B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import other.A;\n");
buf.append("\n");
buf.append("public class E {\n");
buf.append(" public int foo() {\n");
buf.append(" return A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
40,634 |
Bug 40634 new project - java - location, gives xerces211 does not exist
|
When doing file->new->java project->location x->next, I received a message which said something about an error and to check the log. Here is the entry from the log. !ENTRY org.eclipse.jdt.ui 4 10001 Jul 22, 2003 16:59:29.47 !MESSAGE Internal Error !STACK 1 Java Model Exception: Java Model Status [xerces211 does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException(JavaElement.java:437) at org.eclipse.jdt.internal.core.JavaModelManager.getPerProjectInfoCheckExistence(JavaModelManager.java:848) at org.eclipse.jdt.internal.core.JavaProject.getPerProjectInfo(JavaProject.java:1544) at org.eclipse.jdt.internal.core.JavaProject.getResolvedClasspath(JavaProject.java:1635) at org.eclipse.jdt.internal.core.JavaProject.getResolvedClasspath(JavaProject.java:1621) at org.eclipse.jdt.internal.core.JavaProject.buildStructure(JavaProject.java:217) at org.eclipse.jdt.internal.core.Openable.generateInfos(Openable.java:198) at org.eclipse.jdt.internal.core.JavaElement.openWhenClosed(JavaElement.java:448) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:269) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo(JavaElement.java:255) at org.eclipse.jdt.internal.core.JavaProject.getJavaProjectElementInfo(JavaProject.java:1282) at org.eclipse.jdt.internal.core.JavaProject.getNameLookup(JavaProject.java:1290) at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:1004) at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:988) at org.eclipse.jdt.internal.core.CompilationUnit.reconcile(CompilationUnit.java:981) at org.eclipse.jdt.internal.ui.wizards.ClassPathDetector.visitCompilationUnit(ClassPathDetector.java:216) at org.eclipse.jdt.internal.ui.wizards.ClassPathDetector.visit(ClassPathDetector.java:273) at org.eclipse.core.internal.resources.Resource$1.visitElement(Resource.java:50) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:76) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:80) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:80) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:80) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:80) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:80) at org.eclipse.core.internal.watson.ElementTreeIterator.doIteration(ElementTreeIterator.java:80) at org.eclipse.core.internal.watson.ElementTreeIterator.iterate(ElementTreeIterator.java:119) at org.eclipse.core.internal.resources.Resource.accept(Resource.java:60) at org.eclipse.jdt.internal.ui.wizards.ClassPathDetector.<init>(ClassPathDetector.java:62) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizardPage.updateProject(NewProjectCreationWizardPage.java:124) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizardPage$1.run(NewProjectCreationWizardPage.java:86) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:758) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizardPage.changeToNewProject(NewProjectCreationWizardPage.java:94) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizardPage.setVisible(NewProjectCreationWizardPage.java:64) at org.eclipse.jface.wizard.WizardDialog.updateForPage(WizardDialog.java:959) at org.eclipse.jface.wizard.WizardDialog.access$1(WizardDialog.java:940) at org.eclipse.jface.wizard.WizardDialog$3.run(WizardDialog.java:929) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.wizard.WizardDialog.showPage(WizardDialog.java:927) at org.eclipse.jface.wizard.WizardDialog.nextPressed(WizardDialog.java:684) at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:316) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:423) 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:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.ui.actions.NewProjectAction.run(NewProjectAction.java:107) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583) !ENTRY org.eclipse.jdt.core 4 969 Jul 22, 2003 16:59:29.62 !MESSAGE xerces211 does not exist.
|
verified fixed
|
e80cb3f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-23T13:31:32Z | 2003-07-23T00:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ISourceAttribute;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
*/
public class ClassPathDetector implements IResourceProxyVisitor {
private HashMap fSourceFolders;
private List fClassFiles;
private HashSet fJARFiles;
private IProject fProject;
private IPath fResultOutputFolder;
private IClasspathEntry[] fResultClasspath;
public ClassPathDetector(IProject project) throws CoreException {
fSourceFolders= new HashMap();
fJARFiles= new HashSet(10);
fClassFiles= new ArrayList(100);
fProject= project;
project.accept(this, IResource.NONE);
fResultClasspath= null;
fResultOutputFolder= null;
detectClasspath();
}
private boolean isNested(IPath path, Iterator iter) {
while (iter.hasNext()) {
IPath other= (IPath) iter.next();
if (other.isPrefixOf(path)) {
return true;
}
}
return false;
}
/**
* Method detectClasspath.
*/
private void detectClasspath() {
ArrayList cpEntries= new ArrayList();
detectSourceFolders(cpEntries);
IPath outputLocation= detectOutputFolder(cpEntries);
detectLibraries(cpEntries, outputLocation);
if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
return;
}
IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
for (int i= 0; i < jreEntries.length; i++) {
cpEntries.add(jreEntries[i]);
}
IClasspathEntry[] entries= (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
return;
}
fResultClasspath= entries;
fResultOutputFolder= outputLocation;
}
private IPath findInSourceFolders(IPath path) {
Iterator iter= fSourceFolders.keySet().iterator();
while (iter.hasNext()) {
Object key= iter.next();
List cus= (List) fSourceFolders.get(key);
if (cus.contains(path)) {
return (IPath) key;
}
}
return null;
}
private IPath detectOutputFolder(List entries) {
HashSet classFolders= new HashSet();
for (Iterator iter= fClassFiles.iterator(); iter.hasNext();) {
IFile file= (IFile) iter.next();
IPath location= file.getLocation();
if (location == null) {
continue;
}
IClassFileReader reader= ToolFactory.createDefaultClassFileReader(location.toOSString(), IClassFileReader.CLASSFILE_ATTRIBUTES);
if (reader == null) {
continue; // problematic class file
}
char[] className= reader.getClassName();
ISourceAttribute sourceAttribute= reader.getSourceFileAttribute();
if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
IPath packPath= file.getParent().getFullPath();
int idx= CharOperation.lastIndexOf('/', className) + 1;
IPath relPath= new Path(new String(className, 0, idx));
IPath cuPath= relPath.append(new String(sourceAttribute.getSourceFileName()));
IPath resPath= null;
if (idx == 0) {
resPath= packPath;
} else {
IPath folderPath= getFolderPath(packPath, relPath);
if (folderPath != null) {
resPath= folderPath;
}
}
if (resPath != null) {
IPath path= findInSourceFolders(cuPath);
if (path != null) {
return resPath;
} else {
classFolders.add(resPath);
}
}
}
}
IPath projPath= fProject.getFullPath();
if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
return projPath;
} else {
IPath path= projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
while (classFolders.contains(path)) {
path= new Path(path.toString() + '1');
}
return path;
}
}
private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {
Set sourceFolderSet= fSourceFolders.keySet();
for (Iterator iter= fJARFiles.iterator(); iter.hasNext();) {
IPath path= (IPath) iter.next();
if (isNested(path, sourceFolderSet.iterator())) {
continue;
}
if (outputLocation != null && outputLocation.isPrefixOf(path)) {
continue;
}
IClasspathEntry entry= JavaCore.newLibraryEntry(path, null, null);
cpEntries.add(entry);
}
}
private void detectSourceFolders(ArrayList resEntries) {
Set sourceFolderSet= fSourceFolders.keySet();
for (Iterator iter= sourceFolderSet.iterator(); iter.hasNext();) {
IPath path= (IPath) iter.next();
ArrayList excluded= new ArrayList();
for (Iterator inner= sourceFolderSet.iterator(); inner.hasNext();) {
IPath other= (IPath) inner.next();
if (!path.equals(other) && path.isPrefixOf(other)) {
IPath pathToExclude= other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
excluded.add(pathToExclude);
}
}
IPath[] excludedPaths= (IPath[]) excluded.toArray(new IPath[excluded.size()]);
IClasspathEntry entry= JavaCore.newSourceEntry(path, excludedPaths);
resEntries.add(entry);
}
}
private void visitCompilationUnit(IFile file) throws JavaModelException {
ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
if (cu != null) {
ICompilationUnit workingCopy= null;
try {
workingCopy= (ICompilationUnit) cu.getWorkingCopy();
synchronized(workingCopy) {
workingCopy.reconcile();
}
IPath packPath= file.getParent().getFullPath();
IPackageDeclaration[] decls= workingCopy.getPackageDeclarations();
String cuName= file.getName();
if (decls.length == 0) {
addToMap(fSourceFolders, packPath, new Path(cuName));
} else {
IPath relpath= new Path(decls[0].getElementName().replace('.', '/'));
IPath folderPath= getFolderPath(packPath, relpath);
if (folderPath != null) {
addToMap(fSourceFolders, folderPath, relpath.append(cuName));
}
}
} finally {
if (workingCopy != null) {
workingCopy.destroy();
}
}
}
}
private void addToMap(HashMap map, IPath folderPath, IPath relPath) {
List list= (List) map.get(folderPath);
if (list == null) {
list= new ArrayList(50);
map.put(folderPath, list);
}
list.add(relPath);
}
private IPath getFolderPath(IPath packPath, IPath relpath) {
int remainingSegments= packPath.segmentCount() - relpath.segmentCount();
if (remainingSegments >= 0) {
IPath common= packPath.removeFirstSegments(remainingSegments);
if (common.equals(relpath)) {
return packPath.uptoSegment(remainingSegments);
}
}
return null;
}
private boolean hasExtension(String name, String ext) {
return name.endsWith(ext) && (ext.length() != name.length());
}
private boolean isValidCUName(String name) {
return !JavaConventions.validateCompilationUnitName(name).matches(IStatus.ERROR);
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
*/
public boolean visit(IResourceProxy proxy) throws CoreException {
if (proxy.getType() == IResource.FILE) {
String name= proxy.getName();
if (hasExtension(name, ".java") && isValidCUName(name)) { //$NON-NLS-1$
visitCompilationUnit((IFile) proxy.requestResource());
} else if (hasExtension(name, ".class")) { //$NON-NLS-1$
fClassFiles.add(proxy.requestResource());
} else if (hasExtension(name, ".jar")) { //$NON-NLS-1$
fJARFiles.add(proxy.requestFullPath());
}
return false;
}
return true;
}
public IPath getOutputLocation() {
return fResultOutputFolder;
}
public IClasspathEntry[] getClasspath() {
return fResultClasspath;
}
}
|
40,592 |
Bug 40592 Extend <ctrl-shift-m> (Add Import) functionality
|
Currently, if you do an "add import" for a fully-qualified class, the import is added and the full-qualification is removed. (ie/the package part of the class name is removed). If you do the same to another usage of the same class, nothing happens. It would be very helpful to have the package part of the class name removed for any class that has an existing import when doing an add import.
|
resolved fixed
|
10a1b41
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-23T14:49:26Z | 2003-07-22T13:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AddImportOnSelectionAction.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.util.ArrayList;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ITypeNameRequestor;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
public class AddImportOnSelectionAction extends Action implements IUpdate {
private CompilationUnitEditor fEditor;
public AddImportOnSelectionAction(CompilationUnitEditor editor) {
super(JavaEditorMessages.getString("AddImportOnSelection.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("AddImportOnSelection.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("AddImportOnSelection.description")); //$NON-NLS-1$
fEditor= editor;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
setEnabled(getCompilationUnit() != null);
}
public AddImportOnSelectionAction() {
this(null);
}
public void update() {
setEnabled(fEditor != null && getCompilationUnit() != null);
}
private ICompilationUnit getCompilationUnit () {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(fEditor.getEditorInput());
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
ICompilationUnit cu= getCompilationUnit();
if (!ElementValidator.checkValidateEdit(cu, getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"))) //$NON-NLS-1$
return;
if (!ActionUtil.isProcessable(getShell(), cu))
return;
if (cu != null) {
ISelection s= fEditor.getSelectionProvider().getSelection();
IDocument doc= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
ITextSelection selection= (ITextSelection) s;
if (doc != null) {
try {
int nameStart= getNameStart(doc, selection.getOffset());
int nameEnd= getNameEnd(doc, selection.getOffset() + selection.getLength());
int len= nameEnd - nameStart;
String name= doc.get(nameStart, len).trim();
String simpleName= Signature.getSimpleName(name);
String containerName= Signature.getQualifier(name);
IImportDeclaration existingImport= JavaModelUtil.findImport(cu, simpleName);
if (existingImport != null) {
if (!existingImport.getElementName().equals(name)) {
getShell().getDisplay().beep();
}
return;
}
IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
TypeInfo[] types= findAllTypes(simpleName, searchScope, null);
if (types.length== 0) {
getShell().getDisplay().beep();
return;
}
TypeInfo chosen= selectResult(types, containerName, getShell());
if (chosen == null) {
return;
}
IType type= chosen.resolveType(searchScope);
if (type == null) {
JavaPlugin.logErrorMessage("AddImportOnSelectionAction: Failed to resolve TypeRef: " + chosen.toString()); //$NON-NLS-1$
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), JavaEditorMessages.getString("AddImportOnSelection.error.notresolved.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
removeQualification(doc, nameStart, chosen);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddImportsOperation op= new AddImportsOperation(cu, new IJavaElement[] { type }, settings, false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled.
}
return;
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null); //$NON-NLS-1$
} catch (BadLocationException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
}
}
private int getNameStart(IDocument doc, int pos) throws BadLocationException {
while (pos > 0) {
char ch= doc.getChar(pos - 1);
if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
return pos;
}
pos--;
}
return pos;
}
private int getNameEnd(IDocument doc, int pos) throws BadLocationException {
if (pos > 0) {
if (Character.isWhitespace(doc.getChar(pos - 1))) {
return pos;
}
}
int len= doc.getLength();
while (pos < len) {
char ch= doc.getChar(pos);
if (!Character.isJavaIdentifierPart(ch)) {
return pos;
}
pos++;
}
return pos;
}
private void removeQualification(IDocument doc, int nameStart, TypeInfo typeInfo) throws BadLocationException {
String containerName= typeInfo.getTypeContainerName();
int containerLen= containerName.length();
int docLen= doc.getLength();
if ((containerLen > 0) && (nameStart + containerLen + 1 < docLen)) {
for (int k= 0; k < containerLen; k++) {
if (doc.getChar(nameStart + k) != containerName.charAt(k)) {
return;
}
}
if (doc.getChar(nameStart + containerLen) == '.') {
doc.replace(nameStart, containerLen + 1, ""); //$NON-NLS-1$
}
}
}
/**
* Finds a type by the simple name.
*/
private static TypeInfo[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, IProgressMonitor monitor) throws CoreException {
SearchEngine searchEngine= new SearchEngine();
ArrayList typeRefsFound= new ArrayList(10);
ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound);
searchEngine.searchAllTypeNames(
JavaPlugin.getWorkspace(),
null,
simpleTypeName.toCharArray(),
IJavaSearchConstants.EXACT_MATCH,
IJavaSearchConstants.CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
searchScope,
requestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
monitor);
return (TypeInfo[]) typeRefsFound.toArray(new TypeInfo[typeRefsFound.size()]);
}
private Shell getShell() {
return fEditor.getSite().getShell();
}
private TypeInfo selectResult(TypeInfo[] results, String containerName, Shell shell) {
int nResults= results.length;
if (nResults == 0) {
return null;
} else if (nResults == 1) {
return results[0];
}
if (containerName.length() != 0) {
for (int i= 0; i < nResults; i++) {
TypeInfo curr= results[i];
if (containerName.equals(curr.getTypeContainerName())) {
return curr;
}
}
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED));
dialog.setTitle(JavaEditorMessages.getString("AddImportOnSelection.dialog.title")); //$NON-NLS-1$
dialog.setMessage(JavaEditorMessages.getString("AddImportOnSelection.dialog.message")); //$NON-NLS-1$
dialog.setElements(results);
if (dialog.open() == Window.OK) {
return (TypeInfo) dialog.getFirstResult();
}
return null;
}
}
|
40,291 |
Bug 40291 javadoc / declaration views: should update when shown
|
Tests 20030716 1. Open the declaration view 2. Select a reference in code -> declaration shows in view (ok) 3. Open (or bring to front when in a tabbed view) javadoc view 4. Newly opened view is empty -> should fill with content for current selection when shown / opened
|
resolved fixed
|
80861f1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-25T15:00:13Z | 2003-07-17T11:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/AbstractInfoView.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 org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.search.SearchUtil;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Abstract class for views which show information for a given element.
*
* @since 3.0
*/
abstract class AbstractInfoView extends ViewPart implements ISelectionListener {
/** JavaElementLabels flags used for the title */
private static final int TITLE_LABEL_FLAGS= 0;
/** JavaElementLabels flags used for the tool tip text */
private static final int TOOLTIP_LABEL_FLAGS= JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_POST_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH |
JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_APP_RETURNTYPE | JavaElementLabels.M_EXCEPTIONS |
JavaElementLabels.F_APP_TYPE_SIGNATURE;
/** The current input. */
protected IJavaElement fCurrentInput;
/*
* @see IPartListener2
*/
private IPartListener2 fPartListener= new IPartListener2() {
public void partVisible(IWorkbenchPartReference ref) {
if (ref.getId().equals(getSite().getId()))
startListeningForSelectionChanges();
}
public void partHidden(IWorkbenchPartReference ref) {
if (ref.getId().equals(getSite().getId()))
stopListeningForSelectionChanges();
}
public void partInputChanged(IWorkbenchPartReference ref) {
if (!ref.getId().equals(getSite().getId()))
setInputFrom(ref.getPart(false));
}
public void partActivated(IWorkbenchPartReference ref) {
}
public void partBroughtToTop(IWorkbenchPartReference ref) {
}
public void partClosed(IWorkbenchPartReference ref) {
}
public void partDeactivated(IWorkbenchPartReference ref) {
}
public void partOpened(IWorkbenchPartReference ref) {
}
};
/**
* Set the input of this view.
*
* @param input the input object
* @return <code>true</code> if the input was set successfully
*/
abstract protected boolean setInput(Object input);
/**
* Create the part control.
*
* @param parent the parent control
* @see IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
abstract protected void internalCreatePartControl(Composite parent);
/**
* Set the view's foreground color.
*
* @param color the SWT color
*/
abstract protected void setForeground(Color color);
/**
* Set the view's background color.
*
* @param color the SWT color
*/
abstract protected void setBackground(Color color);
/*
* @see IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public final void createPartControl(Composite parent) {
internalCreatePartControl(parent);
setInfoColor();
getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener);
}
/**
* Sets the foreground and background color to the corresponding SWT info color.
*/
private void setInfoColor() {
if (getSite().getShell().isDisposed())
return;
Display display= getSite().getShell().getDisplay();
if (display == null || display.isDisposed())
return;
setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
/**
* Start to listen for selection changes.
*/
protected void startListeningForSelectionChanges() {
getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(this);
}
/**
* Stop to listen for selection changes.
*/
protected void stopListeningForSelectionChanges() {
getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this);
}
/*
* @see ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part.equals(this))
return;
// XXX: Workaround for bug 38888: javadoc / declaration view: selection is unacceptably slow
if (selection instanceof ITextSelection && ((ITextSelection)selection).getLength() > 0)
return;
setInputFrom(part);
}
/**
* Finds and returns the Java element selected in the given part.
*
* @param part the workbench part for which to find the selected Java element
* @return the selected Java element
*/
private IJavaElement findSelectedJavaElement(IWorkbenchPart part) {
Object element;
try {
IStructuredSelection sel= SelectionConverter.getStructuredSelection(part);
element= SelectionUtil.getSingleElement(sel);
} catch (JavaModelException e) {
return null;
}
if (SearchUtil.isISearchResultViewEntry(element)) {
IJavaElement je= SearchUtil.getJavaElement(element);
if (je != null)
return je;
element= SearchUtil.getResource(element);
}
IJavaElement je= null;
if (element instanceof IAdaptable)
je= (IJavaElement)((IAdaptable)element).getAdapter(IJavaElement.class);
if (je != null && je.getElementType() == IJavaElement.COMPILATION_UNIT)
je= WorkingCopyUtil.getWorkingCopyIfExists((ICompilationUnit)je);
return je;
}
/**
* Finds and returns the type for the given CU.
*
* @param cu the compilation unit
* @return the type with same name as the given CU or the first type in the CU
*/
protected IType getTypeForCU(ICompilationUnit cu) {
if (cu == null || !cu.exists())
return null;
cu= WorkingCopyUtil.getWorkingCopyIfExists(cu);
// Use primary type if possible
IType primaryType= cu.findPrimaryType();
if (primaryType != null)
return primaryType;
// Use first top-level type
try {
IType[] types= cu.getTypes();
if (types.length > 0)
return types[0];
else
return null;
} catch (JavaModelException ex) {
return null;
}
}
/**
* Sets this view's input based on the selection in the given part.
*
* @param part the part from which to get the selected Java element
*/
private void setInputFrom(IWorkbenchPart part) {
IJavaElement je= findSelectedJavaElement(part);
if (fCurrentInput != null && fCurrentInput.equals(je))
return;
if (!setInput(je))
return;
fCurrentInput= je;
setTitle(getSite().getRegisteredName() + " (" + JavaElementLabels.getElementLabel(je, TITLE_LABEL_FLAGS) + ")"); //$NON-NLS-1$//$NON-NLS-2$
setTitleToolTip(JavaElementLabels.getElementLabel(je, TOOLTIP_LABEL_FLAGS)); //$NON-NLS-1$//$NON-NLS-2$
}
/*
* @see IWorkbenchPart#dispose()
*/
final public void dispose() {
getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener);
internalDispose();
}
/*
* @see IWorkbenchPart#dispose()
*/
protected void internalDispose() {
}
}
|
40,722 |
Bug 40722 "add arguement to match" throws NPE [quick fix]
|
---------------Z.java----------------- public class Z extends X { public Z() { super(); //<-- use quickfix here } } class X { public X(int i) { } } ------------------------------------- if you use quick fix where mentioned above to add arguements you get NPE: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.AddArgumentCorrectionProposal.getRew rite(AddArgumentCorrectionProposal.java:53) at org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal.createC ompilationUnitChange(ASTRewriteCorrectionProposal.java:49) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getChange (CUCorrectionProposal.java:90) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getCompilationU nitChange(CUCorrectionProposal.java:291) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.apply (CUCorrectionProposal.java:202) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:328) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithM ask(CompletionProposalPopup.java:292) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey (CompletionProposalPopup.java:581) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey (ContentAssistant.java:599) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey (TextViewer.java:368) at org.eclipse.swt.custom.StyledTextListener.handleEvent (StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:665) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5208) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:4957) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1675) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1671) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:2993) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2872) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
2446a11
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-25T16:17:51Z | 2003-07-24T15:20:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedMethodsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.NewMethodCompletionProposal;
public class UnresolvedMethodsQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedMethodsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedMethodsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedMethodsQuickFixTest("testMethodInAnonymous2"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
fJProject1= ProjectTestSetup.getProject();
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testMethodInSameType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInForInit() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(int i) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInInfixExpression1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) || f(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) || f(2);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private boolean f(int i) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInInfixExpression2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) == f(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) == f(2);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private Object f(int i) {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing0EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing1EmptyLine() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing2EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingComment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingNonJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInSameTypeUsingThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentClass() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(1, 2.1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("\n");
buf.append(" public boolean goo(int i, double d) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInAnonymous1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void xoo() {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" protected void xoo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" foo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testMethodInAnonymous2() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import other.A;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" A.xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public static void xoo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
assertEqualString(preview1, expected1);
}
public void testMethodInDifferentInterface() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(getClass());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("\n");
buf.append(" boolean goo(Class class1);\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testParameterMismatchCast() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo((int) (x + 1));\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(long l) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(long l) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchCast2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((float) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((int) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(float f, E e) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(float f, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x, o);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(null);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(0, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(Object object) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, 1, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, int j, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(int i, int j, X x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(String s, int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int x2) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(Collections.EMPTY_SET, 1, 2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(Set set, int i, int k) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(Set set, int i, int j) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchSwap() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(i - 1, new Object[] { o });\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(Object[] objects, int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o, int i) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" super.foo(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCanAssign() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Collection;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public class E {\n");
buf.append(" boolean bool;\n");
buf.append(" char c;\n");
buf.append(" byte b;\n");
buf.append(" short s;\n");
buf.append(" int i;\n");
buf.append(" long l;\n");
buf.append(" float f;\n");
buf.append(" double d;\n");
buf.append(" Object object;\n");
buf.append(" Vector vector;\n");
buf.append(" Cloneable cloneable;\n");
buf.append(" Collection collection;\n");
buf.append(" Serializable serializable;\n");
buf.append(" Object[] objectArr;\n");
buf.append(" int[] int_arr;\n");
buf.append(" long[] long_arr;\n");
buf.append(" Vector[] vector_arr;\n");
buf.append(" Collection[] collection_arr;\n");
buf.append(" Object[][] objectArrArr;\n");
buf.append(" Collection[][] collection_arrarr;\n");
buf.append(" Vector[][] vector_arrarr;\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
VariableDeclarationFragment bool= findFieldDeclaration(type, "bool");
VariableDeclarationFragment c= findFieldDeclaration(type, "c");
VariableDeclarationFragment b= findFieldDeclaration(type, "b");
VariableDeclarationFragment s= findFieldDeclaration(type, "s");
VariableDeclarationFragment i= findFieldDeclaration(type, "i");
VariableDeclarationFragment l= findFieldDeclaration(type, "l");
VariableDeclarationFragment f= findFieldDeclaration(type, "f");
VariableDeclarationFragment d= findFieldDeclaration(type, "d");
VariableDeclarationFragment object= findFieldDeclaration(type, "object");
VariableDeclarationFragment vector= findFieldDeclaration(type, "vector");
VariableDeclarationFragment cloneable= findFieldDeclaration(type, "cloneable");
VariableDeclarationFragment collection= findFieldDeclaration(type, "collection");
VariableDeclarationFragment serializable= findFieldDeclaration(type, "serializable");
VariableDeclarationFragment objectArr= findFieldDeclaration(type, "objectArr");
VariableDeclarationFragment int_arr= findFieldDeclaration(type, "int_arr");
VariableDeclarationFragment long_arr= findFieldDeclaration(type, "long_arr");
VariableDeclarationFragment vector_arr= findFieldDeclaration(type, "vector_arr");
VariableDeclarationFragment collection_arr= findFieldDeclaration(type, "collection_arr");
VariableDeclarationFragment objectArrArr= findFieldDeclaration(type, "objectArrArr");
VariableDeclarationFragment collection_arrarr= findFieldDeclaration(type, "collection_arrarr");
VariableDeclarationFragment vector_arrarr= findFieldDeclaration(type, "vector_arrarr");
VariableDeclarationFragment[] targets= new VariableDeclarationFragment[] {
bool, c, b, s, i, l, f, d, object, vector, cloneable, serializable, collection, objectArr, int_arr, long_arr,
vector_arr, collection_arr, objectArrArr, collection_arrarr, vector_arrarr
};
for (int k= 0; k < targets.length; k++) {
for (int n= 0; n < targets.length; n++) {
VariableDeclarationFragment f1= targets[k];
VariableDeclarationFragment f2= targets[n];
String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F extends E {\n");
buf.append(" void foo() {\n");
buf.append(" ").append(line).append(";\n");
buf.append(" }\n");
buf.append("}\n");
char[] content= buf.toString().toCharArray();
astRoot= AST.parseCompilationUnit(content, "F.java", cu1.getJavaProject());
problems= astRoot.getProblems();
ITypeBinding b1= f1.resolveBinding().getType();
assertNotNull(b1);
ITypeBinding b2= f2.resolveBinding().getType();
assertNotNull(b2);
boolean res= TypeRules.canAssign(b1, b2.getQualifiedName());
assertEquals(line, problems.length == 0, res);
boolean res2= TypeRules.canAssign(b1, b2);
assertEquals(line, problems.length == 0, res2);
}
}
}
}
|
40,722 |
Bug 40722 "add arguement to match" throws NPE [quick fix]
|
---------------Z.java----------------- public class Z extends X { public Z() { super(); //<-- use quickfix here } } class X { public X(int i) { } } ------------------------------------- if you use quick fix where mentioned above to add arguements you get NPE: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.AddArgumentCorrectionProposal.getRew rite(AddArgumentCorrectionProposal.java:53) at org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal.createC ompilationUnitChange(ASTRewriteCorrectionProposal.java:49) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getChange (CUCorrectionProposal.java:90) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getCompilationU nitChange(CUCorrectionProposal.java:291) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.apply (CUCorrectionProposal.java:202) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:328) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithM ask(CompletionProposalPopup.java:292) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey (CompletionProposalPopup.java:581) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey (ContentAssistant.java:599) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey (TextViewer.java:368) at org.eclipse.swt.custom.StyledTextListener.handleEvent (StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:665) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5208) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:4957) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1675) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1671) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:2993) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2872) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
2446a11
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-25T16:17:51Z | 2003-07-24T15:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ChangeMethodSignatureProposal.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.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ArrayType;
import org.eclipse.jdt.core.dom.CompilationUnit;
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.SingleVariableDeclaration;
import org.eclipse.jdt.core.dom.Type;
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.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer;
public class ChangeMethodSignatureProposal extends LinkedCorrectionProposal {
public static interface ChangeDescription {
}
public static class SwapDescription implements ChangeDescription {
int index;
public SwapDescription(int index) {
this.index= index;
}
}
public static class RemoveDescription implements ChangeDescription {
}
private static class ModifyDescription implements ChangeDescription {
String name;
ITypeBinding type;
SingleVariableDeclaration resultingNode;
public ModifyDescription(ITypeBinding type, String name) {
this.type= type;
this.name= name;
}
}
public static class EditDescription extends ModifyDescription {
public EditDescription(ITypeBinding type, String name) {
super(type, name);
}
}
public static class InsertDescription extends ModifyDescription {
public InsertDescription(ITypeBinding type, String name) {
super(type, name);
}
}
private ASTNode fNameNode;
private IMethodBinding fSenderBinding;
private ChangeDescription[] fParameterChanges;
public ChangeMethodSignatureProposal(String label, ICompilationUnit targetCU, ASTNode nameNode, IMethodBinding binding, ChangeDescription[] changes, int relevance, Image image) {
super(label, targetCU, null, relevance, image);
fNameNode= nameNode;
fSenderBinding= binding;
fParameterChanges= changes;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot= (CompilationUnit) fNameNode.getRoot();
ASTNode methodDecl= astRoot.findDeclaringNode(fSenderBinding);
ASTNode newMethodDecl= null;
boolean isInDifferentCU;
if (methodDecl != null) {
isInDifferentCU= false;
newMethodDecl= methodDecl;
} else {
isInDifferentCU= true;
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newMethodDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newMethodDecl instanceof MethodDeclaration) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
modifySignature(rewrite, (MethodDeclaration) newMethodDecl, isInDifferentCU);
return rewrite;
}
return null;
}
private void modifySignature(ASTRewrite rewrite, MethodDeclaration methodDecl, boolean isInDifferentCU) throws CoreException {
List parameters= methodDecl.parameters();
// create a copy to not loose the indexes
SingleVariableDeclaration[] oldParameters= (SingleVariableDeclaration[]) parameters.toArray(new SingleVariableDeclaration[parameters.size()]);
AST ast= methodDecl.getAST();
int k= 0; // index over the oldParameters
ArrayList usedNames= new ArrayList();
boolean hasCreatedVariables= false;
IVariableBinding[] declaredFields= fSenderBinding.getDeclaringClass().getDeclaredFields();
for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
usedNames.add(declaredFields[i].getName());
}
for (int i= 0; i < fParameterChanges.length; i++) {
ChangeDescription curr= fParameterChanges[i];
if (curr == null) {
usedNames.add(oldParameters[k].getName().getIdentifier());
k++;
} else if (curr instanceof InsertDescription) {
InsertDescription desc= (InsertDescription) curr;
SingleVariableDeclaration newNode= ast.newSingleVariableDeclaration();
String type= addImport(desc.type);
newNode.setType(ASTNodeFactory.newType(ast, type));
// remember to set name later
desc.resultingNode= newNode;
hasCreatedVariables= true;
rewrite.markAsInserted(newNode);
parameters.add(i, newNode);
} else if (curr instanceof RemoveDescription) {
rewrite.markAsRemoved(oldParameters[k]);
k++;
} else if (curr instanceof EditDescription) {
EditDescription desc= (EditDescription) curr;
SingleVariableDeclaration newNode= ast.newSingleVariableDeclaration();
String type= addImport(desc.type);
newNode.setType(ASTNodeFactory.newType(ast, type));
// remember to set name later
desc.resultingNode= newNode;
hasCreatedVariables= true;
rewrite.markAsReplaced(oldParameters[k], newNode);
k++;
} else if (curr instanceof SwapDescription) {
SingleVariableDeclaration decl1= oldParameters[k];
SingleVariableDeclaration decl2= oldParameters[((SwapDescription) curr).index];
rewrite.markAsReplaced(decl1, rewrite.createCopy(decl2));
rewrite.markAsReplaced(decl2, rewrite.createCopy(decl1));
usedNames.add(decl1.getName().getIdentifier());
k++;
}
}
if (!hasCreatedVariables) {
return;
}
if (methodDecl.getBody() != null) {
// avoid take a name of a local variable inside
CompilationUnit root= (CompilationUnit) methodDecl.getRoot();
IBinding[] bindings= (new ScopeAnalyzer(root)).getDeclarationsAfter(methodDecl.getBody().getStartPosition(), ScopeAnalyzer.VARIABLES);
for (int i= 0; i < bindings.length; i++) {
usedNames.add(bindings[i].getName());
}
}
fixupNames(rewrite, usedNames, isInDifferentCU);
}
private void fixupNames(ASTRewrite rewrite, ArrayList usedNames, boolean isInDifferentCU) {
AST ast= rewrite.getRootNode().getAST();
// set names for new parameters
for (int i= 0; i < fParameterChanges.length; i++) {
ChangeDescription curr= fParameterChanges[i];
if (curr instanceof ModifyDescription) {
ModifyDescription desc= (ModifyDescription) curr;
SingleVariableDeclaration var= desc.resultingNode;
String suggestedName= desc.name;
String typeKey= "param_type_" + i; //$NON-NLS-1$
String nameKey= "param_name_" + i; //$NON-NLS-1$
// collect name suggestions
String favourite= null;
String[] excludedNames= (String[]) usedNames.toArray(new String[usedNames.size()]);
if (suggestedName != null) {
favourite= StubUtility.guessArgumentName(getCompilationUnit().getJavaProject(), suggestedName, excludedNames);
addLinkedModeProposal(nameKey, favourite);
}
Type type= var.getType();
int dim= 0;
if (type.isArrayType()) {
dim= ((ArrayType) type).getDimensions();
type= ((ArrayType) type).getElementType();
}
String[] suggestedNames= NamingConventions.suggestArgumentNames(getCompilationUnit().getJavaProject(), "", ASTNodes.asString(type), dim, excludedNames); //$NON-NLS-1$
for (int k= 0; k < suggestedNames.length; k++) {
addLinkedModeProposal(nameKey, suggestedNames[k]);
}
if (favourite == null) {
favourite= suggestedNames[0];
}
var.setName(ast.newSimpleName(favourite));
usedNames.add(favourite);
// collect type suggestions
ITypeBinding[] bindings= ASTResolving.getRelaxingTypes(ast, desc.type);
for (int k= 0; k < bindings.length; k++) {
addLinkedModeProposal(typeKey, bindings[k]);
}
markAsLinked(rewrite, var.getType(), false, typeKey); //$NON-NLS-1$
markAsLinked(rewrite, var.getName(), false, nameKey); //$NON-NLS-1$
}
}
if (isInDifferentCU) {
markAsSelection(rewrite, fNameNode.getParent());
}
}
}
|
40,722 |
Bug 40722 "add arguement to match" throws NPE [quick fix]
|
---------------Z.java----------------- public class Z extends X { public Z() { super(); //<-- use quickfix here } } class X { public X(int i) { } } ------------------------------------- if you use quick fix where mentioned above to add arguements you get NPE: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.AddArgumentCorrectionProposal.getRew rite(AddArgumentCorrectionProposal.java:53) at org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal.createC ompilationUnitChange(ASTRewriteCorrectionProposal.java:49) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getChange (CUCorrectionProposal.java:90) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getCompilationU nitChange(CUCorrectionProposal.java:291) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.apply (CUCorrectionProposal.java:202) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:328) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithM ask(CompletionProposalPopup.java:292) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey (CompletionProposalPopup.java:581) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey (ContentAssistant.java:599) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey (TextViewer.java:368) at org.eclipse.swt.custom.StyledTextListener.handleEvent (StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:665) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5208) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:4957) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1675) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1671) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:2993) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2872) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
2446a11
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-25T16:17:51Z | 2003-07-24T15:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.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.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.NamingConventions;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.ui.CodeGeneration;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
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.ASTRewrite;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class NewMethodCompletionProposal extends LinkedCorrectionProposal {
private static final String KEY_NAME= "name"; //$NON-NLS-1$
private static final String KEY_TYPE= "type"; //$NON-NLS-1$
private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation
private List fArguments;
private ITypeBinding fSenderBinding;
private boolean fIsInDifferentCU;
public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) {
super(label, targetCU, null, relevance, image);
fNode= invocationNode;
fArguments= arguments;
fSenderBinding= binding;
}
protected ASTRewrite getRewrite() throws CoreException {
CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode);
ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding);
ASTNode newTypeDecl= null;
if (typeDecl != null) {
fIsInDifferentCU= false;
newTypeDecl= typeDecl;
} else {
fIsInDifferentCU= true;
astRoot= AST.parseCompilationUnit(getCompilationUnit(), true);
newTypeDecl= astRoot.findDeclaringNode(fSenderBinding.getKey());
}
if (newTypeDecl != null) {
ASTRewrite rewrite= new ASTRewrite(astRoot);
List members;
if (fSenderBinding.isAnonymous()) {
members= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations();
} else {
members= ((TypeDeclaration) newTypeDecl).bodyDeclarations();
}
MethodDeclaration newStub= getStub(rewrite, newTypeDecl);
if (isConstructor()) {
members.add(findConstructorInsertIndex(members), newStub);
} else if (!fIsInDifferentCU) {
members.add(findMethodInsertIndex(members, fNode.getStartPosition()), newStub);
} else {
members.add(newStub);
}
rewrite.markAsInserted(newStub);
if (!fIsInDifferentCU) {
Name invocationName= getInvocationName();
if (invocationName != null) {
markAsLinked(rewrite, invocationName, true, KEY_NAME);
}
}
markAsLinked(rewrite, newStub.getName(), false, KEY_NAME); //$NON-NLS-1$
if (!newStub.isConstructor()) {
markAsLinked(rewrite, newStub.getReturnType(), false, KEY_TYPE); //$NON-NLS-1$
}
return rewrite;
}
return null;
}
private boolean isConstructor() {
return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION;
}
private MethodDeclaration getStub(ASTRewrite rewrite, ASTNode targetTypeDecl) throws CoreException {
AST ast= targetTypeDecl.getAST();
MethodDeclaration decl= ast.newMethodDeclaration();
decl.setConstructor(isConstructor());
decl.setModifiers(evaluateModifiers(targetTypeDecl));
decl.setName(ast.newSimpleName(getMethodName()));
List arguments= fArguments;
List params= decl.parameters();
int nArguments= arguments.size();
ArrayList takenNames= new ArrayList(nArguments);
IVariableBinding[] declaredFields= fSenderBinding.getDeclaredFields();
for (int i= 0; i < declaredFields.length; i++) { // avoid to take parameter names that are equal to field names
takenNames.add(declaredFields[i].getName());
}
for (int i= 0; i < arguments.size(); i++) {
Expression elem= (Expression) arguments.get(i);
SingleVariableDeclaration param= ast.newSingleVariableDeclaration();
// argument type
String argTypeKey= "arg_type_" + i; //$NON-NLS-1$
Type type= evaluateParameterTypes(ast, elem, argTypeKey);
param.setType(type);
// argument name
String argNameKey= "arg_name_" + i; //$NON-NLS-1$
String name= evaluateParameterNames(takenNames, elem, type, argNameKey);
param.setName(ast.newSimpleName(name));
params.add(param);
markAsLinked(rewrite, param.getType(), false, argTypeKey);
markAsLinked(rewrite, param.getName(), false, argNameKey);
}
Block body= null;
String bodyStatement= ""; //$NON-NLS-1$
if (!isConstructor()) {
Type returnType= evaluateMethodType(ast);
if (returnType == null) {
decl.setReturnType(ast.newPrimitiveType(PrimitiveType.VOID));
} else {
decl.setReturnType(returnType);
}
if (!fSenderBinding.isInterface() && returnType != null) {
ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
bodyStatement= ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'));
}
}
if (!fSenderBinding.isInterface()) {
body= ast.newBlock();
String placeHolder= CodeGeneration.getMethodBodyContent(getCompilationUnit(), fSenderBinding.getName(), getMethodName(), isConstructor(), bodyStatement, String.valueOf('\n'));
if (placeHolder != null) {
ASTNode todoNode= rewrite.createPlaceholder(placeHolder, ASTRewrite.STATEMENT);
body.statements().add(todoNode);
}
}
decl.setBody(body);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (settings.createComments && !fSenderBinding.isAnonymous()) {
String string= CodeGeneration.getMethodComment(getCompilationUnit(), fSenderBinding.getName(), decl, null, String.valueOf('\n'));
if (string != null) {
Javadoc javadoc= (Javadoc) rewrite.createPlaceholder(string, ASTRewrite.JAVADOC);
decl.setJavadoc(javadoc);
}
}
return decl;
}
private int findMethodInsertIndex(List decls, int currPos) {
int nDecls= decls.size();
for (int i= 0; i < nDecls; i++) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) {
return i + 1;
}
}
return nDecls;
}
private int findConstructorInsertIndex(List decls) {
int nDecls= decls.size();
int lastMethod= 0;
for (int i= nDecls - 1; i >= 0; i--) {
ASTNode curr= (ASTNode) decls.get(i);
if (curr instanceof MethodDeclaration) {
if (((MethodDeclaration) curr).isConstructor()) {
return i + 1;
}
lastMethod= i;
}
}
return lastMethod;
}
private Name getInvocationName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName();
} else if (fNode instanceof ClassInstanceCreation) {
return ((ClassInstanceCreation)fNode).getName();
}
return null;
}
private String getMethodName() {
if (fNode instanceof MethodInvocation) {
return ((MethodInvocation)fNode).getName().getIdentifier();
} else if (fNode instanceof SuperMethodInvocation) {
return ((SuperMethodInvocation)fNode).getName().getIdentifier();
} else {
return fSenderBinding.getName(); // name of the class
}
}
private int evaluateModifiers(ASTNode targetTypeDecl) {
if (fSenderBinding.isInterface()) {
// for interface members copy the modifiers from an existing field
MethodDeclaration[] methodDecls= ((TypeDeclaration) targetTypeDecl).getMethods();
if (methodDecls.length > 0) {
return methodDecls[0].getModifiers();
}
return 0;
}
if (fNode instanceof MethodInvocation) {
int modifiers= 0;
Expression expression= ((MethodInvocation)fNode).getExpression();
if (expression != null) {
if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) {
modifiers |= Modifier.STATIC;
}
} else if (ASTResolving.isInStaticContext(fNode)) {
modifiers |= Modifier.STATIC;
}
ASTNode node= ASTResolving.findParentType(fNode);
if (targetTypeDecl.equals(node)) {
modifiers |= Modifier.PRIVATE;
} else if (node instanceof AnonymousClassDeclaration && ASTNodes.isParent(node, targetTypeDecl)) {
modifiers |= Modifier.PROTECTED;
} else {
modifiers |= Modifier.PUBLIC;
}
return modifiers;
}
return Modifier.PUBLIC;
}
private Type evaluateMethodType(AST ast) throws CoreException {
ITypeBinding binding= ASTResolving.guessBindingForReference(fNode);
if (binding != null) {
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
} else {
ASTNode parent= fNode.getParent();
if (!(parent instanceof ExpressionStatement)) {
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
}
return null;
}
private Type evaluateParameterTypes(AST ast, Expression elem, String key) throws CoreException {
ITypeBinding binding= Bindings.normalizeTypeBinding(elem.resolveTypeBinding());
if (binding != null) {
ITypeBinding[] typeProposals= ASTResolving.getRelaxingTypes(ast, binding);
for (int i= 0; i < typeProposals.length; i++) {
addLinkedModeProposal(key, typeProposals[i]);
}
String typeName= addImport(binding);
return ASTNodeFactory.newType(ast, typeName);
}
return ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
private String evaluateParameterNames(ArrayList takenNames, Expression argNode, Type type, String key) {
IJavaProject project= getCompilationUnit().getJavaProject();
String[] excludedNames= (String[]) takenNames.toArray(new String[takenNames.size()]);
String favourite= null;
if (argNode instanceof SimpleName) {
SimpleName name= (SimpleName) argNode;
favourite= StubUtility.guessArgumentName(project, name.getIdentifier(), excludedNames);
}
int dim= 0;
if (type.isArrayType()) {
ArrayType arrayType= (ArrayType) type;
dim= arrayType.getDimensions();
type= arrayType.getElementType();
}
String typeName= ASTNodes.asString(type);
String packName= Signature.getQualifier(typeName);
String[] names= NamingConventions.suggestArgumentNames(project, packName, typeName, dim, excludedNames);
if (favourite == null) {
favourite= names[0];
}
for (int i= 0; i < names.length; i++) {
addLinkedModeProposal(key, names[i]);
}
takenNames.add(favourite);
return favourite;
}
}
|
40,722 |
Bug 40722 "add arguement to match" throws NPE [quick fix]
|
---------------Z.java----------------- public class Z extends X { public Z() { super(); //<-- use quickfix here } } class X { public X(int i) { } } ------------------------------------- if you use quick fix where mentioned above to add arguements you get NPE: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.AddArgumentCorrectionProposal.getRew rite(AddArgumentCorrectionProposal.java:53) at org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal.createC ompilationUnitChange(ASTRewriteCorrectionProposal.java:49) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getChange (CUCorrectionProposal.java:90) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.getCompilationU nitChange(CUCorrectionProposal.java:291) at org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal.apply (CUCorrectionProposal.java:202) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:328) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithM ask(CompletionProposalPopup.java:292) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey (CompletionProposalPopup.java:581) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey (ContentAssistant.java:599) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey (TextViewer.java:368) at org.eclipse.swt.custom.StyledTextListener.handleEvent (StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:665) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5208) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:4957) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1675) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1671) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:2993) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2872) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
2446a11
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-25T16:17:51Z | 2003-07-24T15:20:00Z |
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 <[email protected]> - 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.ui.text.java.*;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
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.textmanipulation.SimpleTextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
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.preferences.JavaPreferencesSettings;
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;
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 suggestVariablePropasals= true;
int typeKind= 0;
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) {
suggestVariablePropasals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
}
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;
suggestVariablePropasals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariablePropasals= 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(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if (!suggestVariablePropasals) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
addSimilarVariableProposals(cu, astRoot, simpleName, proposals);
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image));
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
senderBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!senderBinding.isAnonymous()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image));
}
}
}
}
if (binding == null) {
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 5, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 7, 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= new ASTRewrite(statement.getParent());
rewrite.markAsRemoved(statement);
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);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
}
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, Collection proposals) {
IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES);
if (varsInScope.length > 0) {
// avoid corrections like int i= i;
String assignedName= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier();
}
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();
if (!currName.equals(assignedName)) {
int relevance= 0;
if (NameMatcher.isSimilarName(currName, identifier)) {
relevance += 3; // variable with a similar name than the unresolved variable
}
if (guessedType != null && TypeRules.canAssign(guessedType, curr.getType())) {
relevance += 2; // unresolved variable can be assign to this variable
}
if (relevance > 0) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
}
}
}
}
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 variablefragment
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.REF_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;
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 simlar 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 JavaModelException {
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 JavaModelException {
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importEdit.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importEdit.isEmpty()) {
root.add(importEdit); //$NON-NLS-1$
}
String[] arg= { simpleName, Signature.getQualifier(fullName) };
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg)); //$NON-NLS-1$
proposal.setRelevance(relevance + 20);
} else {
root.add(SimpleTextEdit.createReplace(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg)); //$NON-NLS-1$
proposal.setRelevance(relevance);
}
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTResolving.getSimpleName(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't sugest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 24347
// IBinding binding= qualifierName.resolveBinding();
// if (binding instanceof ITypeBinding) {
// enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject());
IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
if (res!= null && res.length > 0 && res[0] instanceof IType) {
enclosingType= (IType) res[0];
} else {
qualifier= qualifierName;
enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
}
}
// new top level type
if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance));
}
}
// new member type
if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) {
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance));
}
}
}
node= qualifier;
} while (node != null);
}
public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, 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) && needsNewName) {
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 ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6));
}
}
addParameterMissmatchProposals(context, problem, parameterMismatchs, 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)) {
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));
}
}
}
}
}
}
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, 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, 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, arguments, argTypes, elem, proposals);
} else {
doMoreArguments(context, problem, arguments, argTypes, elem, proposals);
}
}
}
private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, 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();
ASTNode nameNode= problem.getCoveredNode(astRoot);
// 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(), nameNode, arguments, indexSkipped, paramTypes, 8);
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD));
proposal.ensureNoModifications();
proposals.add(proposal);
}
// remove parameters
if (declaringType.isFromSource()) {
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, nameNode, methodBinding, changeDesc, 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 void doMoreArguments(IInvocationContext context, IProblemLocation problem, 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();
ASTNode nameNode= problem.getCoveredNode(astRoot);
// remove arguments
{
ASTNode selectedNode= problem.getCoveringNode(astRoot);
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]));
}
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);
proposal.ensureNoModifications();
proposals.add(proposal);
}
// add parameters
if (declaringType.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType);
if (targetCU != null) {
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, !cu.equals(targetCU)), 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, nameNode, methodBinding, changeDesc, 5, image);
proposals.add(proposal);
}
}
}
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, 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.getCoveredNode(astRoot);
if (nDiffs == 1) { // one argument missmatching: try to fix
int idx= indexOfDiff[0];
Expression nodeToCast= (Expression) arguments.get(idx);
String castType= paramTypes[idx].getQualifiedName();
ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.getCastProposal(context, castType, nodeToCast, 6);
if (proposal != null) { // null returned when no cast is possible
proposals.add(proposal);
String[] arg= new String[] { String.valueOf(idx + 1), castType };
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$
}
}
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= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2));
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1));
{
String[] arg= new String[] { String.valueOf(idx1 + 1), String.valueOf(idx2 + 1) };
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);
proposal.ensureNoModifications();
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[] { argTypes[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, nameNode, methodBinding, changeDesc, 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);
}
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) };
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, nameNode, methodBinding, changeDesc, 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;
}
curr= Bindings.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
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;
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();
}
}
if (targetBinding == null) {
return;
}
IMethodBinding[] methods= targetBinding.getDeclaredMethods();
ArrayList similarElements= new ArrayList();
IMethodBinding defConstructor= null;
for (int i= 0; i < methods.length; i++) {
IMethodBinding curr= methods[i];
if (curr.isConstructor()) {
if (curr.getParameterTypes().length == 0) {
defConstructor= curr;
} else {
similarElements.add(curr);
}
}
}
if (defConstructor != null) {
// default constructor could be implicit (bug 36819). Only add when we're sure its not.
// Misses the case when in other type
if (!similarElements.isEmpty() || (astRoot.findDeclaringNode(defConstructor) != null)) {
similarElements.add(defConstructor);
}
}
addParameterMissmatchProposals(context, problem, similarElements, 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= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
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) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image);
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importEdit.addImport(qualifiedTypeName);
importEdit.setFindAmbiguosImports(true);
proposal.getRootTextEdit().add(importEdit);
proposals.add(proposal);
}
}
}
}
|
40,793 |
Bug 40793 Primary working copies: Type search does not find type in modified CU
|
M2 See test cases AllTypesCacheTest.testWorkingCopies() & testWorkingCopies2(): Editor is opened and the type name of the opened type is modfied. testWorkingCopies(): editor is saved: new type is found in index but also old type is still found testWorkingCopies2(): editor is not saved: new type is not found in index
|
verified fixed
|
ebffc44
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-25T17:21:28Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/AllTypesCacheTest.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.tests.core;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipFile;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
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.testplugin.JavaProjectHelper;
import org.eclipse.jdt.testplugin.JavaTestPlugin;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
public class AllTypesCacheTest extends TestCase {
private static final Class THIS= AllTypesCacheTest.class;
private IJavaProject fJProject1;
private IJavaProject fJProject2;
private IPackageFragmentRoot fLibrary;
private IPackageFragmentRoot fSourceFolder;
public AllTypesCacheTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new AllTypesCacheTest("testClasspathChange"));
return suite;
}
}
protected void setUp() throws Exception {
fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin");
assertNotNull("jre is null", JavaProjectHelper.addRTJar(fJProject1));
File lib= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.MYLIB);
assertTrue("lib does not exist", lib != null && lib.exists());
fLibrary= JavaProjectHelper.addLibrary(fJProject1, new Path(lib.getPath())); // add library to proj1
fJProject2= JavaProjectHelper.createJavaProject("TestProject2", "bin");
assertNotNull("jre is null", JavaProjectHelper.addRTJar(fJProject2));
// add Junit source to project 2
File junitSrcArchive= JavaTestPlugin.getDefault().getFileInPlugin(JavaProjectHelper.JUNIT_SRC);
assertTrue("Junit source", junitSrcArchive != null && junitSrcArchive.exists());
ZipFile zipfile= new ZipFile(junitSrcArchive);
fSourceFolder= JavaProjectHelper.addSourceContainerWithImport(fJProject2, "src", zipfile);
}
protected void tearDown() throws Exception {
JavaProjectHelper.delete(fJProject1);
JavaProjectHelper.delete(fJProject2);
}
public void testDifferentScopes() throws Exception {
IJavaSearchScope workspaceScope= SearchEngine.createWorkspaceScope();
IJavaSearchScope proj1Scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { fJProject1 });
IJavaSearchScope proj2Scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { fJProject2 });
ArrayList res1= new ArrayList();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertTrue("542 types in workspace expected, is " + res1.size(), res1.size() == 542);
int nFlushes= AllTypesCache.getNumberOfCacheFlushes();
res1.clear();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.INTERFACE, null, res1);
assertTrue("73 interfaces in workspace expected, is " + res1.size(), res1.size() == 73);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.CLASS, null, res1);
assertTrue("469 classes in workspace expected, is " + res1.size(), res1.size() == 469);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(proj1Scope, IJavaSearchConstants.TYPE, null, res1);
assertTrue("471 types in proj1 expected, is " + res1.size(), res1.size() == 471);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(proj1Scope, IJavaSearchConstants.INTERFACE, null, res1);
assertTrue("65 interfaces in proj1 expected, is " + res1.size(), res1.size() == 65);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(proj1Scope, IJavaSearchConstants.CLASS, null, res1);
assertTrue("406 classes in proj1 expected, is " + res1.size(), res1.size() == 406);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(proj2Scope, IJavaSearchConstants.TYPE, null, res1);
assertTrue("539 types in proj2 expected, is " + res1.size(), res1.size() == 539);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(proj2Scope, IJavaSearchConstants.INTERFACE, null, res1);
assertTrue("73 interfaces in proj2 expected, is " + res1.size(), res1.size() == 73);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
res1.clear();
AllTypesCache.getTypes(proj2Scope, IJavaSearchConstants.CLASS, null, res1);
assertTrue("466 classes in proj2 expected, is " + res1.size(), res1.size() == 466);
assertTrue("unnecessary flush of cache", AllTypesCache.getNumberOfCacheFlushes() == nFlushes);
}
public void testClasspathChange() throws Exception {
IJavaSearchScope workspaceScope= SearchEngine.createWorkspaceScope();
ArrayList res1= new ArrayList();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertNotNull("mylib.Foo not found", findTypeRef(res1, "mylib.Foo"));
assertTrue("542 types expected, is " + res1.size(), res1.size() == 542);
int nFlushes= AllTypesCache.getNumberOfCacheFlushes();
JavaProjectHelper.removeFromClasspath(fJProject1, fLibrary.getPath());
res1.clear();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertNull("mylib.Foo still found", findTypeRef(res1, "mylib.Foo"));
assertTrue("539 types in workspace expected, is " + res1.size(), res1.size() == 539);
assertTrue("cache not flushed", nFlushes != AllTypesCache.getNumberOfCacheFlushes());
}
public void testNewElementCreation() throws Exception {
IJavaSearchScope workspaceScope= SearchEngine.createWorkspaceScope();
ArrayList res1= new ArrayList();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertTrue("542 types expected, is " + res1.size(), res1.size() == 542);
int nFlushes= AllTypesCache.getNumberOfCacheFlushes();
IPackageFragment pack= fSourceFolder.getPackageFragment("");
ICompilationUnit newCU= pack.getCompilationUnit("A.java");
IType type= newCU.createType("public class A {\n}\n", null, true, null);
res1.clear();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertNotNull("A not found", findTypeRef(res1, "A"));
assertTrue("543 types in workspace expected, is " + res1.size(), res1.size() == 543);
assertTrue("cache not flushed", nFlushes != AllTypesCache.getNumberOfCacheFlushes());
nFlushes= AllTypesCache.getNumberOfCacheFlushes();
// create a field: should not flush cache
type.createField("public int fCount;", null, true, null);
res1.clear();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertTrue("still 543 types in workspace expected, is " + res1.size(), res1.size() == 543);
assertTrue("cache was flushed", nFlushes == AllTypesCache.getNumberOfCacheFlushes());
// create an inner type: should flush cache
type.createType("public class AInner {}", null, true, null);
res1.clear();
AllTypesCache.getTypes(workspaceScope, IJavaSearchConstants.TYPE, null, res1);
assertNotNull("AInner not found", findTypeRef(res1, "A.AInner"));
assertTrue("still 544 types in workspace expected, is " + res1.size(), res1.size() == 544);
assertTrue("cache not flushed after inner type creation", nFlushes != AllTypesCache.getNumberOfCacheFlushes());
}
private TypeInfo findTypeRef(List refs, String fullname) {
for (int i= 0; i <refs.size(); i++) {
TypeInfo curr= (TypeInfo) refs.get(i);
if (fullname.equals(curr.getFullyQualifiedName())) {
return curr;
}
}
return null;
}
}
|
40,074 |
Bug 40074 [navigation] Selection reset to previous item when arrowing in outline
|
build I20030710 - open a Java editor on a class with several methods - in the outline, select the first method - use the arrow key to go down one item - as soon as the delay passes and the new text range is selected, use the arrow key to go down another item - after the delay, the selection is reset back to the previous item
|
resolved fixed
|
bfd97bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-28T12:51:06Z | 2003-07-15T03: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.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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.IStatus;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
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.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.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.ChangeRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IChangeRulerColumn;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberChangeRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
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.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
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.editors.quickdiff.IQuickDiffProviderImplementation;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
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.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.ui.internal.editors.quickdiff.DocumentLineDiffer;
import org.eclipse.ui.internal.editors.quickdiff.ReferenceProviderDescriptor;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
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.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.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.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor 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
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
if (isEditingScriptRunning())
return;
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** 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);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
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 && !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();
}
});
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
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
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for showing the line number ruler */
protected final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
protected final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** 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 highlighting current line */
protected final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
protected final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
protected final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
protected final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
protected final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for error indication */
protected final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
protected final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
protected final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
protected final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
protected final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
protected final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
protected final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
protected final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
protected final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
protected final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
protected final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
protected final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for shwoing the overview ruler */
protected final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
protected final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** Indicates whether this editor should react on outline page selection changes */
private int fIgnoreOutlinePageSelection;
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/**
* The change ruler column.
* @since 3.0
*/
private IChangeRulerColumn fChangeRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** The annotation access */
protected IAnnotationAccess fAnnotationAccess= new AnnotationAccess();
/** The source viewer decoration support */
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/** The overview ruler */
protected OverviewRuler fOverviewRuler;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Whether quick diff information is displayed, either on a change ruler or the line number ruler.
* @since 3.0
*/
private boolean fIsChangeInformationShown;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISharedTextColors sharedColors= JavaPlugin.getDefault().getJavaTextTools().getColorManager();
fOverviewRuler= new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.WARNING);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.ERROR);
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
configureSourceViewerDecorationSupport();
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
if (fOutlinePage != null && element != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (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= 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 IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
public synchronized void editingScriptStarted() {
++ fIgnoreOutlinePageSelection;
}
public synchronized void editingScriptEnded() {
-- fIgnoreOutlinePageSelection;
}
public synchronized boolean isEditingScriptRunning() {
return (fIgnoreOutlinePageSelection > 0);
}
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);
try {
editingScriptStarted();
setSelection(reference, !isActivePart());
} finally {
editingScriptEnded();
}
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part != null && part.equals(this);
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= 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();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
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});
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);
}
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 (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null
&& (LINE_NUMBER_COLOR.equals(property)
|| PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
|| PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (PreferenceConstants.QUICK_DIFF_CHANGED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_ADDED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_DELETED_COLOR.equals(property)) {
if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
initializeChangeRulerColumn((IChangeRulerColumn) fLineNumberRulerColumn);
else if (fChangeRulerColumn != null)
initializeChangeRulerColumn(fChangeRulerColumn);
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#showChangeInformation(boolean)
*/
public void showChangeInformation(boolean show) {
if (show == fIsChangeInformationShown)
return;
if (fIsChangeInformationShown) {
uninstallChangeRulerModel();
showChangeRuler(false); // hide change ruler if its displayed - if the line number ruler is showing, only the colors get removed by deinstalling the model
} else {
ensureChangeInfoCanBeDisplayed(); // can be replaced w/ showChangeRuler(false) once the old line number ruler is gone
installChangeRulerModel();
}
fIsChangeInformationShown= show;
}
/**
* Installs the differ annotation model with the current quick diff display.
* @since R3.0
*/
private void installChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(getOrCreateDiffer());
}
/**
* Uninstalls the differ annotation model from the current quick diff display.
*
* @since R3.0
*/
private void uninstallChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(null);
}
/**
* Ensures that either the line number display is a <code>LineNumberChangeRuler</code> or
* a separate change ruler gets displayed.
*
* @since R3.0
*/
private void ensureChangeInfoCanBeDisplayed() {
if (isLineNumberRulerVisible()) {
if (!(fLineNumberRulerColumn instanceof IChangeRulerColumn)) {
hideLineNumberRuler();
// HACK: set state already so a change ruler is created. Not needed once always a change line number bar gets installed
fIsChangeInformationShown= true;
showLineNumberRuler();
}
} else
showChangeRuler(true);
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#isChangeInformationShowing()
*/
public boolean isChangeInformationShowing() {
return fIsChangeInformationShown;
}
/**
* Creates a new <code>DocumentLineDiffer</code> and installs it with <code>model</code>.
* The default reference provider is installed with the newly created differ.
*
* @param model the annotation model of the current document.
* @return a new <code>DocumentLineDiffer</code> instance.
* @since R3.0
*/
private DocumentLineDiffer createDiffer(IAnnotationModelExtension model) {
DocumentLineDiffer differ;
differ= new DocumentLineDiffer();
IQuickDiffProviderImplementation provider= getDefaultReferenceProvider();
if (provider != null)
differ.setReferenceProvider(provider);
model.addAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID, differ);
return differ;
}
/**
* Returns the default quick diff reference provider. It is determined by first trying to
* enable the preferred provider as specified by the preferences; if this is unsuccessful, the
* default provider as specified by the extension point mechanism is installed. If that fails
* as well, <code>null</code> is returned.
*
* @return the default reference provider
* @since R3.0
*/
private IQuickDiffProviderImplementation getDefaultReferenceProvider() {
String defaultID= getPreferenceStore().getString(PreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER);
EditorsPlugin editorPlugin= EditorsPlugin.getDefault();
ReferenceProviderDescriptor[] descs= editorPlugin.getExtensions();
IQuickDiffProviderImplementation provider= null;
// try to fetch preferred provider; load if needed
for (int i= 0; i < descs.length; i++) {
if (descs[i].getId().equals(defaultID)) {
provider= descs[i].createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (provider.isEnabled())
break;
provider.dispose();
provider= null;
}
}
}
// if not found, get default provider as specified by the extension point
if (provider == null) {
ReferenceProviderDescriptor defaultDescriptor= editorPlugin.getDefaultProvider();
if (defaultDescriptor != null) {
provider= defaultDescriptor.createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (!provider.isEnabled()) {
provider.dispose();
provider= null;
}
}
}
}
return provider;
}
/**
* Returns the annotation model associated with the document displayed in the
* viewer if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>.
*
* @return the displayed document's annotation model if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>
* @since R3.0
*/
private IAnnotationModelExtension getModel() {
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return null;
IAnnotationModel m= viewer.getAnnotationModel();
if (m instanceof IAnnotationModelExtension)
return (IAnnotationModelExtension) m;
else
return null;
}
/**
* Extracts the line differ from the displayed document's annotation model. If none can be found,
* a new differ is created and attached to the annotation model.
*
* @return the linediffer, or <code>null</code> if none could be found or created.
* @since R3.0
*/
private DocumentLineDiffer getOrCreateDiffer() {
IAnnotationModelExtension model= getModel();
if (model == null)
return null;
DocumentLineDiffer differ= (DocumentLineDiffer)model.getAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID);
if (differ == null)
differ= createDiffer(model);
return differ;
}
/**
* Returns the <code>IChangeRulerColumn</code> of this editor, or <code>null</code> if there is none. Either
* the line number bar or a separate change ruler column can be returned.
*
* @return an instance of <code>IChangeRulerColumn</code> or <code>null</code>.
* @since R3.0
*/
private IChangeRulerColumn getChangeColumn() {
if (fChangeRulerColumn != null)
return fChangeRulerColumn;
else if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
return (IChangeRulerColumn) fLineNumberRulerColumn;
else
return null;
}
/**
* Sets the display state of the separate change ruler column (not the quick diff display on
* the line number ruler column) to <code>show</code>.
*
* @param show <code>true</code> if the change ruler column should be shown, <code>false</code> if it should be hidden
* @since R3.0
*/
private void showChangeRuler(boolean show) {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
if (show && fChangeRulerColumn == null)
c.addDecorator(1, createChangeRulerColumn());
else if (!show && fChangeRulerColumn != null) {
c.removeDecorator(fChangeRulerColumn);
fChangeRulerColumn= null;
}
}
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
showChangeRuler(false);
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (fLineNumberRulerColumn != null && v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(fLineNumberRulerColumn);
fLineNumberRulerColumn= null;
}
if (fIsChangeInformationShown)
showChangeRuler(true);
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns whether quick diff info should be visible upon opening an editor
* according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
* @since R3.0
*/
private boolean isQuickDiffAlwaysOn() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PreferenceConstants.QUICK_DIFF_ALWAYS_ON);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @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(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
int lineOffset;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/**
* Initializes the given line number ruler column from the preference store.
*
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
rulerColumn.redraw();
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @return a new line number ruler column
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
if (isQuickDiffAlwaysOn() || isChangeInformationShowing()) {
LineNumberChangeRulerColumn column= new LineNumberChangeRulerColumn();
column.setHover(new JavaChangeHover());
initializeChangeRulerColumn(column);
fLineNumberRulerColumn= column;
} else {
fLineNumberRulerColumn= new LineNumberRulerColumn();
}
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/**
* Initializes the given change ruler column from the preference store.
*
* @param changeColumn the ruler column to be initialized
* @since R3.0
*/
private void initializeChangeRulerColumn(IChangeRulerColumn changeColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
ISourceViewer v= getSourceViewer();
if (v != null && v.getAnnotationModel() != null) {
changeColumn.setModel(v.getAnnotationModel());
}
rgb= null;
// change color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
}
}
changeColumn.setChangedColor(manager.getColor(rgb));
rgb= null;
// addition color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_ADDED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
}
}
changeColumn.setAddedColor(manager.getColor(rgb));
rgb= null;
// deletion indicator color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_DELETED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
}
}
changeColumn.setDeletedColor(manager.getColor(rgb));
}
changeColumn.redraw();
}
/**
* Creates a new change ruler column for quick diff display independent of the
* line number ruler column
*
* @return a new change ruler column
* @since R3.0
*/
protected IChangeRulerColumn createChangeRulerColumn() {
IChangeRulerColumn column= new ChangeRulerColumn();
column.setHover(new JavaChangeHover());
fChangeRulerColumn= column;
initializeChangeRulerColumn(fChangeRulerColumn);
return fChangeRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fSourceViewerDecorationSupport.install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
if (isQuickDiffAlwaysOn())
showChangeInformation(true);
}
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
protected void configureSourceViewerDecorationSupport() {
fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.UNKNOWN, UNKNOWN_INDICATION_COLOR, UNKNOWN_INDICATION, UNKNOWN_INDICATION_IN_OVERVIEW_RULER, 0);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.BOOKMARK, BOOKMARK_INDICATION_COLOR, BOOKMARK_INDICATION, BOOKMARK_INDICATION_IN_OVERVIEW_RULER, 1);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.TASK, TASK_INDICATION_COLOR, TASK_INDICATION, TASK_INDICATION_IN_OVERVIEW_RULER, 2);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.SEARCH, SEARCH_RESULT_INDICATION_COLOR, SEARCH_RESULT_INDICATION, SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, 3);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.WARNING, WARNING_INDICATION_COLOR, WARNING_INDICATION, WARNING_INDICATION_IN_OVERVIEW_RULER, 4);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.ERROR, ERROR_INDICATION_COLOR, ERROR_INDICATION, ERROR_INDICATION_IN_OVERVIEW_RULER, 5);
fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses 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);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
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;
}
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position errorPosition= new Position(0, 0);
IJavaAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition);
if (nextError != null) {
IMarker marker= null;
if (nextError instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextError).getMarker();
else {
Iterator e= nextError.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
setStatusLineErrorMessage(nextError.getMessage());
} else {
setStatusLineErrorMessage(null);
}
}
private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
IJavaAnnotation nextError= null;
Position nextErrorPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
if (a.hasOverlay() || !a.isProblem())
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= a;
nextErrorPosition= p;
}
}
}
if (nextErrorPosition != null) {
errorPosition.setOffset(nextErrorPosition.getOffset());
errorPosition.setLength(nextErrorPosition.getLength());
}
return nextError;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
}
|
40,780 |
Bug 40780 [plan item] Improve context views
|
Declaration View and Javadoc View should compute their contents in background Both should provide a context menu containing at least Copy and F3 (where available).
|
resolved fixed
|
697ab6b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-30T13:09:06Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/AbstractInfoView.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 org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.jface.action.IMenuListener;
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.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.search.SearchUtil;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Abstract class for views which show information for a given element.
*
* @since 3.0
*/
abstract class AbstractInfoView extends ViewPart implements ISelectionListener, IMenuListener {
/** JavaElementLabels flags used for the title */
private static final int TITLE_LABEL_FLAGS= JavaElementLabels.DEFAULT_QUALIFIED;
/** JavaElementLabels flags used for the tool tip text */
private static final int TOOLTIP_LABEL_FLAGS= JavaElementLabels.DEFAULT_QUALIFIED | JavaElementLabels.ROOT_POST_QUALIFIED | JavaElementLabels.APPEND_ROOT_PATH |
JavaElementLabels.M_PARAMETER_TYPES | JavaElementLabels.M_PARAMETER_NAMES | JavaElementLabels.M_APP_RETURNTYPE | JavaElementLabels.M_EXCEPTIONS |
JavaElementLabels.F_APP_TYPE_SIGNATURE;
/*
* @see IPartListener2
*/
private IPartListener2 fPartListener= new IPartListener2() {
public void partVisible(IWorkbenchPartReference ref) {
if (ref.getId().equals(getSite().getId())) {
IWorkbenchPart activePart= ref.getPage().getActivePart();
if (activePart != null)
selectionChanged(activePart, ref.getPage().getSelection());
startListeningForSelectionChanges();
}
}
public void partHidden(IWorkbenchPartReference ref) {
if (ref.getId().equals(getSite().getId()))
stopListeningForSelectionChanges();
}
public void partInputChanged(IWorkbenchPartReference ref) {
if (!ref.getId().equals(getSite().getId()))
setInputFrom(ref.getPart(false));
}
public void partActivated(IWorkbenchPartReference ref) {
}
public void partBroughtToTop(IWorkbenchPartReference ref) {
}
public void partClosed(IWorkbenchPartReference ref) {
}
public void partDeactivated(IWorkbenchPartReference ref) {
}
public void partOpened(IWorkbenchPartReference ref) {
}
};
/** The current input. */
protected IJavaElement fCurrentInput;
/** The copy to clipboard action. */
private SelectionDispatchAction fCopyToClipboardAction;
/** The goto input action. */
private GotoInputAction fGotoInputAction;
/**
* Set the input of this view.
*
* @param input the input object
* @return <code>true</code> if the input was set successfully
*/
abstract protected boolean setInput(Object input);
/**
* Create the part control.
*
* @param parent the parent control
* @see IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
abstract protected void internalCreatePartControl(Composite parent);
/**
* Set the view's foreground color.
*
* @param color the SWT color
*/
abstract protected void setForeground(Color color);
/**
* Set the view's background color.
*
* @param color the SWT color
*/
abstract protected void setBackground(Color color);
/**
* Returns the view's primary control.
*
* @return the primary control
*/
abstract Control getControl();
/*
* @see IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public final void createPartControl(Composite parent) {
internalCreatePartControl(parent);
setInfoColor();
getSite().getWorkbenchWindow().getPartService().addPartListener(fPartListener);
createContextMenu();
createActions();
fillActionBars(getViewSite().getActionBars());
}
/**
* Creates the actions and action groups for this view.
*/
protected void createActions() {
fGotoInputAction= new GotoInputAction(this);
fGotoInputAction.setEnabled(false);
fCopyToClipboardAction= new CopyToClipboardAction(getViewSite());
getSelectionProvider().addSelectionChangedListener(fCopyToClipboardAction);
}
/**
* Creates the context menu for this view.
*/
protected void createContextMenu() {
MenuManager menuManager= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(this);
Menu contextMenu= menuManager.createContextMenu(getControl());
getControl().setMenu(contextMenu);
getSite().registerContextMenu(menuManager, getSelectionProvider());
}
/*
* @see IMenuListener#menuAboutToShow(org.eclipse.jface.action.IMenuManager)
*/
public void menuAboutToShow(IMenuManager menu) {
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fCopyToClipboardAction);
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fGotoInputAction);
}
/**
* Returns the input of this view.
*
* @return input the input object or <code>null</code> if not input is set
*/
protected IJavaElement getInput() {
return fCurrentInput;
}
// Helper method
ISelectionProvider getSelectionProvider() {
return getViewSite().getSelectionProvider();
}
/**
* Fills the actions bars.
* <p>
* Subclasses may extend.
*/
protected void fillActionBars(IActionBars actionBars) {
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.COPY, fCopyToClipboardAction);
}
/**
* Fills the tool bar.
* <p>
* Default is to do nothing.</p>
*/
protected void fillToolBar(IToolBarManager tbm) {
tbm.add(fGotoInputAction);
}
/**
* Sets the foreground and background color to the corresponding SWT info color.
*/
private void setInfoColor() {
if (getSite().getShell().isDisposed())
return;
Display display= getSite().getShell().getDisplay();
if (display == null || display.isDisposed())
return;
setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
}
/**
* Start to listen for selection changes.
*/
protected void startListeningForSelectionChanges() {
getSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(this);
}
/**
* Stop to listen for selection changes.
*/
protected void stopListeningForSelectionChanges() {
getSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this);
}
/*
* @see ISelectionListener#selectionChanged(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
*/
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (part.equals(this))
return;
setInputFrom(part);
}
/**
* Tells whether the new input should be ignored
* if the current input is the same.
*
* @return <code>true</code> if the new input should be ignored
*/
protected boolean isIgnoringEqualInput() {
return true;
}
/**
* Finds and returns the Java element selected in the given part.
*
* @param part the workbench part for which to find the selected Java element
* @return the selected Java element
*/
protected IJavaElement findSelectedJavaElement(IWorkbenchPart part) {
Object element;
try {
IStructuredSelection sel= SelectionConverter.getStructuredSelection(part);
element= SelectionUtil.getSingleElement(sel);
} catch (JavaModelException e) {
return null;
}
return findJavaElement(element);
}
/**
* Tries to get a Java element out of the given element.
*
* @param element an object
* @return the Java element represented by the given element or <code>null</code>
*/
protected IJavaElement findJavaElement(Object element) {
if (SearchUtil.isISearchResultViewEntry(element)) {
IJavaElement je= SearchUtil.getJavaElement(element);
if (je != null)
return je;
element= SearchUtil.getResource(element);
}
IJavaElement je= null;
if (element instanceof IAdaptable)
je= (IJavaElement)((IAdaptable)element).getAdapter(IJavaElement.class);
if (je != null && je.getElementType() == IJavaElement.COMPILATION_UNIT)
je= WorkingCopyUtil.getWorkingCopyIfExists((ICompilationUnit)je);
return je;
}
/**
* Finds and returns the type for the given CU.
*
* @param cu the compilation unit
* @return the type with same name as the given CU or the first type in the CU
*/
protected IType getTypeForCU(ICompilationUnit cu) {
if (cu == null || !cu.exists())
return null;
cu= WorkingCopyUtil.getWorkingCopyIfExists(cu);
// Use primary type if possible
IType primaryType= cu.findPrimaryType();
if (primaryType != null)
return primaryType;
// Use first top-level type
try {
IType[] types= cu.getTypes();
if (types.length > 0)
return types[0];
else
return null;
} catch (JavaModelException ex) {
return null;
}
}
/**
* Sets this view's input based on the selection in the given part.
*
* @param part the part from which to get the selected Java element
*/
private void setInputFrom(IWorkbenchPart part) {
IJavaElement je= findSelectedJavaElement(part);
if (!isIgnoringEqualInput() && fCurrentInput != null && fCurrentInput.equals(je))
return;
if (!setInput(je))
return;
fCurrentInput= je;
fGotoInputAction.setEnabled(true);
String title= InfoViewMessages.getFormattedString("AbstractInfoView.compoundTitle", getSite().getRegisteredName(), JavaElementLabels.getElementLabel(je, TITLE_LABEL_FLAGS)); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(JavaElementLabels.getElementLabel(je, TOOLTIP_LABEL_FLAGS)); //$NON-NLS-1$//$NON-NLS-2$
}
/*
* @see IWorkbenchPart#dispose()
*/
final public void dispose() {
getSite().getWorkbenchWindow().getPartService().removePartListener(fPartListener);
getSelectionProvider().removeSelectionChangedListener(fCopyToClipboardAction);
internalDispose();
}
/*
* @see IWorkbenchPart#dispose()
*/
protected void internalDispose() {
}
}
|
40,780 |
Bug 40780 [plan item] Improve context views
|
Declaration View and Javadoc View should compute their contents in background Both should provide a context menu containing at least Copy and F3 (where available).
|
resolved fixed
|
697ab6b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-30T13:09:06Z | 2003-07-25T16:20: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.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
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.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.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
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.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
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.actions.SelectionConverter;
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.util.SelectionUtil;
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 styled 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;
/**
* The Javadoc view's select all action.
*/
private static class SelectAllAction extends Action {
/** The styled text widget. */
private StyledText fStyledText;
/** The selection provider. */
private SelectionProvider fSelectionProvider;
/**
* Creates the action.
*/
public SelectAllAction(StyledText styledText, SelectionProvider selectionProvider) {
super("selectAll"); //$NON-NLS-1$
Assert.isNotNull(styledText);
Assert.isNotNull(selectionProvider);
fStyledText= styledText;
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() {
fStyledText.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 styled text widget. */
private StyledText fStyledText;
/**
* Creates a new selection provider.
*
* @param styledText the styled text widget
*/
public SelectionProvider(StyledText styledText) {
Assert.isNotNull(styledText);
fStyledText= styledText;
fStyledText.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() {
IDocument document= new Document(fStyledText.getSelectionText());
return new TextSelection(document, 0, document.getLength());
}
/*
* @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) {
fText= new StyledText(parent, SWT.V_SCROLL | SWT.H_SCROLL);
fText.setEditable(false);
fPresenter= new HTMLTextPresenter(false);
getViewSite().setSelectionProvider(new SelectionProvider(fText));
}
/*
* @see AbstractInfoView#createActions()
*/
protected void createActions() {
super.createActions();
fSelectAllAction= new SelectAllAction(fText, (SelectionProvider)getSelectionProvider());
}
/*
* @see AbstractInfoView#setForeground(Color)
*/
protected void setForeground(Color color) {
fText.setForeground(color);
}
/*
* @see AbstractInfoView#setBackground(Color)
*/
protected void setBackground(Color color) {
fText.setBackground(color);
}
/*
* @see AbstractInfoView#internalDispose()
*/
protected void internalDispose() {
fText= null;
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
fText.setFocus();
}
/*
* @see AbstractInfoView#setInput(Object)
*/
protected boolean setInput(Object input) {
if (fText == null || ! (input instanceof IJavaElement))
return false;
IJavaElement je= (IJavaElement)input;
String javadocHtml= null;
if (je.getElementType() == IJavaElement.COMPILATION_UNIT) {
try {
javadocHtml= getJavadocHtml(((ICompilationUnit)je).getTypes());
} catch (JavaModelException ex) {
return false;
}
} else
javadocHtml= getJavadocHtml(new IJavaElement[] { je });
fPresentation.clear();
Point size= fText.getSize();
try {
javadocHtml= fPresenter.updatePresentation(getSite().getShell().getDisplay(), javadocHtml, fPresentation, size.x, size.y);
} catch (IllegalArgumentException ex) {
// the javadoc might no longer be valid
return false;
}
if (javadocHtml == null)
return false;
fText.setText(javadocHtml);
TextPresentation.applyTextPresentation(fPresentation, fText);
return true;
}
/**
* 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 > 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 AbstractInfoView#isUpdatingIfSameInput()
*/
protected boolean isIngoringEqualInput() {
return false;
}
/*
* @see AbstractInfoView#findSelectedJavaElement(IWorkbenchPart)
*/
protected IJavaElement findSelectedJavaElement(IWorkbenchPart part) {
Object element;
try {
IStructuredSelection sel= SelectionConverter.getStructuredSelection(part);
if (sel.isEmpty() && part instanceof JavaEditor) {
JavaEditor editor= (JavaEditor)part;
IDocument document= editor.getDocumentProvider().getDocument(editor.getEditorInput());
if (document == null)
return null;
ITypedRegion typedRegion= document.getPartition(((ITextSelection)editor.getSelectionProvider().getSelection()).getOffset());
if (IJavaPartitions.JAVA_DOC.equals(typedRegion.getType()))
element= SelectionConverter.getElementAtOffset((JavaEditor)part);
else
return null;
} else
element= SelectionUtil.getSingleElement(sel);
} catch (JavaModelException e) {
return null;
} catch (BadLocationException e) {
return null;
}
return findJavaElement(element);
}
/*
* @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(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
}
/*
* @see AbstractInfoView#getControl()
*/
protected Control getControl() {
return fText;
}
}
|
40,780 |
Bug 40780 [plan item] Improve context views
|
Declaration View and Javadoc View should compute their contents in background Both should provide a context menu containing at least Copy and F3 (where available).
|
resolved fixed
|
697ab6b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-30T13:09:06Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/SourceView.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.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.OpenAction;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
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.javaeditor.JavaSourceViewer;
import org.eclipse.jdt.internal.ui.text.JavaCodeReader;
/**
* View which shows source for a given Java element.
*
* @since 3.0
*/
public class SourceView extends AbstractInfoView implements IMenuListener {
/** Symbolic Java editor font name. */
private static final String SYMBOLIC_FONT_NAME= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$
/**
* Internal property change listener for handling workbench font changes.
*/
class FontPropertyChangeListener implements IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
String property= event.getProperty();
if (SYMBOLIC_FONT_NAME.equals(property))
setViewerFont();
}
}
/**
* The Javadoc view's select all action.
*/
private static class SelectAllAction extends Action {
private TextViewer fTextViewer;
/**
* Creates the action.
*/
public SelectAllAction(TextViewer textViewer) {
super("selectAll"); //$NON-NLS-1$
Assert.isNotNull(textViewer);
fTextViewer= textViewer;
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 viewer.
*/
public void run() {
fTextViewer.doOperation(ITextOperationTarget.SELECT_ALL);
}
}
/** This view's source viewer */
private SourceViewer fViewer;
/** The viewer's font properties change listener. */
private IPropertyChangeListener fFontPropertyChangeListener= new FontPropertyChangeListener();
/** The open action */
private OpenAction fOpen;
/** The number of removed leading comment lines. */
private int fCommentLineCount;
/** The select all action. */
private SelectAllAction fSelectAllAction;
/** Element opened by the open action. */
private IJavaElement fLastOpenedElement;
/*
* @see AbstractInfoView#internalCreatePartControl(Composite)
*/
protected void internalCreatePartControl(Composite parent) {
fViewer= new JavaSourceViewer(parent, null, null, false, SWT.V_SCROLL | SWT.H_SCROLL);
fViewer.configure(new JavaSourceViewerConfiguration(JavaPlugin.getDefault().getJavaTextTools(), null));
fViewer.setEditable(false);
setViewerFont();
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
getViewSite().setSelectionProvider(fViewer);
}
/*
* @see AbstractInfoView#internalCreatePartControl(Composite)
*/
protected void createActions() {
super.createActions();
fSelectAllAction= new SelectAllAction(fViewer);
// Setup OpenAction
fOpen= new OpenAction(getViewSite()) {
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#getSelection()
*/
public ISelection getSelection() {
return convertToJavaElementSelection(fViewer.getSelection());
}
/*
* @see org.eclipse.jdt.ui.actions.OpenAction#run(IStructuredSelection)
*/
public void run(IStructuredSelection selection) {
if (selection.isEmpty()) {
getShell().getDisplay().beep();
return;
}
super.run(selection);
}
/*
* @see org.eclipse.jdt.ui.actions.OpenAction#getElementToOpen(Object)
*/
public Object getElementToOpen(Object object) throws JavaModelException {
if (object instanceof IJavaElement)
fLastOpenedElement= (IJavaElement)object;
else
fLastOpenedElement= null;
return super.getElementToOpen(object);
}
/*
* @see org.eclipse.jdt.ui.actions.OpenAction#run(Object[])
*/
public void run(Object[] elements) {
stopListeningForSelectionChanges();
super.run(elements);
startListeningForSelectionChanges();
}
};
}
/*
* @see AbstractInfoView#fillActionBars(IActionBars)
*/
protected void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
actionBars.setGlobalActionHandler(JdtActionConstants.OPEN, fOpen);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
}
/*
* @see AbstractInfoView#getControl()
*/
protected Control getControl() {
return fViewer.getControl();
}
/*
* @see AbstractInfoView#menuAboutToShow(IMenuManager)
*/
public void menuAboutToShow(IMenuManager menu) {
super.menuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, fSelectAllAction);
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
}
/*
* @see AbstractInfoView#setForeground(Color)
*/
protected void setForeground(Color color) {
fViewer.getTextWidget().setForeground(color);
}
/*
* @see AbstractInfoView#setBackground(Color)
*/
protected void setBackground(Color color) {
fViewer.getTextWidget().setBackground(color);
}
/**
* Converts the given selection to a structured selection
* containing Java elements.
*
* @param selection the selection
* @return a structured selection with Java elements
*/
private IStructuredSelection convertToJavaElementSelection(ISelection selection) {
if (!(selection instanceof ITextSelection && fCurrentInput instanceof ISourceReference))
return StructuredSelection.EMPTY;
ITextSelection textSelection= (ITextSelection)selection;
Object codeAssist= fCurrentInput.getAncestor(IJavaElement.COMPILATION_UNIT);
if (codeAssist == null)
codeAssist= fCurrentInput.getAncestor(IJavaElement.CLASS_FILE);
if (codeAssist instanceof ICodeAssist) {
IJavaElement[] elements= null;
try {
ISourceRange range= ((ISourceReference)fCurrentInput).getSourceRange();
elements= ((ICodeAssist)codeAssist).codeSelect(range.getOffset() + getOffsetInUnclippedDocument(textSelection), textSelection.getLength());
} catch (JavaModelException e) {
return StructuredSelection.EMPTY;
}
if (elements != null && elements.length > 0) {
return new StructuredSelection(elements[0]);
} else
return StructuredSelection.EMPTY;
}
return StructuredSelection.EMPTY;
}
/**
* Computes and returns the offset in the unclipped document
* based on the given text selection from the clipped
* document.
*
* @param textSelection
* @return the offest in the unclipped document or <code>-1</code> if the offset cannot be computed
*/
private int getOffsetInUnclippedDocument(ITextSelection textSelection) {
IDocument unclippedDocument= null;
try {
unclippedDocument= new Document(((ISourceReference)fCurrentInput).getSource());
} catch (JavaModelException e) {
return -1;
}
IDocument clippedDoc= (IDocument)fViewer.getInput();
try {
IRegion unclippedLineInfo= unclippedDocument.getLineInformation(fCommentLineCount + textSelection.getStartLine());
IRegion clippedLineInfo= clippedDoc.getLineInformation(textSelection.getStartLine());
int removedIndentation= unclippedLineInfo.getLength() - clippedLineInfo.getLength();
int relativeLineOffset= textSelection.getOffset() - clippedLineInfo.getOffset();
return unclippedLineInfo.getOffset() + removedIndentation + relativeLineOffset ;
} catch (BadLocationException ex) {
return -1;
}
}
/*
* @see AbstractInfoView#internalDispose()
*/
protected void internalDispose() {
fViewer= null;
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
}
/*
* @see org.eclipse.ui.part.WorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTextWidget().setFocus();
}
/*
* @see AbstractInfoView#setInput(Object)
*/
protected boolean setInput(Object input) {
if (fViewer == null || !(input instanceof ISourceReference))
return false;
ISourceReference sourceRef= (ISourceReference)input;
if (fLastOpenedElement != null && input instanceof IJavaElement && ((IJavaElement)input).getHandleIdentifier().equals(fLastOpenedElement.getHandleIdentifier())) {
fLastOpenedElement= null;
return false;
} else {
fLastOpenedElement= null;
}
String source;
try {
source= sourceRef.getSource();
} catch (JavaModelException ex) {
return false;
}
if (source == null)
return false;
source= removeLeadingComments(source);
String delim= null;
try {
if (input instanceof IJavaElement)
delim= StubUtility.getLineDelimiterUsed((IJavaElement)input);
} catch (JavaModelException e) {
delim= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
String[] sourceLines= Strings.convertIntoLines(source);
String firstLine= sourceLines[0];
if (!Character.isWhitespace(firstLine.charAt(0)))
sourceLines[0]= ""; //$NON-NLS-1$
CodeFormatterUtil.removeIndentation(sourceLines);
if (!Character.isWhitespace(firstLine.charAt(0)))
sourceLines[0]= firstLine;
source= Strings.concatenate(sourceLines, delim);
IDocument doc= new Document(source);
IDocumentPartitioner dp= JavaPlugin.getDefault().getJavaTextTools().createDocumentPartitioner();
if (dp != null) {
doc.setDocumentPartitioner(dp);
dp.connect(doc);
}
fViewer.setInput(doc);
return true;
}
/**
* Removes the leading comments from the given source.
*
* @param source the string with the source
* @return the source without leading comments
*/
private String removeLeadingComments(String source) {
JavaCodeReader reader= new JavaCodeReader();
IDocument document= new Document(source);
int i;
try {
reader.configureForwardReader(document, 0, document.getLength(), true, false);
int c= reader.read();
while (c != -1 && (c == '\r' || c == '\n' || c == '\t')) {
c= reader.read();
}
i= reader.getOffset();
reader.close();
} catch (IOException ex) {
i= 0;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
JavaPlugin.log(ex);
}
}
try {
fCommentLineCount= document.getLineOfOffset(i);
} catch (BadLocationException e) {
fCommentLineCount= 0;
}
if (i < 0)
return source;
return source.substring(i);
}
/**
* Sets the font for this viewer sustaining selection and scroll position.
*/
private void setViewerFont() {
Font font= JFaceResources.getFont(SYMBOLIC_FONT_NAME);
if (fViewer.getDocument() != null) {
Point selection= fViewer.getSelectedRange();
int topIndex= fViewer.getTopIndex();
StyledText styledText= fViewer.getTextWidget();
Control parent= styledText;
if (fViewer instanceof ITextViewerExtension) {
ITextViewerExtension extension= (ITextViewerExtension) fViewer;
parent= extension.getControl();
}
parent.setRedraw(false);
styledText.setFont(font);
fViewer.setSelectedRange(selection.x , selection.y);
fViewer.setTopIndex(topIndex);
if (parent instanceof Composite) {
Composite composite= (Composite) parent;
composite.layout(true);
}
parent.setRedraw(true);
} else {
StyledText styledText= fViewer.getTextWidget();
styledText.setFont(font);
}
}
}
|
40,780 |
Bug 40780 [plan item] Improve context views
|
Declaration View and Javadoc View should compute their contents in background Both should provide a context menu containing at least Copy and F3 (where available).
|
resolved fixed
|
697ab6b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-30T13:09:06Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/infoviews/TextSelectionConverter.java
| |
40,350 |
Bug 40350 extract method: assertion failed [refactoring]
|
20030716 public class S { Object f(){ f(f(), f()); return null; } private void f(Object object, Object object2) { } } select 'f(), f()' extract method a java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Can only collapse statements at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.collapseNodes (ASTRewrite.java:444) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getTar getNode(ExtractMethodRefactoring.java:492) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create Change(ExtractMethodRefactoring.java:347) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (Unknown Source)
|
resolved fixed
|
ca4aaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:23:28Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/invalidSelection/A_test193.java
| |
40,350 |
Bug 40350 extract method: assertion failed [refactoring]
|
20030716 public class S { Object f(){ f(f(), f()); return null; } private void f(Object object, Object object2) { } } select 'f(), f()' extract method a java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Can only collapse statements at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.collapseNodes (ASTRewrite.java:444) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getTar getNode(ExtractMethodRefactoring.java:492) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create Change(ExtractMethodRefactoring.java:347) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (Unknown Source)
|
resolved fixed
|
ca4aaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:23:28Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
40,350 |
Bug 40350 extract method: assertion failed [refactoring]
|
20030716 public class S { Object f(){ f(f(), f()); return null; } private void f(Object object, Object object2) { } } select 'f(), f()' extract method a java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Can only collapse statements at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.collapseNodes (ASTRewrite.java:444) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getTar getNode(ExtractMethodRefactoring.java:492) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create Change(ExtractMethodRefactoring.java:347) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (Unknown Source)
|
resolved fixed
|
ca4aaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:23:28Z | 2003-07-17T13:53:20Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
| |
40,350 |
Bug 40350 extract method: assertion failed [refactoring]
|
20030716 public class S { Object f(){ f(f(), f()); return null; } private void f(Object object, Object object2) { } } select 'f(), f()' extract method a java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Can only collapse statements at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.collapseNodes (ASTRewrite.java:444) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getTar getNode(ExtractMethodRefactoring.java:492) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create Change(ExtractMethodRefactoring.java:347) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (Unknown Source)
|
resolved fixed
|
ca4aaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:23:28Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/core
| |
40,350 |
Bug 40350 extract method: assertion failed [refactoring]
|
20030716 public class S { Object f(){ f(f(), f()); return null; } private void f(Object object, Object object2) { } } select 'f(), f()' extract method a java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; Can only collapse statements at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.dom.ASTRewrite.collapseNodes (ASTRewrite.java:444) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getTar getNode(ExtractMethodRefactoring.java:492) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create Change(ExtractMethodRefactoring.java:347) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:104) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (Unknown Source)
|
resolved fixed
|
ca4aaa3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:23:28Z | 2003-07-17T13:53:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodAnalyzer.java
| |
40,352 |
Bug 40352 extract method: IllegalArgumentException
|
20030716 type space as the new method name in the extract method dialog the following is logged java.lang.IllegalArgumentException at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.core.dom.SimpleName.setIdentifier (SimpleName.java:125) at org.eclipse.jdt.core.dom.AST.newSimpleName(AST.java) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create NewMethod(ExtractMethodRefactoring.java:597) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getSig nature(ExtractMethodRefactoring.java:411) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.updatePrevie w(ExtractMethodInputPage.java:227) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.textModified (ExtractMethodInputPage.java:257) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.access$6 (ExtractMethodInputPage.java:255) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage$5.modifyText (ExtractMethodInputPage.java:193) 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.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:1825) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:3025) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Unknown Source) at org.eclipse.jface.window.Window.open(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:55) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run (ExtractMethodAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Unknown Source) at org.eclipse.ui.internal.commands.old.ActionHandler.execute(Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.pressed (Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.access$1(Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager$7.widgetSelected (Unknown Source) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent(Unknown Source) 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(Unknown Source) at org.eclipse.ui.internal.Workbench.run(Unknown Source) at org.eclipse.core.internal.boot.InternalBootLoader.run(Unknown Source) at org.eclipse.core.boot.BootLoader.run(Unknown Source) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Unknown Source) at org.eclipse.core.launcher.Main.run(Unknown Source) at org.eclipse.core.launcher.Main.main(Unknown Source)
|
resolved fixed
|
efa176a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:37:57Z | 2003-07-17T13:53:20Z |
org.eclipse.jdt.ui/ui
| |
40,352 |
Bug 40352 extract method: IllegalArgumentException
|
20030716 type space as the new method name in the extract method dialog the following is logged java.lang.IllegalArgumentException at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.core.dom.SimpleName.setIdentifier (SimpleName.java:125) at org.eclipse.jdt.core.dom.AST.newSimpleName(AST.java) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.create NewMethod(ExtractMethodRefactoring.java:597) at org.eclipse.jdt.internal.corext.refactoring.code.ExtractMethodRefactoring.getSig nature(ExtractMethodRefactoring.java:411) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.updatePrevie w(ExtractMethodInputPage.java:227) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.textModified (ExtractMethodInputPage.java:257) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage.access$6 (ExtractMethodInputPage.java:255) at org.eclipse.jdt.internal.ui.refactoring.code.ExtractMethodInputPage$5.modifyText (ExtractMethodInputPage.java:193) 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.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:1825) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:3025) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java) at org.eclipse.swt.widgets.Control.windowProc(Control.java) at org.eclipse.swt.widgets.Display.windowProc(Display.java) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java) at org.eclipse.jface.window.Window.runEventLoop(Unknown Source) at org.eclipse.jface.window.Window.open(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:55) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run (ExtractMethodAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Unknown Source) at org.eclipse.ui.internal.commands.old.ActionHandler.execute(Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.pressed (Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.access$1(Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager$7.widgetSelected (Unknown Source) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent(Unknown Source) 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(Unknown Source) at org.eclipse.ui.internal.Workbench.run(Unknown Source) at org.eclipse.core.internal.boot.InternalBootLoader.run(Unknown Source) at org.eclipse.core.boot.BootLoader.run(Unknown Source) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Unknown Source) at org.eclipse.core.launcher.Main.run(Unknown Source) at org.eclipse.core.launcher.Main.main(Unknown Source)
|
resolved fixed
|
efa176a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T14:37:57Z | 2003-07-17T13:53:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java
| |
40,885 |
Bug 40885 Extract Method Dialog: NPE from keyhandler in "Parameters" table [refactoring]
|
Build id: 200307230800, plugin-exports from20030729_0833 ### from Smoke Test, Refactoring: - have JUnit 3.8.1 as source project - In file junit.swingui.AboutDialog.java at the end of constructor AboutDialog(JFrame parent) select the following lines: constraintsLogo1.gridx = 2; constraintsLogo1.gridy = 0; constraintsLogo1.gridwidth = 1; constraintsLogo1.gridheight = 1; constraintsLogo1.anchor = GridBagConstraints.CENTER; getContentPane().add(logo, constraintsLogo1); - select Refactor > Extract Method... from the workbench menu ### new: - Click Button "Edit" - Click Button "Cancel" - Press any key (e.g. left arrow) - Result in Error log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl$5.keyReleased(ChangeParametersControl.java:296) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:124) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1675) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1671) at org.eclipse.swt.widgets.Control.WM_KEYUP(Control.java:3500) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2900) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:187) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
a2acecc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T15:16:27Z | 2003-07-29T12:00:00Z |
org.eclipse.jdt.ui/ui
| |
40,885 |
Bug 40885 Extract Method Dialog: NPE from keyhandler in "Parameters" table [refactoring]
|
Build id: 200307230800, plugin-exports from20030729_0833 ### from Smoke Test, Refactoring: - have JUnit 3.8.1 as source project - In file junit.swingui.AboutDialog.java at the end of constructor AboutDialog(JFrame parent) select the following lines: constraintsLogo1.gridx = 2; constraintsLogo1.gridy = 0; constraintsLogo1.gridwidth = 1; constraintsLogo1.gridheight = 1; constraintsLogo1.anchor = GridBagConstraints.CENTER; getContentPane().add(logo, constraintsLogo1); - select Refactor > Extract Method... from the workbench menu ### new: - Click Button "Edit" - Click Button "Cancel" - Press any key (e.g. left arrow) - Result in Error log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.refactoring.ChangeParametersControl$5.keyReleased(ChangeParametersControl.java:296) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:124) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:857) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1675) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1671) at org.eclipse.swt.widgets.Control.WM_KEYUP(Control.java:3500) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2900) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2713) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1338) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1876) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate(RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ExtractMethodAction.run(ExtractMethodAction.java:70) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:187) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent(WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:496) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:468) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
a2acecc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T15:16:27Z | 2003-07-29T12:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/callhierarchy/HistoryListAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* Jesper Kamstrup Linnet ([email protected]) - initial API and implementation
* (report 36180: Callers/Callees view)
******************************************************************************/
package org.eclipse.jdt.internal.ui.callhierarchy;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class HistoryListAction extends Action {
private class HistoryListDialog extends StatusDialog {
private ListDialogField fHistoryList;
private IStatus fHistoryStatus;
private IMethod fResult;
private HistoryListDialog(Shell shell, IMethod[] elements) {
super(shell);
setTitle(CallHierarchyMessages.getString("HistoryListDialog.title")); //$NON-NLS-1$
String[] buttonLabels= new String[] {
/* 0 */ CallHierarchyMessages.getString("HistoryListDialog.remove.button"), //$NON-NLS-1$
};
IListAdapter adapter= new IListAdapter() {
public void customButtonPressed(ListDialogField field, int index) {
doCustomButtonPressed();
}
public void selectionChanged(ListDialogField field) {
doSelectionChanged();
}
public void doubleClicked(ListDialogField field) {
doDoubleClicked();
}
};
JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT);
fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider);
fHistoryList.setLabelText(CallHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$
fHistoryList.setElements(Arrays.asList(elements));
ISelection sel;
if (elements.length > 0) {
sel= new StructuredSelection(elements[0]);
} else {
sel= new StructuredSelection();
}
fHistoryList.selectElements(sel);
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0);
LayoutUtil.setHeigthHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12));
LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null));
applyDialogFont(composite);
return composite;
}
/**
* Method doCustomButtonPressed.
*/
private void doCustomButtonPressed() {
fHistoryList.removeElements(fHistoryList.getSelectedElements());
}
private void doDoubleClicked() {
if (fHistoryStatus.isOK()) {
okPressed();
}
}
private void doSelectionChanged() {
StatusInfo status= new StatusInfo();
List selected= fHistoryList.getSelectedElements();
if (selected.size() != 1) {
status.setError(""); //$NON-NLS-1$
fResult= null;
} else {
fResult= (IMethod) selected.get(0);
}
fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size());
fHistoryStatus= status;
updateStatus(status);
}
public IMethod getResult() {
return fResult;
}
public IMethod[] getRemaining() {
List elems= fHistoryList.getElements();
return (IMethod[]) elems.toArray(new IMethod[elems.size()]);
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG);
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#create()
*/
public void create() {
setShellStyle(getShellStyle() | SWT.RESIZE);
super.create();
}
}
private CallHierarchyViewPart fView;
public HistoryListAction(CallHierarchyViewPart view) {
fView= view;
setText(CallHierarchyMessages.getString("HistoryListAction.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION);
}
/*
* @see IAction#run()
*/
public void run() {
IMethod[] historyEntries= fView.getHistoryEntries();
HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries);
if (dialog.open() == Window.OK) {
fView.setHistoryEntries(dialog.getRemaining());
fView.setMethod(dialog.getResult());
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarManifestWizardPage.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.jarpackager;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.filters.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.search.JavaSearchScopeFactory;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.MainMethodSearchEngine;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
/**
* Page 3 of the JAR Package wizard
*/
class JarManifestWizardPage extends WizardPage implements IJarPackageWizardPage {
// Untyped listener
private class UntypedListener implements Listener {
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
}
private UntypedListener fUntypedListener= new UntypedListener();
// Model
private JarPackageData fJarPackage;
// Cache for main types
private IType[] fMainTypes;
// Widgets
private Composite fManifestGroup;
private Button fGenerateManifestRadioButton;
private Button fSaveManifestCheckbox;
private Button fReuseManifestCheckbox;
private Text fNewManifestFileText;
private Label fNewManifestFileLabel;
private Button fNewManifestFileBrowseButton;
private Button fUseManifestRadioButton;
private Text fManifestFileText;
private Label fManifestFileLabel;
private Button fManifestFileBrowseButton;
private Label fSealingHeaderLabel;
private Button fSealJarRadioButton;
private Label fSealJarLabel;
private Button fSealedPackagesDetailsButton;
private Button fSealPackagesRadioButton;
private Label fSealPackagesLabel;
private Button fUnSealedPackagesDetailsButton;
private Label fMainClassHeaderLabel;
private Label fMainClassLabel;
private Text fMainClassText;
private Button fMainClassBrowseButton;
// Dialog store id constants
private final static String PAGE_NAME= "JarManifestWizardPage"; //$NON-NLS-1$
// Manifest creation
private final static String STORE_GENERATE_MANIFEST= PAGE_NAME + ".GENERATE_MANIFEST"; //$NON-NLS-1$
private final static String STORE_SAVE_MANIFEST= PAGE_NAME + ".SAVE_MANIFEST"; //$NON-NLS-1$
private final static String STORE_REUSE_MANIFEST= PAGE_NAME + ".REUSE_MANIFEST"; //$NON-NLS-1$
private final static String STORE_MANIFEST_LOCATION= PAGE_NAME + ".MANIFEST_LOCATION"; //$NON-NLS-1$
// Sealing
private final static String STORE_SEAL_JAR= PAGE_NAME + ".SEAL_JAR"; //$NON-NLS-1$
/**
* Create an instance of this class
*/
public JarManifestWizardPage(JarPackageData jarPackage) {
super(PAGE_NAME);
setTitle(JarPackagerMessages.getString("JarManifestWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarManifestWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
}
// ----------- Widget creation -----------
/*
* Method declared on IDialogPage.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
Composite composite= new Composite(parent, SWT.NULL);
composite.setLayout(new GridLayout());
composite.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_FILL | GridData.HORIZONTAL_ALIGN_FILL));
createLabel(composite, JarPackagerMessages.getString("JarManifestWizardPage.manifestSource.label"), false); //$NON-NLS-1$
createManifestGroup(composite);
createSpacer(composite);
fSealingHeaderLabel= createLabel(composite, JarPackagerMessages.getString("JarManifestWizardPage.sealingHeader.label"), false); //$NON-NLS-1$
createSealingGroup(composite);
createSpacer(composite);
fMainClassHeaderLabel= createLabel(composite, JarPackagerMessages.getString("JarManifestWizardPage.mainClassHeader.label"), false); //$NON-NLS-1$
createMainClassGroup(composite);
setEqualButtonSizes();
restoreWidgetValues();
setControl(composite);
update();
Dialog.applyDialogFont(composite);
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JARMANIFEST_WIZARD_PAGE);
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createManifestGroup(Composite parent) {
fManifestGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
fManifestGroup.setLayout(layout);
fManifestGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fGenerateManifestRadioButton= new Button(fManifestGroup, SWT.RADIO | SWT.LEFT);
fGenerateManifestRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.genetateManifest.text")); //$NON-NLS-1$
fGenerateManifestRadioButton.addListener(SWT.Selection, fUntypedListener);
Composite saveOptions= new Composite(fManifestGroup, SWT.NONE);
GridLayout saveOptionsLayout= new GridLayout();
saveOptionsLayout.marginWidth= 0;
saveOptions.setLayout(saveOptionsLayout);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.horizontalIndent=20;
saveOptions.setLayoutData(data);
fSaveManifestCheckbox= new Button(saveOptions, SWT.CHECK | SWT.LEFT);
fSaveManifestCheckbox.setText(JarPackagerMessages.getString("JarManifestWizardPage.saveManifest.text")); //$NON-NLS-1$
fSaveManifestCheckbox.addListener(SWT.MouseUp, fUntypedListener);
fReuseManifestCheckbox= new Button(saveOptions, SWT.CHECK | SWT.LEFT);
fReuseManifestCheckbox.setText(JarPackagerMessages.getString("JarManifestWizardPage.reuseManifest.text")); //$NON-NLS-1$
fReuseManifestCheckbox.addListener(SWT.MouseUp, fUntypedListener);
createNewManifestFileGroup(saveOptions);
fUseManifestRadioButton= new Button(fManifestGroup, SWT.RADIO | SWT.LEFT);
fUseManifestRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.useManifest.text")); //$NON-NLS-1$
fUseManifestRadioButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
Composite existingManifestGroup= new Composite(fManifestGroup, SWT.NONE);
GridLayout existingManifestLayout= new GridLayout();
existingManifestLayout.marginWidth= 0;
existingManifestGroup.setLayout(existingManifestLayout);
data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.horizontalIndent=20;
existingManifestGroup.setLayoutData(data);
createManifestFileGroup(existingManifestGroup);
}
protected void createNewManifestFileGroup(Composite parent) {
// destination specification group
Composite manifestFileGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 3;
manifestFileGroup.setLayout(layout);
manifestFileGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fNewManifestFileLabel= new Label(manifestFileGroup, SWT.NONE);
fNewManifestFileLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.newManifestFile.text")); //$NON-NLS-1$
// entry field
fNewManifestFileText= new Text(manifestFileGroup, SWT.SINGLE | SWT.BORDER);
fNewManifestFileText.addListener(SWT.Modify, fUntypedListener);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(40);
fNewManifestFileText.setLayoutData(data);
// browse button
fNewManifestFileBrowseButton= new Button(manifestFileGroup, SWT.PUSH);
fNewManifestFileBrowseButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.newManifestFileBrowseButton.text")); //$NON-NLS-1$
fNewManifestFileBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fNewManifestFileBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleNewManifestFileBrowseButtonPressed();
}
});
}
protected void createManifestFileGroup(Composite parent) {
// destination specification group
Composite manifestFileGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
manifestFileGroup.setLayout(layout);
manifestFileGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fManifestFileLabel= new Label(manifestFileGroup, SWT.NONE);
fManifestFileLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.manifestFile.text")); //$NON-NLS-1$
// entry field
fManifestFileText= new Text(manifestFileGroup, SWT.SINGLE | SWT.BORDER);
fManifestFileText.addListener(SWT.Modify, fUntypedListener);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(40);
fManifestFileText.setLayoutData(data);
// browse button
fManifestFileBrowseButton= new Button(manifestFileGroup, SWT.PUSH);
fManifestFileBrowseButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.manifestFileBrowse.text")); //$NON-NLS-1$
fManifestFileBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fManifestFileBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleManifestFileBrowseButtonPressed();
}
});
}
/**
* Creates the JAR sealing specification controls.
*
* @param parent the parent control
*/
protected void createSealingGroup(Composite parent) {
// destination specification group
Composite sealingGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
layout.horizontalSpacing += 3;
sealingGroup.setLayout(layout);
sealingGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
createSealJarGroup(sealingGroup);
createSealPackagesGroup(sealingGroup);
}
/**
* Creates the JAR sealing specification controls to seal the whole JAR.
*
* @param parent the parent control
*/
protected void createSealJarGroup(Composite sealGroup) {
fSealJarRadioButton= new Button(sealGroup, SWT.RADIO);
fSealJarRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.sealJar.text")); //$NON-NLS-1$
fSealJarRadioButton.addListener(SWT.Selection, fUntypedListener);
fSealJarLabel= new Label(sealGroup, SWT.RIGHT);
fSealJarLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fSealJarLabel.setText(""); //$NON-NLS-1$
fUnSealedPackagesDetailsButton= new Button(sealGroup, SWT.PUSH);
fUnSealedPackagesDetailsButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fUnSealedPackagesDetailsButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.unsealPackagesButton.text")); //$NON-NLS-1$
fUnSealedPackagesDetailsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleUnSealPackagesDetailsButtonPressed();
}
});
}
/**
* Creates the JAR sealing specification controls to seal packages.
*
* @param parent the parent control
*/
protected void createSealPackagesGroup(Composite sealGroup) {
fSealPackagesRadioButton= new Button(sealGroup, SWT.RADIO);
fSealPackagesRadioButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.sealPackagesButton.text")); //$NON-NLS-1$
fSealPackagesLabel= new Label(sealGroup, SWT.RIGHT);
fSealPackagesLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL));
fSealPackagesLabel.setText(""); //$NON-NLS-1$
fSealedPackagesDetailsButton= new Button(sealGroup, SWT.PUSH);
fSealedPackagesDetailsButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fSealedPackagesDetailsButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.sealedPackagesDetailsButton.text")); //$NON-NLS-1$
fSealedPackagesDetailsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleSealPackagesDetailsButtonPressed();
}
});
}
protected void createMainClassGroup(Composite parent) {
// main type group
Composite mainClassGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
mainClassGroup.setLayout(layout);
mainClassGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
fMainClassLabel= new Label(mainClassGroup, SWT.NONE);
fMainClassLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.mainClass.label")); //$NON-NLS-1$
// entry field
fMainClassText= new Text(mainClassGroup, SWT.SINGLE | SWT.BORDER);
fMainClassText.addListener(SWT.Modify, fUntypedListener);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= convertWidthInCharsToPixels(40);
fMainClassText.setLayoutData(data);
fMainClassText.addKeyListener(new KeyAdapter() {
/*
* @see KeyListener#keyReleased(KeyEvent)
*/
public void keyReleased(KeyEvent e) {
fJarPackage.setManifestMainClass(findMainMethodByName(fMainClassText.getText()));
update();
}
});
// browse button
fMainClassBrowseButton= new Button(mainClassGroup, SWT.PUSH);
fMainClassBrowseButton.setText(JarPackagerMessages.getString("JarManifestWizardPage.mainClassBrowseButton.text")); //$NON-NLS-1$
fMainClassBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
fMainClassBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleMainClassBrowseButtonPressed();
}
});
}
// ----------- Event handlers -----------
private void update() {
updateModel();
updateEnableState();
updatePageCompletion();
}
/**
* Open an appropriate dialog so that the user can specify a manifest
* to save
*/
protected void handleNewManifestFileBrowseButtonPressed() {
// Use Save As dialog to select a new file inside the workspace
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarManifestWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getManifestLocation()));
if (dialog.open() == Window.OK) {
fJarPackage.setManifestLocation(dialog.getResult());
fNewManifestFileText.setText(dialog.getResult().toString());
}
}
protected void handleManifestFileBrowseButtonPressed() {
ElementTreeSelectionDialog dialog= createWorkspaceFileSelectionDialog(JarPackagerMessages.getString("JarManifestWizardPage.manifestSelectionDialog.title"), JarPackagerMessages.getString("JarManifestWizardPage.manifestSelectionDialog.message")); //$NON-NLS-2$ //$NON-NLS-1$
if (fJarPackage.isManifestAccessible())
dialog.setInitialSelections(new IResource[] {fJarPackage.getManifestFile()});
if (dialog.open() == Window.OK) {
Object[] resources= dialog.getResult();
if (resources.length != 1)
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.onlyOneManifestMustBeSelected")); //$NON-NLS-1$
else {
setErrorMessage(""); //$NON-NLS-1$
fJarPackage.setManifestLocation(((IResource)resources[0]).getFullPath());
fManifestFileText.setText(fJarPackage.getManifestLocation().toString());
}
}
}
private IType findMainMethodByName(String name) {
if (fMainTypes == null) {
List resources= JarPackagerUtil.asResources(fJarPackage.getElements());
if (resources == null)
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.noResourceSelected")); //$NON-NLS-1$
IJavaSearchScope searchScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope((IResource[])resources.toArray(new IResource[resources.size()]));
MainMethodSearchEngine engine= new MainMethodSearchEngine();
try {
fMainTypes= engine.searchMainMethods(getContainer(), searchScope, 0);
} catch (InvocationTargetException ex) {
// null
} catch (InterruptedException e) {
// null
}
}
for (int i= 0; i < fMainTypes.length; i++) {
if (fMainTypes[i].getFullyQualifiedName().equals(name))
return fMainTypes[i];
}
return null;
}
protected void handleMainClassBrowseButtonPressed() {
List resources= JarPackagerUtil.asResources(fJarPackage.getElements());
if (resources == null) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.noResourceSelected")); //$NON-NLS-1$
return;
}
IJavaSearchScope searchScope= JavaSearchScopeFactory.getInstance().createJavaSearchScope((IResource[])resources.toArray(new IResource[resources.size()]));
SelectionDialog dialog= JavaUI.createMainTypeDialog(getContainer().getShell(), getContainer(), searchScope, 0, false, ""); //$NON-NLS-1$
dialog.setTitle(JarPackagerMessages.getString("JarManifestWizardPage.mainTypeSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.mainTypeSelectionDialog.message")); //$NON-NLS-1$
if (fJarPackage.getManifestMainClass() != null)
dialog.setInitialSelections(new Object[] {fJarPackage.getManifestMainClass()});
if (dialog.open() == Window.OK) {
fJarPackage.setManifestMainClass((IType)dialog.getResult()[0]);
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
} else if (!fJarPackage.isMainClassValid(getContainer())) {
// user did not cancel: no types were found
fJarPackage.setManifestMainClass(null);
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
}
}
protected void handleSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(getPackagesForSelectedResources(fJarPackage));
dialog.setTitle(JarPackagerMessages.getString("JarManifestWizardPage.sealedPackagesSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.sealedPackagesSelectionDialog.message")); //$NON-NLS-1$
dialog.setInitialSelections(fJarPackage.getPackagesToSeal());
if (dialog.open() == Window.OK)
fJarPackage.setPackagesToSeal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
protected void handleUnSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(getPackagesForSelectedResources(fJarPackage));
dialog.setTitle(JarPackagerMessages.getString("JarManifestWizardPage.unsealedPackagesSelectionDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarManifestWizardPage.unsealedPackagesSelectionDialog.message")); //$NON-NLS-1$
dialog.setInitialSelections(fJarPackage.getPackagesToUnseal());
if (dialog.open() == Window.OK)
fJarPackage.setPackagesToUnseal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
/**
* Updates the enable state of this page's controls. Subclasses may extend.
*/
protected void updateEnableState() {
boolean generate= fGenerateManifestRadioButton.getSelection();
boolean save= generate && fSaveManifestCheckbox.getSelection();
fSaveManifestCheckbox.setEnabled(generate);
fReuseManifestCheckbox.setEnabled(fJarPackage.isDescriptionSaved() && save);
fNewManifestFileText.setEnabled(save);
fNewManifestFileLabel.setEnabled(save);
fNewManifestFileBrowseButton.setEnabled(save);
fManifestFileText.setEnabled(!generate);
fManifestFileLabel.setEnabled(!generate);
fManifestFileBrowseButton.setEnabled(!generate);
fSealingHeaderLabel.setEnabled(generate);
boolean sealState= fSealJarRadioButton.getSelection();
fSealJarRadioButton.setEnabled(generate);
fSealJarLabel.setEnabled(generate);
fUnSealedPackagesDetailsButton.setEnabled(sealState && generate);
fSealPackagesRadioButton.setEnabled(generate);
fSealPackagesLabel.setEnabled(generate);
fSealedPackagesDetailsButton.setEnabled(!sealState && generate);
fMainClassHeaderLabel.setEnabled(generate);
fMainClassLabel.setEnabled(generate);
fMainClassText.setEnabled(generate);
fMainClassBrowseButton.setEnabled(generate);
updateSealingInfo();
}
protected void updateSealingInfo() {
if (fJarPackage.isJarSealed()) {
fSealPackagesLabel.setText(""); //$NON-NLS-1$
int i= fJarPackage.getPackagesToUnseal().length;
if (i == 0)
fSealJarLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.jarSealed")); //$NON-NLS-1$
else if (i == 1)
fSealJarLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.jarSealedExceptOne")); //$NON-NLS-1$
else
fSealJarLabel.setText(JarPackagerMessages.getFormattedString("JarManifestWizardPage.jarSealedExceptSome", new Integer(i))); //$NON-NLS-1$
}
else {
fSealJarLabel.setText(""); //$NON-NLS-1$
int i= fJarPackage.getPackagesToSeal().length;
if (i == 0)
fSealPackagesLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.nothingSealed")); //$NON-NLS-1$
else if (i == 1)
fSealPackagesLabel.setText(JarPackagerMessages.getString("JarManifestWizardPage.onePackageSealed")); //$NON-NLS-1$
else
fSealPackagesLabel.setText(JarPackagerMessages.getFormattedString("JarManifestWizardPage.somePackagesSealed", new Integer(i))); //$NON-NLS-1$
}
}
/*
* Implements method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
boolean isPageComplete= true;
setMessage(null);
if (!fJarPackage.areClassFilesExported())
return true;
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
if (fJarPackage.getManifestLocation().toString().length() == 0)
isPageComplete= false;
else {
IPath location= fJarPackage.getManifestLocation();
if (!location.toString().startsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.manifestPathMustBeAbsolute")); //$NON-NLS-1$
return false;
}
IResource resource= findResource(location);
if (resource != null && resource.getType() != IResource.FILE) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.manifestMustNotBeExistingContainer")); //$NON-NLS-1$
return false;
}
resource= findResource(location.removeLastSegments(1));
if (resource == null || resource.getType() == IResource.FILE) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.manifestContainerDoesNotExist")); //$NON-NLS-1$
return false;
}
}
}
if (!fJarPackage.isManifestGenerated()) {
if (fJarPackage.isManifestAccessible()) {
Manifest manifest= null;
try {
manifest= fJarPackage.getManifestProvider().create(fJarPackage);
} catch (CoreException ex) {
// nothing reported in the wizard
}
if (manifest != null && manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION) == null)
setMessage(JarPackagerMessages.getString("JarManifestWizardPage.warning.noManifestVersion"), IMessageProvider.WARNING); //$NON-NLS-1$
} else {
if (fJarPackage.getManifestLocation().toString().length() == 0)
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.noManifestFile")); //$NON-NLS-1$
else
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.invalidManifestFile")); //$NON-NLS-1$
return false;
}
}
Set selectedPackages= getPackagesForSelectedResources(fJarPackage);
if (fJarPackage.isJarSealed()
&& !selectedPackages.containsAll(Arrays.asList(fJarPackage.getPackagesToUnseal()))) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.unsealedPackagesNotInSelection")); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isJarSealed()
&& !selectedPackages.containsAll(Arrays.asList(fJarPackage.getPackagesToSeal()))) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.sealedPackagesNotInSelection")); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(getContainer()) || (fJarPackage.getManifestMainClass() == null && fMainClassText.getText().length() > 0)) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.invalidMainClass")); //$NON-NLS-1$
return false;
}
setErrorMessage(null);
return isPageComplete;
}
/*
* Implements method from IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
fMainTypes= null;
updateEnableState();
if (getContainer() != null)
updatePageCompletion();
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
// ----------- Model handling -----------
/**
* Persists resource specification control setting that are to be restored
* in the next instance of this page. Subclasses wishing to persist
* settings for their controls should extend the hook method
* <code>internalSaveWidgetValues</code>.
*/
public final void saveWidgetValues() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// Manifest creation
settings.put(STORE_GENERATE_MANIFEST, fJarPackage.isManifestGenerated());
settings.put(STORE_SAVE_MANIFEST, fJarPackage.isManifestSaved());
settings.put(STORE_REUSE_MANIFEST, fJarPackage.isManifestReused());
settings.put(STORE_MANIFEST_LOCATION, fJarPackage.getManifestLocation().toString());
// Sealing
settings.put(STORE_SEAL_JAR, fJarPackage.isJarSealed());
}
// Allow subclasses to save values
internalSaveWidgetValues();
}
/**
* Hook method for subclasses to persist their settings.
*/
protected void internalSaveWidgetValues() {
}
/**
* Hook method for restoring widget values to the values that they held
* last time this wizard was used to completion.
*/
protected void restoreWidgetValues() {
if (!((JarPackageWizard)getWizard()).isInitializingFromJarPackage())
initializeJarPackage();
// Manifest creation
if (fJarPackage.isManifestGenerated())
fGenerateManifestRadioButton.setSelection(true);
else
fUseManifestRadioButton.setSelection(true);
fSaveManifestCheckbox.setSelection(fJarPackage.isManifestSaved());
fReuseManifestCheckbox.setSelection(fJarPackage.isManifestReused());
fManifestFileText.setText(fJarPackage.getManifestLocation().toString());
fNewManifestFileText.setText(fJarPackage.getManifestLocation().toString());
// Sealing
if (fJarPackage.isJarSealed())
fSealJarRadioButton.setSelection(true);
else
fSealPackagesRadioButton.setSelection(true);
// Main-Class
fMainClassText.setText(JarPackagerUtil.getMainClassName(fJarPackage));
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// Manifest creation
fJarPackage.setGenerateManifest(settings.getBoolean(STORE_GENERATE_MANIFEST));
fJarPackage.setSaveManifest(settings.getBoolean(STORE_SAVE_MANIFEST));
fJarPackage.setReuseManifest(settings.getBoolean(STORE_REUSE_MANIFEST));
String pathStr= settings.get(STORE_MANIFEST_LOCATION);
if (pathStr == null)
pathStr= ""; //$NON-NLS-1$
fJarPackage.setManifestLocation(new Path(pathStr));
// Sealing
fJarPackage.setSealJar(settings.getBoolean(STORE_SEAL_JAR));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// Manifest creation
fJarPackage.setGenerateManifest(fGenerateManifestRadioButton.getSelection());
fJarPackage.setSaveManifest(fSaveManifestCheckbox.getSelection());
fJarPackage.setReuseManifest(fReuseManifestCheckbox.getSelection());
String path;
if (fJarPackage.isManifestGenerated())
path= fNewManifestFileText.getText();
else
path= fManifestFileText.getText();
if (path == null)
path= ""; //$NON-NLS-1$
fJarPackage.setManifestLocation(new Path(path));
// Sealing
fJarPackage.setSealJar(fSealJarRadioButton.getSelection());
}
/**
* Determine if the page is complete and update the page appropriately.
*/
protected void updatePageCompletion() {
boolean pageComplete= isPageComplete();
setPageComplete(pageComplete);
if (pageComplete) {
setErrorMessage(null);
}
}
// ----------- Utility methods -----------
/**
* Creates a file resource handle for the file with the given workspace path.
* This method does not create the file resource; this is the responsibility
* of <code>createFile</code>.
*
* @param filePath the path of the file resource to create a handle for
* @return the new file resource handle
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return JavaPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Creates a new label with a bold font.
*
* @param parent the parent control
* @param text the label text
* @return the new label control
*/
protected Label createLabel(Composite parent, String text, boolean bold) {
Label label= new Label(parent, SWT.NONE);
if (bold)
label.setFont(JFaceResources.getBannerFont());
label.setText(text);
GridData data= new GridData();
data.verticalAlignment= GridData.FILL;
data.horizontalAlignment= GridData.FILL;
label.setLayoutData(data);
return label;
}
/**
* Sets the size of a control.
*
* @param control the control for which to set the size
* @param width the new width of the control
* @param height the new height of the control
*/
protected void setSize(Control control, int width, int height) {
GridData gd= new GridData(GridData.END);
gd.widthHint= width ;
gd.heightHint= height;
control.setLayoutData(gd);
}
/**
* Makes the size of all buttons equal.
*/
protected void setEqualButtonSizes() {
int width= SWTUtil.getButtonWidthHint(fManifestFileBrowseButton);
int height= SWTUtil.getButtonHeigthHint(fManifestFileBrowseButton);
int width2= SWTUtil.getButtonWidthHint(fNewManifestFileBrowseButton);
int height2= SWTUtil.getButtonHeigthHint(fNewManifestFileBrowseButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
width2= SWTUtil.getButtonWidthHint(fSealedPackagesDetailsButton);
height2= SWTUtil.getButtonHeigthHint(fSealedPackagesDetailsButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
width2= SWTUtil.getButtonWidthHint(fUnSealedPackagesDetailsButton);
height2= SWTUtil.getButtonHeigthHint(fUnSealedPackagesDetailsButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
width2= SWTUtil.getButtonWidthHint(fMainClassBrowseButton);
height2= SWTUtil.getButtonHeigthHint(fMainClassBrowseButton);
width= Math.max(width, width2);
height= Math.max(height, height2);
setSize(fManifestFileBrowseButton, width, height);
setSize(fNewManifestFileBrowseButton, width, height);
setSize(fSealedPackagesDetailsButton, width, height);
setSize(fUnSealedPackagesDetailsButton, width, height);
setSize(fMainClassBrowseButton, width, height);
}
/**
* Creates a horizontal spacer line that fills the width of its container.
*
* @param parent the parent control
*/
protected void createSpacer(Composite parent) {
Label spacer= new Label(parent, SWT.NONE);
GridData data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
spacer.setLayoutData(data);
}
/**
* Returns the resource for the specified path.
*
* @param path the path for which the resource should be returned
* @return the resource specified by the path or <code>null</code>
*/
protected IResource findResource(IPath path) {
IWorkspace workspace= JavaPlugin.getWorkspace();
IStatus result= workspace.validatePath(
path.toString(),
IResource.ROOT | IResource.PROJECT | IResource.FOLDER | IResource.FILE);
if (result.isOK() && workspace.getRoot().exists(path))
return workspace.getRoot().findMember(path);
return null;
}
protected IPath getPathFromString(String text) {
return new Path(text).makeAbsolute();
}
/**
* Creates a selection dialog that lists all packages under the given package
* fragment root.
* The caller is responsible for opening the dialog with <code>Window.open</code>,
* and subsequently extracting the selected packages (of type
* <code>IPackageFragment</code>) via <code>SelectionDialog.getResult</code>.
*
* @param packageFragments the package fragments
* @return a new selection dialog
*/
protected SelectionDialog createPackageDialog(Set packageFragments) {
List packages= new ArrayList(packageFragments.size());
for (Iterator iter= packageFragments.iterator(); iter.hasNext();) {
IPackageFragment fragment= (IPackageFragment)iter.next();
boolean containsJavaElements= false;
int kind;
try {
kind= fragment.getKind();
containsJavaElements= fragment.getChildren().length > 0;
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, getContainer().getShell(), JarPackagerMessages.getString("JarManifestWizardPage.error.jarPackageWizardError.title"), JarPackagerMessages.getFormattedString("JarManifestWizardPage.error.jarPackageWizardError.message", fragment.getElementName())); //$NON-NLS-2$ //$NON-NLS-1$
continue;
}
if (kind != IPackageFragmentRoot.K_BINARY && containsJavaElements)
packages.add(fragment);
}
StandardJavaElementContentProvider cp= new StandardJavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getContainer().getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT), cp);
dialog.setDoubleClickSelects(false);
dialog.setInput(JavaCore.create(JavaPlugin.getWorkspace().getRoot()));
dialog.addFilter(new EmptyInnerPackageFilter());
dialog.addFilter(new LibraryFilter());
dialog.addFilter(new SealPackagesFilter(packages));
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
StatusInfo res= new StatusInfo();
for (int i= 0; i < selection.length; i++) {
if (!(selection[i] instanceof IPackageFragment)) {
res.setError(JarPackagerMessages.getString("JarManifestWizardPage.error.mustContainPackages")); //$NON-NLS-1$
return res;
}
}
res.setOK();
return res;
}
});
return dialog;
}
/**
* Converts selection dialog results into an array of IPackageFragments.
* An empty array is returned in case of errors.
* @throws ClassCastException if results are not IPackageFragments
*/
protected IPackageFragment[] getPackagesFromDialog(SelectionDialog dialog) {
if (dialog.getReturnCode() == Window.OK && dialog.getResult().length > 0)
return (IPackageFragment[])Arrays.asList(dialog.getResult()).toArray(new IPackageFragment[dialog.getResult().length]);
else
return new IPackageFragment[0];
}
/**
* Creates and returns a dialog to choose an existing workspace file.
*/
protected ElementTreeSelectionDialog createWorkspaceFileSelectionDialog(String title, String message) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider contentProvider= new StandardJavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(labelFlags);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider);
dialog.setAllowMultiple(false);
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
StatusInfo res= new StatusInfo();
// only single selection
if (selection.length == 1 && (selection[0] instanceof IFile))
res.setOK();
else
res.setError(""); //$NON-NLS-1$
return res;
}
});
dialog.addFilter(new EmptyInnerPackageFilter());
dialog.addFilter(new LibraryFilter());
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setStatusLineAboveButtons(true);
dialog.setInput(JavaCore.create(JavaPlugin.getWorkspace().getRoot()));
return dialog;
}
/**
* Returns the minimal set of packages which contain all the selected Java resources.
* @return the Set of IPackageFragments which contain all the selected resources
*/
private Set getPackagesForSelectedResources(JarPackageData jarPackage) {
Set packages= new HashSet();
int n= fJarPackage.getElements().length;
for (int i= 0; i < n; i++) {
Object element= fJarPackage.getElements()[i];
if (element instanceof ICompilationUnit) {
IJavaElement pack= JarPackagerUtil.findParentOfKind((IJavaElement)element, org.eclipse.jdt.core.IJavaElement.PACKAGE_FRAGMENT);
if (pack != null)
packages.add(pack);
}
}
return packages;
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.template.ContextType;
import org.eclipse.jdt.internal.corext.template.ContextTypeRegistry;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.corext.template.TemplateVariable;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.text.JavaWordFinder;
import org.eclipse.jdt.internal.ui.text.template.TemplateVariableProcessor;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* Dialog to edit a template.
*/
public class EditTemplateDialog extends StatusDialog {
private static class SimpleJavaSourceViewerConfiguration extends JavaSourceViewerConfiguration {
private final TemplateVariableProcessor fProcessor;
SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, TemplateVariableProcessor processor) {
super(tools, editor);
fProcessor= processor;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
ContentAssistant assistant= new ContentAssistant();
assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE);
// Register the same processor for strings and single line comments to get code completion at the start of those partitions.
assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_STRING);
assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_CHARACTER);
assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT);
assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_MULTI_LINE_COMMENT);
assistant.setContentAssistProcessor(fProcessor, IJavaPartitions.JAVA_DOC);
assistant.enableAutoInsert(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOINSERT));
assistant.enableAutoActivation(store.getBoolean(PreferenceConstants.CODEASSIST_AUTOACTIVATION));
assistant.setAutoActivationDelay(store.getInt(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY));
assistant.setProposalPopupOrientation(ContentAssistant.PROPOSAL_OVERLAY);
assistant.setContextInformationPopupOrientation(ContentAssistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
Color background= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, manager);
assistant.setContextInformationPopupBackground(background);
assistant.setContextSelectorBackground(background);
assistant.setProposalSelectorBackground(background);
Color foreground= getColor(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, manager);
assistant.setContextInformationPopupForeground(foreground);
assistant.setContextSelectorForeground(foreground);
assistant.setProposalSelectorForeground(foreground);
return assistant;
}
private Color getColor(IPreferenceStore store, String key, IColorManager manager) {
RGB rgb= PreferenceConverter.getColor(store, key);
return manager.getColor(rgb);
}
/*
* @see SourceViewerConfiguration#getTextHover(ISourceViewer, String, int)
* @since 2.1
*/
public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType, int stateMask) {
return new TemplateVariableTextHover(fProcessor);
}
}
private static class TemplateVariableTextHover implements ITextHover {
private TemplateVariableProcessor fProcessor;
/**
* @param type
*/
public TemplateVariableTextHover(TemplateVariableProcessor processor) {
fProcessor= processor;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.ITextHover#getHoverInfo(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion subject) {
try {
IDocument doc= textViewer.getDocument();
int offset= subject.getOffset();
if (offset >= 2 && "${".equals(doc.get(offset-2, 2))) { //$NON-NLS-1$
String varName= doc.get(offset, subject.getLength());
Iterator iter= fProcessor.getContextType().variableIterator();
while (iter.hasNext()) {
TemplateVariable var= (TemplateVariable) iter.next();
if (varName.equals(var.getName())) {
return var.getDescription();
}
}
}
} catch (BadLocationException e) {
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.ITextHover#getHoverRegion(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
if (textViewer != null) {
return JavaWordFinder.findWord(textViewer.getDocument(), offset);
}
return null;
}
}
private static class TextViewerAction extends Action implements IUpdate {
private int fOperationCode= -1;
private ITextOperationTarget fOperationTarget;
public TextViewerAction(ITextViewer viewer, int operationCode) {
fOperationCode= operationCode;
fOperationTarget= viewer.getTextOperationTarget();
update();
}
/**
* Updates the enabled state of the action.
* Fires a property change if the enabled state changes.
*
* @see Action#firePropertyChange(String, Object, Object)
*/
public void update() {
boolean wasEnabled= isEnabled();
boolean isEnabled= (fOperationTarget != null && fOperationTarget.canDoOperation(fOperationCode));
setEnabled(isEnabled);
if (wasEnabled != isEnabled) {
firePropertyChange(ENABLED, wasEnabled ? Boolean.TRUE : Boolean.FALSE, isEnabled ? Boolean.TRUE : Boolean.FALSE);
}
}
/**
* @see Action#run()
*/
public void run() {
if (fOperationCode != -1 && fOperationTarget != null) {
fOperationTarget.doOperation(fOperationCode);
}
}
}
private final Template fTemplate;
private Text fNameText;
private Text fDescriptionText;
private Combo fContextCombo;
private SourceViewer fPatternEditor;
private Button fInsertVariableButton;
private boolean fIsNameModifiable;
private StatusInfo fValidationStatus;
private boolean fSuppressError= true; // #4354
private Map fGlobalActions= new HashMap(10);
private List fSelectionActions = new ArrayList(3);
private String[] fContextTypes;
private final TemplateVariableProcessor fProcessor= new TemplateVariableProcessor();
public EditTemplateDialog(Shell parent, Template template, boolean edit, boolean isNameModifiable, String[] contextTypes) {
super(parent);
setShellStyle(getShellStyle() | SWT.MAX | SWT.RESIZE);
String title= edit
? TemplateMessages.getString("EditTemplateDialog.title.edit") //$NON-NLS-1$
: TemplateMessages.getString("EditTemplateDialog.title.new"); //$NON-NLS-1$
setTitle(title);
fTemplate= template;
fIsNameModifiable= isNameModifiable;
fContextTypes= contextTypes;
fValidationStatus= new StatusInfo();
ContextType type= ContextTypeRegistry.getInstance().getContextType(template.getContextTypeName());
fProcessor.setContextType(type);
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite ancestor) {
Composite parent= new Composite(ancestor, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
parent.setLayout(layout);
parent.setLayoutData(new GridData(GridData.FILL_BOTH));
ModifyListener listener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
doTextWidgetChanged(e.widget);
}
};
if (fIsNameModifiable) {
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.name")); //$NON-NLS-1$
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
layout= new GridLayout();
layout.numColumns= 3;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
fNameText= createText(composite);
fNameText.addModifyListener(listener);
createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$
fContextCombo= new Combo(composite, SWT.READ_ONLY);
for (int i= 0; i < fContextTypes.length; i++) {
fContextCombo.add(fContextTypes[i]);
}
fContextCombo.addModifyListener(listener);
}
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$
int descFlags= fIsNameModifiable ? SWT.BORDER : SWT.BORDER | SWT.READ_ONLY;
fDescriptionText= new Text(parent, descFlags );
fDescriptionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fDescriptionText.addModifyListener(listener);
Label patternLabel= createLabel(parent, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$
patternLabel.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
fPatternEditor= createEditor(parent);
Label filler= new Label(parent, SWT.NONE);
filler.setLayoutData(new GridData());
Composite composite= new Composite(parent, SWT.NONE);
layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
composite.setLayoutData(new GridData());
fInsertVariableButton= new Button(composite, SWT.NONE);
fInsertVariableButton.setLayoutData(getButtonGridData(fInsertVariableButton));
fInsertVariableButton.setText(TemplateMessages.getString("EditTemplateDialog.insert.variable")); //$NON-NLS-1$
fInsertVariableButton.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
fPatternEditor.getTextWidget().setFocus();
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
fDescriptionText.setText(fTemplate.getDescription());
if (fIsNameModifiable) {
fNameText.setText(fTemplate.getName());
fContextCombo.select(getIndex(fTemplate.getContextTypeName()));
} else {
fPatternEditor.getControl().setFocus();
}
initializeActions();
applyDialogFont(parent);
return composite;
}
protected void doTextWidgetChanged(Widget w) {
if (w == fNameText) {
String name= fNameText.getText();
if (fSuppressError && (name.trim().length() != 0))
fSuppressError= false;
fTemplate.setName(name);
updateButtons();
} else if (w == fContextCombo) {
String name= fContextCombo.getText();
fTemplate.setContext(name);
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name));
} else if (w == fDescriptionText) {
String desc= fDescriptionText.getText();
fTemplate.setDescription(desc);
}
}
protected void doSourceChanged(IDocument document) {
String text= document.get();
fTemplate.setPattern(text);
fValidationStatus.setOK();
ContextType contextType= ContextTypeRegistry.getInstance().getContextType(fTemplate.getContextTypeName());
if (contextType != null) {
try {
String errorMessage= contextType.validate(text);
if (errorMessage != null) {
fValidationStatus.setError(errorMessage);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
updateUndoAction();
updateButtons();
}
private static GridData getButtonGridData(Button button) {
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.heightHint= SWTUtil.getButtonHeigthHint(button);
return data;
}
private static Label createLabel(Composite parent, String name) {
Label label= new Label(parent, SWT.NULL);
label.setText(name);
label.setLayoutData(new GridData());
return label;
}
private static Text createText(Composite parent) {
Text text= new Text(parent, SWT.BORDER);
text.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
return text;
}
private SourceViewer createEditor(Composite parent) {
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocument document= new Document(fTemplate.getPattern());
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null, fProcessor));
viewer.setEditable(true);
viewer.setDocument(document);
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
int nLines= document.getNumberOfLines();
if (nLines < 5) {
nLines= 5;
} else if (nLines > 12) {
nLines= 12;
}
Control control= viewer.getControl();
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(80);
data.heightHint= convertHeightInCharsToPixels(nLines);
control.setLayoutData(data);
viewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
if (event .getDocumentEvent() != null)
doSourceChanged(event.getDocumentEvent().getDocument());
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateSelectionDependentActions();
}
});
if (viewer instanceof ITextViewerExtension) {
((ITextViewerExtension) viewer).prependVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent event) {
handleVerifyKeyPressed(event);
}
});
} else {
viewer.getTextWidget().addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
public void keyReleased(KeyEvent e) {}
});
}
return viewer;
}
private void handleKeyPressed(KeyEvent event) {
if (event.stateMask != SWT.MOD1)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
break;
// CTRL-Z
case 'z' - 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
break;
}
}
private void handleVerifyKeyPressed(VerifyEvent event) {
if (!event.doit)
return;
if (event.stateMask != SWT.MOD1)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
event.doit= false;
break;
// CTRL-Z
case 'z' - 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
event.doit= false;
break;
}
}
private void initializeActions() {
TextViewerAction action= new TextViewerAction(fPatternEditor, SourceViewer.UNDO);
action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
action= new TextViewerAction(fPatternEditor, SourceViewer.CUT);
action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.CUT, action);
action= new TextViewerAction(fPatternEditor, SourceViewer.COPY);
action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.COPY, action);
action= new TextViewerAction(fPatternEditor, SourceViewer.PASTE);
action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
action= new TextViewerAction(fPatternEditor, SourceViewer.SELECT_ALL);
action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
action= new TextViewerAction(fPatternEditor, SourceViewer.CONTENTASSIST_PROPOSALS);
action.setText(TemplateMessages.getString("EditTemplateDialog.content.assist")); //$NON-NLS-1$
fGlobalActions.put("ContentAssistProposal", action); //$NON-NLS-1$
fSelectionActions.add(ITextEditorActionConstants.CUT);
fSelectionActions.add(ITextEditorActionConstants.COPY);
fSelectionActions.add(ITextEditorActionConstants.PASTE);
// create context menu
MenuManager manager= new MenuManager(null, null);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager mgr) {
fillContextMenu(mgr);
}
});
StyledText text= fPatternEditor.getTextWidget();
Menu menu= manager.createContextMenu(text);
text.setMenu(menu);
}
private void fillContextMenu(IMenuManager menu) {
menu.add(new GroupMarker(ITextEditorActionConstants.GROUP_UNDO));
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO));
menu.add(new Separator(ITextEditorActionConstants.GROUP_EDIT));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.CUT));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.COPY));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.PASTE));
menu.appendToGroup(ITextEditorActionConstants.GROUP_EDIT, (IAction) fGlobalActions.get(ITextEditorActionConstants.SELECT_ALL));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.appendToGroup(IContextMenuConstants.GROUP_GENERATE, (IAction) fGlobalActions.get("ContentAssistProposal")); //$NON-NLS-1$
}
protected void updateSelectionDependentActions() {
Iterator iterator= fSelectionActions.iterator();
while (iterator.hasNext())
updateAction((String)iterator.next());
}
protected void updateUndoAction() {
IAction action= (IAction) fGlobalActions.get(ITextEditorActionConstants.UNDO);
if (action instanceof IUpdate)
((IUpdate) action).update();
}
protected void updateAction(String actionId) {
IAction action= (IAction) fGlobalActions.get(actionId);
if (action instanceof IUpdate)
((IUpdate) action).update();
}
private int getIndex(String context) {
ContextTypeRegistry registry= ContextTypeRegistry.getInstance();
registry.getContextType(context);
if (context == null)
return -1;
for (int i= 0; i < fContextTypes.length; i++) {
if (context.equals(fContextTypes[i])) {
return i;
}
}
return -1;
}
protected void okPressed() {
super.okPressed();
}
private void updateButtons() {
StatusInfo status;
boolean valid= fNameText == null || fNameText.getText().trim().length() != 0;
if (!valid) {
status = new StatusInfo();
if (!fSuppressError) {
status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$
}
} else {
status= fValidationStatus;
}
updateStatus(status);
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.EDIT_TEMPLATE_DIALOG);
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplatePreferencePage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ICheckStateListener;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.corext.template.TemplateSet;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.corext.template.java.JavaContextType;
import org.eclipse.jdt.internal.corext.template.java.JavaDocContextType;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.template.TemplateContentProvider;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static class TemplateLabelProvider extends LabelProvider implements ITableLabelProvider {
public Image getColumnImage(Object element, int columnIndex) {
return null;
}
public String getColumnText(Object element, int columnIndex) {
Template template = (Template) element;
switch (columnIndex) {
case 0:
return template.getName();
case 1:
return template.getContextTypeName();
case 2:
return template.getDescription();
default:
return ""; //$NON-NLS-1$
}
}
}
// preference store keys
private static final String PREF_FORMAT_TEMPLATES= PreferenceConstants.TEMPLATES_USE_CODEFORMATTER;
private final String[] CONTEXTS= new String[] { JavaContextType.NAME, JavaDocContextType.NAME };
private Templates fTemplates;
private CheckboxTableViewer fTableViewer;
private Button fAddButton;
private Button fEditButton;
private Button fImportButton;
private Button fExportButton;
private Button fExportAllButton;
private Button fRemoveButton;
private Button fEnableAllButton;
private Button fDisableAllButton;
private SourceViewer fPatternViewer;
private Button fFormatButton;
public TemplatePreferencePage() {
super();
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(TemplateMessages.getString("TemplatePreferencePage.message")); //$NON-NLS-1$
fTemplates= Templates.getInstance();
}
/*
* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite ancestor) {
Composite parent= new Composite(ancestor, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginHeight= 0;
layout.marginWidth= 0;
parent.setLayout(layout);
Composite innerParent= new Composite(parent, SWT.NONE);
GridLayout innerLayout= new GridLayout();
innerLayout.numColumns= 2;
innerLayout.marginHeight= 0;
innerLayout.marginWidth= 0;
innerParent.setLayout(innerLayout);
GridData gd= new GridData(GridData.FILL_BOTH);
gd.horizontalSpan= 2;
innerParent.setLayoutData(gd);
Table table= new Table(innerParent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(3);
data.heightHint= convertHeightInCharsToPixels(10);
table.setLayoutData(data);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableLayout tableLayout= new TableLayout();
table.setLayout(tableLayout);
TableColumn column1= new TableColumn(table, SWT.NONE);
column1.setText(TemplateMessages.getString("TemplatePreferencePage.column.name")); //$NON-NLS-1$
TableColumn column2= new TableColumn(table, SWT.NONE);
column2.setText(TemplateMessages.getString("TemplatePreferencePage.column.context")); //$NON-NLS-1$
TableColumn column3= new TableColumn(table, SWT.NONE);
column3.setText(TemplateMessages.getString("TemplatePreferencePage.column.description")); //$NON-NLS-1$
fTableViewer= new CheckboxTableViewer(table);
fTableViewer.setLabelProvider(new TemplateLabelProvider());
fTableViewer.setContentProvider(new TemplateContentProvider());
fTableViewer.setSorter(new ViewerSorter() {
public int compare(Viewer viewer, Object object1, Object object2) {
if ((object1 instanceof Template) && (object2 instanceof Template)) {
Template left= (Template) object1;
Template right= (Template) object2;
int result= left.getName().compareToIgnoreCase(right.getName());
if (result != 0)
return result;
return left.getDescription().compareToIgnoreCase(right.getDescription());
}
return super.compare(viewer, object1, object2);
}
public boolean isSorterProperty(Object element, String property) {
return true;
}
});
fTableViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent e) {
edit();
}
});
fTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent e) {
selectionChanged1();
}
});
fTableViewer.addCheckStateListener(new ICheckStateListener() {
public void checkStateChanged(CheckStateChangedEvent event) {
Template template= (Template) event.getElement();
template.setEnabled(event.getChecked());
}
});
Composite buttons= new Composite(innerParent, SWT.NONE);
buttons.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
buttons.setLayout(layout);
fAddButton= new Button(buttons, SWT.PUSH);
fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$
fAddButton.setLayoutData(getButtonGridData(fAddButton));
fAddButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
add();
}
});
fEditButton= new Button(buttons, SWT.PUSH);
fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$
fEditButton.setLayoutData(getButtonGridData(fEditButton));
fEditButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
edit();
}
});
fRemoveButton= new Button(buttons, SWT.PUSH);
fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$
fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton));
fRemoveButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
remove();
}
});
fImportButton= new Button(buttons, SWT.PUSH);
fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$
fImportButton.setLayoutData(getButtonGridData(fImportButton));
fImportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
import_();
}
});
fExportButton= new Button(buttons, SWT.PUSH);
fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$
fExportButton.setLayoutData(getButtonGridData(fExportButton));
fExportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
export();
}
});
fExportAllButton= new Button(buttons, SWT.PUSH);
fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$
fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton));
fExportAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
exportAll();
}
});
fEnableAllButton= new Button(buttons, SWT.PUSH);
fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$
fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton));
fEnableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(true);
}
});
fDisableAllButton= new Button(buttons, SWT.PUSH);
fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$
fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton));
fDisableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(false);
}
});
fPatternViewer= createViewer(parent);
fFormatButton= new Button(parent, SWT.CHECK);
fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$
GridData gd1= new GridData();
gd1.horizontalSpan= 2;
fFormatButton.setLayoutData(gd1);
fTableViewer.setInput(fTemplates);
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES));
updateButtons();
configureTableResizing(innerParent, buttons, table, column1, column2, column3);
Dialog.applyDialogFont(parent);
return parent;
}
/**
* Correctly resizes the table so no phantom columns appear
*/
private static void configureTableResizing(final Composite parent, final Composite buttons, final Table table, final TableColumn column1, final TableColumn column2, final TableColumn column3) {
parent.addControlListener(new ControlAdapter() {
public void controlResized(ControlEvent e) {
Rectangle area= parent.getClientArea();
Point preferredSize= table.computeSize(SWT.DEFAULT, SWT.DEFAULT);
int width= area.width - 2 * table.getBorderWidth();
if (preferredSize.y > area.height) {
// Subtract the scrollbar width from the total column width
// if a vertical scrollbar will be required
Point vBarSize = table.getVerticalBar().getSize();
width -= vBarSize.x;
}
width -= buttons.getSize().x;
Point oldSize= table.getSize();
if (oldSize.x > width) {
// table is getting smaller so make the columns
// smaller first and then resize the table to
// match the client area width
column1.setWidth(width/4);
column2.setWidth(width/4);
column3.setWidth(width - (column1.getWidth() + column2.getWidth()));
table.setSize(width, area.height);
} else {
// table is getting bigger so make the table
// bigger first and then make the columns wider
// to match the client area width
table.setSize(width, area.height);
column1.setWidth(width / 4);
column2.setWidth(width / 4);
column3.setWidth(width - (column1.getWidth() + column2.getWidth()));
}
}
});
}
private Template[] getEnabledTemplates() {
Template[] templates= fTemplates.getTemplates();
List list= new ArrayList(templates.length);
for (int i= 0; i != templates.length; i++)
if (templates[i].isEnabled())
list.add(templates[i]);
return (Template[]) list.toArray(new Template[list.size()]);
}
private SourceViewer createViewer(Composite parent) {
Label label= new Label(parent, SWT.NONE);
label.setText(TemplateMessages.getString("TemplatePreferencePage.preview")); //$NON-NLS-1$
GridData data= new GridData();
data.horizontalSpan= 2;
label.setLayoutData(data);
SourceViewer viewer= new SourceViewer(parent, null, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
IDocument document= new Document();
IDocumentPartitioner partitioner= tools.createDocumentPartitioner();
document.setDocumentPartitioner(partitioner);
partitioner.connect(document);
viewer.configure(new JavaSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(document);
viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Font font= JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.horizontalSpan= 2;
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
return viewer;
}
private static GridData getButtonGridData(Button button) {
GridData data= new GridData(GridData.FILL_HORIZONTAL);
data.widthHint= SWTUtil.getButtonWidthHint(button);
data.heightHint= SWTUtil.getButtonHeigthHint(button);
return data;
}
private void selectionChanged1() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
if (selection.size() == 1) {
Template template= (Template) selection.getFirstElement();
fPatternViewer.getDocument().set(template.getPattern());
} else {
fPatternViewer.getDocument().set(""); //$NON-NLS-1$
}
updateButtons();
}
private void updateButtons() {
int selectionCount= ((IStructuredSelection) fTableViewer.getSelection()).size();
int itemCount= fTableViewer.getTable().getItemCount();
fEditButton.setEnabled(selectionCount == 1);
fExportButton.setEnabled(selectionCount > 0);
fRemoveButton.setEnabled(selectionCount > 0 && selectionCount <= itemCount);
fEnableAllButton.setEnabled(itemCount > 0);
fDisableAllButton.setEnabled(itemCount > 0);
}
private void add() {
Template template= new Template();
template.setContext(CONTEXTS[0]);
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false, true, CONTEXTS);
if (dialog.open() == Window.OK) {
fTemplates.add(template);
fTableViewer.refresh();
fTableViewer.setChecked(template, template.isEnabled());
fTableViewer.setSelection(new StructuredSelection(template));
}
}
private void edit() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Object[] objects= selection.toArray();
if ((objects == null) || (objects.length != 1))
return;
Template template= (Template) selection.getFirstElement();
edit(template);
}
private void edit(Template template) {
Template newTemplate= new Template(template);
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), newTemplate, true, true, CONTEXTS);
if (dialog.open() == Window.OK) {
if (!newTemplate.getName().equals(template.getName()) &&
MessageDialog.openQuestion(getShell(),
TemplateMessages.getString("TemplatePreferencePage.question.create.new.title"), //$NON-NLS-1$
TemplateMessages.getString("TemplatePreferencePage.question.create.new.message"))) //$NON-NLS-1$
{
template= newTemplate;
fTemplates.add(template);
fTableViewer.refresh();
} else {
template.setName(newTemplate.getName());
template.setDescription(newTemplate.getDescription());
template.setContext(newTemplate.getContextTypeName());
template.setPattern(newTemplate.getPattern());
fTableViewer.refresh(template);
}
fTableViewer.setChecked(template, template.isEnabled());
fTableViewer.setSelection(new StructuredSelection(template));
}
}
private void import_() {
FileDialog dialog= new FileDialog(getShell());
dialog.setText(TemplateMessages.getString("TemplatePreferencePage.import.title")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.import.extension")}); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
try {
fTemplates.addFromFile(new File(path), true);
fTableViewer.refresh();
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
} catch (CoreException e) {
openReadErrorDialog(e);
}
}
private void exportAll() {
export(fTemplates);
}
private void export() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Object[] templates= selection.toArray();
TemplateSet templateSet= new TemplateSet(fTemplates.getTemplateTag());
for (int i= 0; i != templates.length; i++)
templateSet.add((Template) templates[i]);
export(templateSet);
}
private void export(TemplateSet templateSet) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(TemplateMessages.getFormattedString("TemplatePreferencePage.export.title", new Integer(templateSet.getTemplates().length))); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {TemplateMessages.getString("TemplatePreferencePage.export.extension")}); //$NON-NLS-1$
dialog.setFileName(TemplateMessages.getString("TemplatePreferencePage.export.filename")); //$NON-NLS-1$
String path= dialog.open();
if (path == null)
return;
File file= new File(path);
if (file.isHidden()) {
String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$
String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
return;
}
if (file.exists() && !file.canWrite()) {
String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$
String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
return;
}
if (!file.exists() || confirmOverwrite(file)) {
try {
templateSet.saveToFile(file);
} catch (CoreException e) {
if (e.getStatus().getException() instanceof FileNotFoundException) {
String title= TemplateMessages.getString("TemplatePreferencePage.export.error.title"); //$NON-NLS-1$
String message= TemplateMessages.getFormattedString("TemplatePreferencePage.export.error.fileNotFound", e.getStatus().getException().getLocalizedMessage()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
return;
}
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
}
}
private boolean confirmOverwrite(File file) {
return MessageDialog.openQuestion(getShell(),
TemplateMessages.getString("TemplatePreferencePage.export.exists.title"), //$NON-NLS-1$
TemplateMessages.getFormattedString("TemplatePreferencePage.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$
}
private void remove() {
IStructuredSelection selection= (IStructuredSelection) fTableViewer.getSelection();
Iterator elements= selection.iterator();
while (elements.hasNext()) {
Template template= (Template) elements.next();
fTemplates.remove(template);
}
fTableViewer.refresh();
}
private void enableAll(boolean enable) {
Template[] templates= fTemplates.getTemplates();
for (int i= 0; i != templates.length; i++)
templates[i].setEnabled(enable);
fTableViewer.setAllChecked(enable);
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {}
/*
* @see Control#setVisible(boolean)
*/
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible)
setTitle(TemplateMessages.getString("TemplatePreferencePage.title")); //$NON-NLS-1$
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fFormatButton.setSelection(prefs.getDefaultBoolean(PREF_FORMAT_TEMPLATES));
try {
fTemplates.restoreDefaults();
} catch (CoreException e) {
openReadErrorDialog(e);
}
// refresh
fTableViewer.refresh();
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
}
/*
* @see PreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_FORMAT_TEMPLATES, fFormatButton.getSelection());
try {
fTemplates.save();
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
JavaPlugin.getDefault().savePluginPreferences();
return super.performOk();
}
/*
* @see PreferencePage#performCancel()
*/
public boolean performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
openReadErrorDialog(e);
}
return super.performCancel();
}
private void openReadErrorDialog(CoreException e) {
String title= TemplateMessages.getString("TemplatePreferencePage.error.read.title"); //$NON-NLS-1$
// Show parse error in a user dialog without logging
if (e.getStatus().getCode() == IJavaStatusConstants.TEMPLATE_PARSE_EXCEPTION) {
String message= e.getStatus().getException().getLocalizedMessage();
if (message != null)
message= TemplateMessages.getFormattedString("TemplatePreferencePage.error.parse.message", message); //$NON-NLS-1$
else
message= TemplateMessages.getString("TemplatePreferencePage.error.read.message"); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
} else {
String message= TemplateMessages.getString("TemplatePreferencePage.error.read.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
}
}
private void openWriteErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$
null, e.getStatus());
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HistoryListAction.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.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
public class HistoryListAction extends Action {
private class HistoryListDialog extends StatusDialog {
private ListDialogField fHistoryList;
private IStatus fHistoryStatus;
private IJavaElement fResult;
private HistoryListDialog(Shell shell, IJavaElement[] elements) {
super(shell);
setTitle(TypeHierarchyMessages.getString("HistoryListDialog.title")); //$NON-NLS-1$
String[] buttonLabels= new String[] {
/* 0 */ TypeHierarchyMessages.getString("HistoryListDialog.remove.button"), //$NON-NLS-1$
};
IListAdapter adapter= new IListAdapter() {
public void customButtonPressed(ListDialogField field, int index) {
doCustomButtonPressed();
}
public void selectionChanged(ListDialogField field) {
doSelectionChanged();
}
public void doubleClicked(ListDialogField field) {
doDoubleClicked();
}
};
JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT);
fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider);
fHistoryList.setLabelText(TypeHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$
fHistoryList.setElements(Arrays.asList(elements));
ISelection sel;
if (elements.length > 0) {
sel= new StructuredSelection(elements[0]);
} else {
sel= new StructuredSelection();
}
fHistoryList.selectElements(sel);
}
/*
* @see Dialog#createDialogArea(Composite)
*/
protected Control createDialogArea(Composite parent) {
initializeDialogUnits(parent);
Composite composite= (Composite) super.createDialogArea(parent);
Composite inner= new Composite(composite, SWT.NONE);
inner.setLayoutData(new GridData(GridData.FILL_BOTH));
LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0);
LayoutUtil.setHeigthHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12));
LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null));
applyDialogFont(composite);
return composite;
}
/**
* Method doCustomButtonPressed.
*/
private void doCustomButtonPressed() {
fHistoryList.removeElements(fHistoryList.getSelectedElements());
}
private void doDoubleClicked() {
if (fHistoryStatus.isOK()) {
okPressed();
}
}
private void doSelectionChanged() {
StatusInfo status= new StatusInfo();
List selected= fHistoryList.getSelectedElements();
if (selected.size() != 1) {
status.setError(""); //$NON-NLS-1$
fResult= null;
} else {
fResult= (IJavaElement) selected.get(0);
}
fHistoryList.enableButton(0, fHistoryList.getSize() > selected.size());
fHistoryStatus= status;
updateStatus(status);
}
public IJavaElement getResult() {
return fResult;
}
public IJavaElement[] getRemaining() {
List elems= fHistoryList.getElements();
return (IJavaElement[]) elems.toArray(new IJavaElement[elems.size()]);
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG);
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#create()
*/
public void create() {
setShellStyle(getShellStyle() | SWT.RESIZE);
super.create();
}
}
private TypeHierarchyViewPart fView;
public HistoryListAction(TypeHierarchyViewPart view) {
fView= view;
setText(TypeHierarchyMessages.getString("HistoryListAction.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION);
}
/*
* @see IAction#run()
*/
public void run() {
IJavaElement[] historyEntries= fView.getHistoryEntries();
HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries);
if (dialog.open() == Window.OK) {
fView.setHistoryEntries(dialog.getRemaining());
fView.setInputElement(dialog.getResult());
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/SWTUtil.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.util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Caret;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.Assert;
/**
* Utility class to simplify access to some SWT resources.
*/
public class SWTUtil {
/**
* Returns the standard display to be used. The method first checks, if
* the thread calling this method has an associated disaply. If so, this
* display is returned. Otherwise the method returns the default display.
*/
public static Display getStandardDisplay() {
Display display;
display= Display.getCurrent();
if (display == null)
display= Display.getDefault();
return display;
}
/**
* Returns the shell for the given widget. If the widget doesn't represent
* a SWT object that manage a shell, <code>null</code> is returned.
*
* @return the shell for the given widget
*/
public static Shell getShell(Widget widget) {
if (widget instanceof Control)
return ((Control)widget).getShell();
if (widget instanceof Caret)
return ((Caret)widget).getParent().getShell();
if (widget instanceof DragSource)
return ((DragSource)widget).getControl().getShell();
if (widget instanceof DropTarget)
return ((DropTarget)widget).getControl().getShell();
if (widget instanceof Menu)
return ((Menu)widget).getParent().getShell();
if (widget instanceof ScrollBar)
return ((ScrollBar)widget).getParent().getShell();
return null;
}
/**
* Returns a width hint for a button control.
*/
public static int getButtonWidthHint(Button button) {
if (button.getFont().equals(JFaceResources.getDefaultFont()))
button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
int widthHint= converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
}
/**
* Returns a height hint for a button control.
*/
public static int getButtonHeigthHint(Button button) {
if (button.getFont().equals(JFaceResources.getDefaultFont()))
button.setFont(JFaceResources.getDialogFont());
PixelConverter converter= new PixelConverter(button);
return converter.convertVerticalDLUsToPixels(IDialogConstants.BUTTON_HEIGHT);
}
/**
* Sets width and height hint for the button control.
* <b>Note:</b> This is a NOP if the button's layout data is not
* an instance of <code>GridData</code>.
*
* @param the button for which to set the dimension hint
*/
public static void setButtonDimensionHint(Button button) {
Assert.isNotNull(button);
Object gd= button.getLayoutData();
if (gd instanceof GridData) {
((GridData)gd).heightHint= getButtonHeigthHint(button);
((GridData)gd).widthHint= getButtonWidthHint(button);
}
}
public static int getTableHeightHint(Table table, int rows) {
if (table.getFont().equals(JFaceResources.getDefaultFont()))
table.setFont(JFaceResources.getDialogFont());
int result= table.getItemHeight() * rows + table.getHeaderHeight();
if (table.getLinesVisible())
result+= table.getGridLineWidth() * (rows - 1);
return result;
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/OutputLocationDialog.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.util.ArrayList;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
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.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.internal.dialogs.ResourceSorter;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.dialogs.StatusDialog;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
public class OutputLocationDialog extends StatusDialog {
private StringButtonDialogField fContainerDialogField;
private SelectionButtonDialogField fUseDefault;
private SelectionButtonDialogField fUseSpecific;
private StatusInfo fContainerFieldStatus;
private IProject fCurrProject;
private IPath fOutputLocation;
public OutputLocationDialog(Shell parent, CPListElement entryToEdit) {
super(parent);
setTitle(NewWizardMessages.getString("OutputLocationDialog.title")); //$NON-NLS-1$
fContainerFieldStatus= new StatusInfo();
OutputLocationAdapter adapter= new OutputLocationAdapter();
fUseDefault= new SelectionButtonDialogField(SWT.RADIO);
fUseDefault.setLabelText(NewWizardMessages.getString("OutputLocationDialog.usedefault.label")); //$NON-NLS-1$
fUseDefault.setDialogFieldListener(adapter);
String label= NewWizardMessages.getFormattedString("OutputLocationDialog.usespecific.label", entryToEdit.getPath().segment(0)); //$NON-NLS-1$
fUseSpecific= new SelectionButtonDialogField(SWT.RADIO);
fUseSpecific.setLabelText(label);
fUseSpecific.setDialogFieldListener(adapter);
fContainerDialogField= new StringButtonDialogField(adapter);
fContainerDialogField.setButtonLabel(NewWizardMessages.getString("OutputLocationDialog.location.button")); //$NON-NLS-1$
fContainerDialogField.setDialogFieldListener(adapter);
fUseSpecific.attachDialogField(fContainerDialogField);
fCurrProject= entryToEdit.getJavaProject().getProject();
IPath outputLocation= (IPath) entryToEdit.getAttribute(CPListElement.OUTPUT);
if (outputLocation == null) {
fUseDefault.setSelection(true);
} else {
fUseSpecific.setSelection(true);
fContainerDialogField.setText(outputLocation.removeFirstSegments(1).makeRelative().toString());
}
}
protected Control createDialogArea(Composite parent) {
Composite composite= (Composite)super.createDialogArea(parent);
int widthHint= convertWidthInCharsToPixels(60);
int indent= convertWidthInCharsToPixels(4);
Composite inner= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
inner.setLayout(layout);
fUseDefault.doFillIntoGrid(inner, 2);
fUseSpecific.doFillIntoGrid(inner, 2);
Text textControl= fContainerDialogField.getTextControl(inner);
GridData textData= new GridData();
textData.widthHint= widthHint;
textData.grabExcessHorizontalSpace= true;
textData.horizontalIndent= indent;
textControl.setLayoutData(textData);
Button buttonControl= fContainerDialogField.getChangeControl(inner);
GridData buttonData= new GridData();
buttonData.widthHint= SWTUtil.getButtonWidthHint(buttonControl);
buttonData.heightHint= SWTUtil.getButtonHeigthHint(buttonControl);
buttonControl.setLayoutData(buttonData);
applyDialogFont(composite);
return composite;
}
// -------- OutputLocationAdapter --------
private class OutputLocationAdapter implements IDialogFieldListener, IStringButtonAdapter {
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
doStatusLineUpdate();
}
public void changeControlPressed(DialogField field) {
doChangeControlPressed();
}
}
protected void doChangeControlPressed() {
IContainer container= chooseOutputLocation();
if (container != null) {
fContainerDialogField.setText(container.getProjectRelativePath().toString());
}
}
protected void doStatusLineUpdate() {
checkIfPathValid();
updateStatus(fContainerFieldStatus);
}
protected void checkIfPathValid() {
fOutputLocation= null;
fContainerFieldStatus.setOK();
if (fUseDefault.isSelected()) {
return;
}
String pathStr= fContainerDialogField.getText();
if (pathStr.length() == 0) {
fContainerFieldStatus.setOK();
return;
}
IPath projectPath= fCurrProject.getFullPath();
IPath path= projectPath.append(pathStr);
IWorkspace workspace= fCurrProject.getWorkspace();
IStatus pathValidation= workspace.validatePath(path.toString(), IResource.PROJECT | IResource.FOLDER);
if (!pathValidation.isOK()) {
fContainerFieldStatus.setError(NewWizardMessages.getFormattedString("OutputLocationDialog.error.invalidpath", pathValidation.getMessage())); //$NON-NLS-1$
return;
}
IWorkspaceRoot root= workspace.getRoot();
IResource res= root.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fContainerFieldStatus.setError(NewWizardMessages.getString("OutputLocationDialog.error.existingisfile")); //$NON-NLS-1$
return;
}
}
fOutputLocation= path;
}
public IPath getOutputLocation() {
return fOutputLocation;
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.OUTPUT_LOCATION_DIALOG);
}
// ---------- util method ------------
private IContainer chooseOutputLocation() {
IWorkspaceRoot root= fCurrProject.getWorkspace().getRoot();
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
IProject[] allProjects= root.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(fCurrProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSelection= null;
if (fOutputLocation != null) {
initSelection= root.findMember(fOutputLocation);
}
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setTitle(NewWizardMessages.getString("OutputLocationDialog.ChooseOutputFolder.title")); //$NON-NLS-1$
dialog.setValidator(validator);
dialog.setMessage(NewWizardMessages.getString("OutputLocationDialog.ChooseOutputFolder.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(root);
dialog.setInitialSelection(initSelection);
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (dialog.open() == Window.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/LayoutUtil.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
public class LayoutUtil {
/**
* Calculates the number of columns needed by field editors
*/
public static int getNumberOfColumns(DialogField[] editors) {
int nCulumns= 0;
for (int i= 0; i < editors.length; i++) {
nCulumns= Math.max(editors[i].getNumberOfControls(), nCulumns);
}
return nCulumns;
}
/**
* Creates a composite and fills in the given editors.
* @param labelOnTop Defines if the label of all fields should be on top of the fields
*/
public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop) {
doDefaultLayout(parent, editors, labelOnTop, 0, 0, 0, 0);
}
/**
* Creates a composite and fills in the given editors.
* @param labelOnTop Defines if the label of all fields should be on top of the fields
* @param minWidth The minimal width of the composite
* @param minHeight The minimal height of the composite
*/
public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight) {
doDefaultLayout(parent, editors, labelOnTop, minWidth, minHeight, 0, 0);
}
/**
* Creates a composite and fills in the given editors.
* @param labelOnTop Defines if the label of all fields should be on top of the fields
* @param minWidth The minimal width of the composite
* @param minHeight The minimal height of the composite
* @param marginWidth The margin width to be used by the composite
* @param marginHeight The margin height to be used by the composite
* @deprecated
*/
public static void doDefaultLayout(Composite parent, DialogField[] editors, boolean labelOnTop, int minWidth, int minHeight, int marginWidth, int marginHeight) {
int nCulumns= getNumberOfColumns(editors);
Control[][] controls= new Control[editors.length][];
for (int i= 0; i < editors.length; i++) {
controls[i]= editors[i].doFillIntoGrid(parent, nCulumns);
}
if (labelOnTop) {
nCulumns--;
modifyLabelSpans(controls, nCulumns);
}
GridLayout layout= new GridLayout();
if (marginWidth != SWT.DEFAULT) {
layout.marginWidth= marginWidth;
}
if (marginHeight != SWT.DEFAULT) {
layout.marginHeight= marginHeight;
}
layout.numColumns= nCulumns;
parent.setLayout(layout);
}
private static void modifyLabelSpans(Control[][] controls, int nCulumns) {
for (int i= 0; i < controls.length; i++) {
setHorizontalSpan(controls[i][0], nCulumns);
}
}
/**
* Sets the span of a control. Assumes that GridData is used.
*/
public static void setHorizontalSpan(Control control, int span) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).horizontalSpan= span;
} else if (span != 1) {
GridData gd= new GridData();
gd.horizontalSpan= span;
control.setLayoutData(gd);
}
}
/**
* Sets the width hint of a control. Assumes that GridData is used.
*/
public static void setWidthHint(Control control, int widthHint) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).widthHint= widthHint;
}
}
/**
* Sets the heigthHint hint of a control. Assumes that GridData is used.
*/
public static void setHeigthHint(Control control, int heigthHint) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).heightHint= heigthHint;
}
}
/**
* Sets the horizontal indent of a control. Assumes that GridData is used.
*/
public static void setHorizontalIndent(Control control, int horizontalIndent) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).horizontalIndent= horizontalIndent;
}
}
/**
* Sets the horizontal indent of a control. Assumes that GridData is used.
*/
public static void setHorizontalGrabbing(Control control) {
Object ld= control.getLayoutData();
if (ld instanceof GridData) {
((GridData)ld).grabExcessHorizontalSpace= true;
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ColumnLayoutData;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableLayout;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.util.TableLayoutComposite;
/**
* A list with a button bar.
* Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
* List model is independend of widget creation.
* DialogFields controls are: Label, List and Composite containing buttons.
*/
public class ListDialogField extends DialogField {
public static class ColumnsDescription {
private ColumnLayoutData[] columns;
private String[] headers;
private boolean drawLines;
public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) {
this.columns= columns;
this.headers= headers;
this.drawLines= drawLines;
}
public ColumnsDescription(String[] headers, boolean drawLines) {
this(createColumnWeightData(headers.length), headers, drawLines);
}
public ColumnsDescription(int nColumns, boolean drawLines) {
this(createColumnWeightData(nColumns), null, drawLines);
}
private static ColumnLayoutData[] createColumnWeightData(int nColumns) {
ColumnLayoutData[] data= new ColumnLayoutData[nColumns];
for (int i= 0; i < nColumns; i++) {
data[i]= new ColumnWeightData(1);
}
return data;
}
}
protected TableViewer fTable;
protected ILabelProvider fLabelProvider;
protected ListViewerAdapter fListViewerAdapter;
protected List fElements;
protected ViewerSorter fViewerSorter;
protected String[] fButtonLabels;
private Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private int fRemoveButtonIndex;
private int fUpButtonIndex;
private int fDownButtonIndex;
private Label fLastSeparator;
private Control fTableControl;
private Composite fButtonsControl;
private ISelection fSelectionWhenEnabled;
private IListAdapter fListAdapter;
private Object fParentElement;
private ColumnsDescription fTableColumns;
/**
* Creates the <code>ListDialogField</code>.
* @param adapter A listener for button invocation, selection changes. Can
* be <code>null</code>.
* @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and
* marks a separator.
* @param lprovider The label provider to render the table entries
*/
public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
super();
fListAdapter= adapter;
fLabelProvider= lprovider;
fListViewerAdapter= new ListViewerAdapter();
fParentElement= this;
fElements= new ArrayList(10);
fButtonLabels= buttonLabels;
if (fButtonLabels != null) {
int nButtons= fButtonLabels.length;
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsEnabled[i]= true;
}
}
fTable= null;
fTableControl= null;
fButtonsControl= null;
fTableColumns= null;
fRemoveButtonIndex= -1;
fUpButtonIndex= -1;
fDownButtonIndex= -1;
}
/**
* Sets the index of the 'remove' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'remove' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setRemoveButtonIndex(int removeButtonIndex) {
Assert.isTrue(removeButtonIndex < fButtonLabels.length);
fRemoveButtonIndex= removeButtonIndex;
}
/**
* Sets the index of the 'up' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'up' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setUpButtonIndex(int upButtonIndex) {
Assert.isTrue(upButtonIndex < fButtonLabels.length);
fUpButtonIndex= upButtonIndex;
}
/**
* Sets the index of the 'down' button in the button label array passed in the constructor.
* The behaviour of the button marked as the 'down' button will then be handled internally.
* (enable state, button invocation behaviour)
*/
public void setDownButtonIndex(int downButtonIndex) {
Assert.isTrue(downButtonIndex < fButtonLabels.length);
fDownButtonIndex= downButtonIndex;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setViewerSorter(ViewerSorter viewerSorter) {
fViewerSorter= viewerSorter;
}
public void setTableColumns(ColumnsDescription column) {
fTableColumns= column;
}
// ------ adapter communication
private void buttonPressed(int index) {
if (!managedButtonPressed(index) && fListAdapter != null) {
fListAdapter.customButtonPressed(this, index);
}
}
/**
* Checks if the button pressed is handled internally
* @return Returns true if button has been handled.
*/
protected boolean managedButtonPressed(int index) {
if (index == fRemoveButtonIndex) {
remove();
} else if (index == fUpButtonIndex) {
up();
} else if (index == fDownButtonIndex) {
down();
} else {
return false;
}
return true;
}
// ------ layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
PixelConverter converter= new PixelConverter(parent);
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
GridData gd= gridDataForLabel(1);
gd.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
Control list= getListControl(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= nColumns - 2;
gd.widthHint= converter.convertWidthInCharsToPixels(50);
gd.heightHint= converter.convertHeightInCharsToPixels(6);
list.setLayoutData(gd);
Composite buttons= getButtonBox(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= 1;
buttons.setLayoutData(gd);
return new Control[] { label, list, buttons };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
/**
* Sets the minimal width of the buttons. Must be called after widget creation.
*/
public void setButtonsMinWidth(int minWidth) {
if (fLastSeparator != null) {
((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth;
}
}
// ------ ui creation
/**
* Returns the list control. When called the first time, the control will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Control getListControl(Composite parent) {
if (fTableControl == null) {
assertCompositeNotNull(parent);
if (fTableColumns == null) {
fTable= createTableViewer(parent);
Table tableControl= fTable.getTable();
fTableControl= tableControl;
tableControl.setLayout(new TableLayout());
} else {
TableLayoutComposite composite= new TableLayoutComposite(parent, SWT.NONE);
fTableControl= composite;
fTable= createTableViewer(composite);
Table tableControl= fTable.getTable();
tableControl.setHeaderVisible(fTableColumns.headers != null);
tableControl.setLinesVisible(fTableColumns.drawLines);
ColumnLayoutData[] columns= fTableColumns.columns;
for (int i= 0; i < columns.length; i++) {
composite.addColumnData(columns[i]);
TableColumn column= new TableColumn(tableControl, SWT.NONE);
//tableLayout.addColumnData(columns[i]);
if (fTableColumns.headers != null) {
column.setText(fTableColumns.headers[i]);
}
}
}
fTable.getTable().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
//fTableControl.setLayout(tableLayout);
fTable.setContentProvider(fListViewerAdapter);
fTable.setLabelProvider(fLabelProvider);
fTable.addSelectionChangedListener(fListViewerAdapter);
fTable.addDoubleClickListener(fListViewerAdapter);
fTable.setInput(fParentElement);
if (fViewerSorter != null) {
fTable.setSorter(fViewerSorter);
}
fTableControl.setEnabled(isEnabled());
if (fSelectionWhenEnabled != null) {
postSetSelection(fSelectionWhenEnabled);
}
}
return fTableControl;
}
/**
* Returns the internally used table viewer.
*/
public TableViewer getTableViewer() {
return fTable;
}
/*
* Subclasses may override to specify a different style.
*/
protected int getListStyle(){
int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ;
if (fTableColumns != null) {
style |= SWT.FULL_SELECTION;
}
return style;
}
protected TableViewer createTableViewer(Composite parent) {
Table table= new Table(parent, getListStyle());
return new TableViewer(table);
}
protected Button createButton(Composite parent, String label, SelectionListener listener) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.addSelectionListener(listener);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private Label createSeparator(Composite parent) {
Label separator= new Label(parent, SWT.NONE);
separator.setVisible(false);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= 4;
separator.setLayoutData(gd);
return separator;
}
/**
* Returns the composite containing the buttons. When called the first time, the control
* will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getButtonBox(Composite parent) {
if (fButtonsControl == null) {
assertCompositeNotNull(parent);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doButtonSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doButtonSelected(e);
}
};
Composite contents= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
contents.setLayout(layout);
if (fButtonLabels != null) {
fButtonControls= new Button[fButtonLabels.length];
for (int i= 0; i < fButtonLabels.length; i++) {
String currLabel= fButtonLabels[i];
if (currLabel != null) {
fButtonControls[i]= createButton(contents, currLabel, listener);
fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
} else {
fButtonControls[i]= null;
createSeparator(contents);
}
}
}
fLastSeparator= createSeparator(contents);
updateButtonState();
fButtonsControl= contents;
}
return fButtonsControl;
}
private void doButtonSelected(SelectionEvent e) {
if (fButtonControls != null) {
for (int i= 0; i < fButtonControls.length; i++) {
if (e.widget == fButtonControls[i]) {
buttonPressed(i);
return;
}
}
}
}
/**
* Handles key events in the table viewer. Specifically
* when the delete key is pressed.
*/
protected void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) {
managedButtonPressed(fRemoveButtonIndex);
}
}
}
// ------ enable / disable management
/*
* @see DialogField#dialogFieldChanged
*/
public void dialogFieldChanged() {
super.dialogFieldChanged();
updateButtonState();
}
/*
* Updates the enable state of the all buttons
*/
protected void updateButtonState() {
if (fButtonControls != null) {
ISelection sel= fTable.getSelection();
for (int i= 0; i < fButtonControls.length; i++) {
Button button= fButtonControls[i];
if (isOkToUse(button)) {
button.setEnabled(isButtonEnabled(sel, i));
}
}
}
}
protected boolean getManagedButtonState(ISelection sel, int index) {
if (index == fRemoveButtonIndex) {
return !sel.isEmpty();
} else if (index == fUpButtonIndex) {
return !sel.isEmpty() && canMoveUp();
} else if (index == fDownButtonIndex) {
return !sel.isEmpty() && canMoveDown();
}
return true;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
boolean enabled= isEnabled();
if (isOkToUse(fTableControl)) {
if (!enabled) {
fSelectionWhenEnabled= fTable.getSelection();
selectElements(null);
} else {
selectElements(fSelectionWhenEnabled);
fSelectionWhenEnabled= null;
}
fTableControl.setEnabled(enabled);
}
updateButtonState();
}
/**
* Sets a button enabled or disabled.
*/
public void enableButton(int index, boolean enable) {
if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
updateButtonState();
}
}
private boolean isButtonEnabled(ISelection sel, int index) {
boolean extraState= getManagedButtonState(sel, index);
return isEnabled() && extraState && fButtonsEnabled[index];
}
// ------ model access
/**
* Sets the elements shown in the list.
*/
public void setElements(List elements) {
fElements= new ArrayList(elements);
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
/**
* Gets the elements shown in the list.
* The list returned is a copy, so it can be modified by the user.
*/
public List getElements() {
return new ArrayList(fElements);
}
/**
* Gets the elements shown at the given index.
*/
public Object getElement(int index) {
return fElements.get(index);
}
/**
* Gets the index of an element in the list or -1 if element is not in list.
*/
public int getIndexOfElement(Object elem) {
return fElements.indexOf(elem);
}
/**
* Replace an element.
*/
public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
int idx= fElements.indexOf(oldElement);
if (idx != -1) {
fElements.set(idx, newElement);
if (fTable != null) {
List selected= getSelectedElements();
if (selected.remove(oldElement)) {
selected.add(newElement);
}
fTable.refresh();
selectElements(new StructuredSelection(selected));
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Adds an element at the end of the list.
*/
public void addElement(Object element) {
if (fElements.contains(element)) {
return;
}
fElements.add(element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds elements at the end of the list.
*/
public void addElements(List elements) {
int nElements= elements.size();
if (nElements > 0) {
// filter duplicated
ArrayList elementsToAdd= new ArrayList(nElements);
for (int i= 0; i < nElements; i++) {
Object elem= elements.get(i);
if (!fElements.contains(elem)) {
elementsToAdd.add(elem);
}
}
fElements.addAll(elementsToAdd);
if (fTable != null) {
fTable.add(elementsToAdd.toArray());
}
dialogFieldChanged();
}
}
/**
* Adds an element at a position.
*/
public void insertElementAt(Object element, int index) {
if (fElements.contains(element)) {
return;
}
fElements.add(index, element);
if (fTable != null) {
fTable.add(element);
}
dialogFieldChanged();
}
/**
* Adds an element at a position.
*/
public void removeAllElements() {
if (fElements.size() > 0) {
fElements.clear();
if (fTable != null) {
fTable.refresh();
}
dialogFieldChanged();
}
}
/**
* Removes an element from the list.
*/
public void removeElement(Object element) throws IllegalArgumentException {
if (fElements.remove(element)) {
if (fTable != null) {
fTable.remove(element);
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes elements from the list.
*/
public void removeElements(List elements) {
if (elements.size() > 0) {
fElements.removeAll(elements);
if (fTable != null) {
fTable.remove(elements.toArray());
}
dialogFieldChanged();
}
}
/**
* Gets the number of elements
*/
public int getSize() {
return fElements.size();
}
public void selectElements(ISelection selection) {
fSelectionWhenEnabled= selection;
if (fTable != null) {
fTable.setSelection(selection, true);
}
}
public void selectFirstElement() {
Object element= null;
if (fViewerSorter != null) {
Object[] arr= fElements.toArray();
fViewerSorter.sort(fTable, arr);
if (arr.length > 0) {
element= arr[0];
}
} else {
if (fElements.size() > 0) {
element= fElements.get(0);
}
}
if (element != null) {
selectElements(new StructuredSelection(element));
}
}
public void postSetSelection(final ISelection selection) {
if (isOkToUse(fTableControl)) {
Display d= fTableControl.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (isOkToUse(fTableControl)) {
selectElements(selection);
}
}
});
}
}
/**
* Refreshes the table.
*/
public void refresh() {
if (fTable != null) {
fTable.refresh();
}
}
// ------- list maintenance
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private void moveUp(List toMoveUp) {
if (toMoveUp.size() > 0) {
setElements(moveUp(fElements, toMoveUp));
fTable.reveal(toMoveUp.get(0));
}
}
private void moveDown(List toMoveDown) {
if (toMoveDown.size() > 0) {
setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
fTable.reveal(toMoveDown.get(toMoveDown.size() - 1));
}
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size()-1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
private void remove() {
removeElements(getSelectedElements());
}
private void up() {
moveUp(getSelectedElements());
}
private void down() {
moveDown(getSelectedElements());
}
private boolean canMoveUp() {
if (isOkToUse(fTableControl)) {
int[] indc= fTable.getTable().getSelectionIndices();
for (int i= 0; i < indc.length; i++) {
if (indc[i] != i) {
return true;
}
}
}
return false;
}
private boolean canMoveDown() {
if (isOkToUse(fTableControl)) {
int[] indc= fTable.getTable().getSelectionIndices();
int k= fElements.size() - 1;
for (int i= indc.length - 1; i >= 0 ; i--, k--) {
if (indc[i] != k) {
return true;
}
}
}
return false;
}
/**
* Returns the selected elements.
*/
public List getSelectedElements() {
List result= new ArrayList();
if (fTable != null) {
ISelection selection= fTable.getSelection();
if (selection instanceof IStructuredSelection) {
Iterator iter= ((IStructuredSelection)selection).iterator();
while (iter.hasNext()) {
result.add(iter.next());
}
}
}
return result;
}
// ------- ListViewerAdapter
private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener, IDoubleClickListener {
// ------- ITableContentProvider Interface ------------
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// will never happen
}
public boolean isDeleted(Object element) {
return false;
}
public void dispose() {
}
public Object[] getElements(Object obj) {
return fElements.toArray();
}
// ------- ISelectionChangedListener Interface ------------
public void selectionChanged(SelectionChangedEvent event) {
doListSelected(event);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event) {
doDoubleClick(event);
}
}
protected void doListSelected(SelectionChangedEvent event) {
updateButtonState();
if (fListAdapter != null) {
fListAdapter.selectionChanged(this);
}
}
protected void doDoubleClick(DoubleClickEvent event) {
if (fListAdapter != null) {
fListAdapter.doubleClicked(this);
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/SelectionButtonDialogField.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* Dialog Field containing a single button such as a radio or checkbox button.
*/
public class SelectionButtonDialogField extends DialogField {
private Button fButton;
private boolean fIsSelected;
private DialogField[] fAttachedDialogFields;
private int fButtonStyle;
/**
* Creates a selection button.
* Allowed button styles: SWT.RADIO, SWT.CHECK, SWT.TOGGLE, SWT.PUSH
*/
public SelectionButtonDialogField(int buttonStyle) {
super();
fIsSelected= false;
fAttachedDialogFields= null;
fButtonStyle= buttonStyle;
}
/**
* Attaches a field to the selection state of the selection button.
* The attached field will be disabled if the selection button is not selected.
*/
public void attachDialogField(DialogField dialogField) {
attachDialogFields(new DialogField[] { dialogField });
}
/**
* Attaches fields to the selection state of the selection button.
* The attached fields will be disabled if the selection button is not selected.
*/
public void attachDialogFields(DialogField[] dialogFields) {
fAttachedDialogFields= dialogFields;
for (int i= 0; i < dialogFields.length; i++) {
dialogFields[i].setEnabled(fIsSelected);
}
}
/**
* Returns <code>true</code> is teh gived field is attached to the selection button.
*/
public boolean isAttached(DialogField editor) {
if (fAttachedDialogFields != null) {
for (int i=0; i < fAttachedDialogFields.length; i++) {
if (fAttachedDialogFields[i] == editor) {
return true;
}
}
}
return false;
}
// ------- layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
Button button= getSelectionButton(parent);
GridData gd= new GridData();
gd.horizontalSpan= nColumns;
gd.horizontalAlignment= GridData.FILL;
if (fButtonStyle == SWT.PUSH) {
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
}
button.setLayoutData(gd);
return new Control[] { button };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 1;
}
// ------- ui creation
/**
* Returns the selection button widget. When called the first time, the widget will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Button getSelectionButton(Composite group) {
if (fButton == null) {
assertCompositeNotNull(group);
fButton= new Button(group, fButtonStyle);
fButton.setFont(group.getFont());
fButton.setText(fLabelText);
fButton.setEnabled(isEnabled());
fButton.setSelection(fIsSelected);
fButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doWidgetSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doWidgetSelected(e);
}
});
}
return fButton;
}
private void doWidgetSelected(SelectionEvent e) {
if (isOkToUse(fButton)) {
changeValue(fButton.getSelection());
}
}
private void changeValue(boolean newState) {
if (fIsSelected != newState) {
fIsSelected= newState;
if (fAttachedDialogFields != null) {
boolean focusSet= false;
for (int i= 0; i < fAttachedDialogFields.length; i++) {
fAttachedDialogFields[i].setEnabled(fIsSelected);
if (fIsSelected && !focusSet) {
focusSet= fAttachedDialogFields[i].setFocus();
}
}
}
dialogFieldChanged();
} else if (fButtonStyle == SWT.PUSH) {
dialogFieldChanged();
}
}
// ------ model access
/**
* Returns the selection state of the button.
*/
public boolean isSelected() {
return fIsSelected;
}
/**
* Sets the selection state of the button.
*/
public void setSelection(boolean selected) {
changeValue(selected);
if (isOkToUse(fButton)) {
fButton.setSelection(selected);
}
}
// ------ enable / disable management
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
if (isOkToUse(fButton)) {
fButton.setEnabled(isEnabled());
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/Separator.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.layout.GridData;
/**
* Dialog field describing a separator.
*/
public class Separator extends DialogField {
private Label fSeparator;
private int fStyle;
public Separator() {
this(SWT.NONE);
}
/**
* @param style of the separator. See <code>Label</code> for possible
* styles.
*/
public Separator(int style) {
super();
fStyle= style;
}
// ------- layout helpers
/**
* Creates the separator and fills it in a MGridLayout.
* @param height The heigth of the separator
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns, int height) {
assertEnoughColumns(nColumns);
Control separator= getSeparator(parent);
separator.setLayoutData(gridDataForSeperator(nColumns, height));
return new Control[] { separator };
}
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
return doFillIntoGrid(parent, nColumns, 4);
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 1;
}
protected static GridData gridDataForSeperator(int span, int height) {
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= height;
gd.horizontalSpan= span;
return gd;
}
// ------- ui creation
/**
* Creates or returns the created separator.
* @param parent The parent composite or <code>null</code> if the widget has
* already been created.
*/
public Control getSeparator(Composite parent) {
if (fSeparator == null) {
assertCompositeNotNull(parent);
fSeparator= new Label(parent, fStyle);
}
return fSeparator;
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/StringButtonDialogField.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* Dialog field containing a label, text control and a button control.
*/
public class StringButtonDialogField extends StringDialogField {
private Button fBrowseButton;
private String fBrowseButtonLabel;
private IStringButtonAdapter fStringButtonAdapter;
private boolean fButtonEnabled;
public StringButtonDialogField(IStringButtonAdapter adapter) {
super();
fStringButtonAdapter= adapter;
fBrowseButtonLabel= "!Browse...!"; //$NON-NLS-1$
fButtonEnabled= true;
}
/**
* Sets the label of the button.
*/
public void setButtonLabel(String label) {
fBrowseButtonLabel= label;
}
// ------ adapter communication
/**
* Programmatical pressing of the button
*/
public void changeControlPressed() {
fStringButtonAdapter.changeControlPressed(this);
}
// ------- layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
label.setLayoutData(gridDataForLabel(1));
Text text= getTextControl(parent);
text.setLayoutData(gridDataForText(nColumns - 2));
Button button= getChangeControl(parent);
button.setLayoutData(gridDataForButton(button, 1));
return new Control[] { label, text, button };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
protected static GridData gridDataForButton(Button button, int span) {
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.horizontalSpan= span;
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
return gd;
}
// ------- ui creation
/**
* Creates or returns the created buttom widget.
* @param parent The parent composite or <code>null</code> if the widget has
* already been created.
*/
public Button getChangeControl(Composite parent) {
if (fBrowseButton == null) {
assertCompositeNotNull(parent);
fBrowseButton= new Button(parent, SWT.PUSH);
fBrowseButton.setText(fBrowseButtonLabel);
fBrowseButton.setEnabled(isEnabled() && fButtonEnabled);
fBrowseButton.addSelectionListener(new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
changeControlPressed();
}
public void widgetSelected(SelectionEvent e) {
changeControlPressed();
}
});
}
return fBrowseButton;
}
// ------ enable / disable management
/**
* Sets the enable state of the button.
*/
public void enableButton(boolean enable) {
if (isOkToUse(fBrowseButton)) {
fBrowseButton.setEnabled(isEnabled() && enable);
}
fButtonEnabled= enable;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
if (isOkToUse(fBrowseButton)) {
fBrowseButton.setEnabled(isEnabled() && fButtonEnabled);
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/TreeListDialogField.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.wizards.dialogfields;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
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.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
/**
* A list with a button bar.
* Typical buttons are 'Add', 'Remove', 'Up' and 'Down'.
* List model is independend of widget creation.
* DialogFields controls are: Label, List and Composite containing buttons.
*/
public class TreeListDialogField extends DialogField {
protected TreeViewer fTree;
protected ILabelProvider fLabelProvider;
protected TreeViewerAdapter fTreeViewerAdapter;
protected List fElements;
protected ViewerSorter fViewerSorter;
protected String[] fButtonLabels;
private Button[] fButtonControls;
private boolean[] fButtonsEnabled;
private int fRemoveButtonIndex;
private int fUpButtonIndex;
private int fDownButtonIndex;
private Label fLastSeparator;
private Tree fTreeControl;
private Composite fButtonsControl;
private ISelection fSelectionWhenEnabled;
private ITreeListAdapter fTreeAdapter;
private Object fParentElement;
private int fTreeExpandLevel;
/**
* @param adapter Can be <code>null</code>.
*/
public TreeListDialogField(ITreeListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) {
super();
fTreeAdapter= adapter;
fLabelProvider= lprovider;
fTreeViewerAdapter= new TreeViewerAdapter();
fParentElement= this;
fElements= new ArrayList(10);
fButtonLabels= buttonLabels;
if (fButtonLabels != null) {
int nButtons= fButtonLabels.length;
fButtonsEnabled= new boolean[nButtons];
for (int i= 0; i < nButtons; i++) {
fButtonsEnabled[i]= true;
}
}
fTree= null;
fTreeControl= null;
fButtonsControl= null;
fRemoveButtonIndex= -1;
fUpButtonIndex= -1;
fDownButtonIndex= -1;
fTreeExpandLevel= 0;
}
/**
* Sets the index of the 'remove' button in the button label array passed in
* the constructor. The behaviour of the button marked as the 'remove' button
* will then behandled internally. (enable state, button invocation
* behaviour)
*/
public void setRemoveButtonIndex(int removeButtonIndex) {
Assert.isTrue(removeButtonIndex < fButtonLabels.length);
fRemoveButtonIndex= removeButtonIndex;
}
/**
* Sets the index of the 'up' button in the button label array passed in the
* constructor. The behaviour of the button marked as the 'up' button will
* then behandled internally.
* (enable state, button invocation behaviour)
*/
public void setUpButtonIndex(int upButtonIndex) {
Assert.isTrue(upButtonIndex < fButtonLabels.length);
fUpButtonIndex= upButtonIndex;
}
/**
* Sets the index of the 'down' button in the button label array passed in
* the constructor. The behaviour of the button marked as the 'down' button
* will then be handled internally. (enable state, button invocation
* behaviour)
*/
public void setDownButtonIndex(int downButtonIndex) {
Assert.isTrue(downButtonIndex < fButtonLabels.length);
fDownButtonIndex= downButtonIndex;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setViewerSorter(ViewerSorter viewerSorter) {
fViewerSorter= viewerSorter;
}
/**
* Sets the viewerSorter.
* @param viewerSorter The viewerSorter to set
*/
public void setTreeExpansionLevel(int level) {
fTreeExpandLevel= level;
if (fTree != null) {
fTree.expandToLevel(level);
}
}
// ------ adapter communication
private void buttonPressed(int index) {
if (!managedButtonPressed(index) && fTreeAdapter != null) {
fTreeAdapter.customButtonPressed(this, index);
}
}
/**
* Checks if the button pressed is handled internally
* @return Returns true if button has been handled.
*/
protected boolean managedButtonPressed(int index) {
if (index == fRemoveButtonIndex) {
remove();
} else if (index == fUpButtonIndex) {
up();
} else if (index == fDownButtonIndex) {
down();
} else {
return false;
}
return true;
}
// ------ layout helpers
/*
* @see DialogField#doFillIntoGrid
*/
public Control[] doFillIntoGrid(Composite parent, int nColumns) {
PixelConverter converter= new PixelConverter(parent);
assertEnoughColumns(nColumns);
Label label= getLabelControl(parent);
GridData gd= gridDataForLabel(1);
gd.verticalAlignment= GridData.BEGINNING;
label.setLayoutData(gd);
Control list= getTreeControl(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= nColumns - 2;
gd.widthHint= converter.convertWidthInCharsToPixels(50);
gd.heightHint= converter.convertHeightInCharsToPixels(6);
list.setLayoutData(gd);
Composite buttons= getButtonBox(parent);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= false;
gd.verticalAlignment= GridData.FILL;
gd.grabExcessVerticalSpace= true;
gd.horizontalSpan= 1;
buttons.setLayoutData(gd);
return new Control[] { label, list, buttons };
}
/*
* @see DialogField#getNumberOfControls
*/
public int getNumberOfControls() {
return 3;
}
/**
* Sets the minimal width of the buttons. Must be called after widget creation.
*/
public void setButtonsMinWidth(int minWidth) {
if (fLastSeparator != null) {
((GridData) fLastSeparator.getLayoutData()).widthHint= minWidth;
}
}
// ------ ui creation
/**
* Returns the tree control. When called the first time, the control will be
* created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Control getTreeControl(Composite parent) {
if (fTreeControl == null) {
assertCompositeNotNull(parent);
fTree= createTreeViewer(parent);
fTreeControl= (Tree) fTree.getControl();
fTreeControl.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
fTree.setAutoExpandLevel(99);
fTree.setContentProvider(fTreeViewerAdapter);
fTree.setLabelProvider(fLabelProvider);
fTree.addSelectionChangedListener(fTreeViewerAdapter);
fTree.addDoubleClickListener(fTreeViewerAdapter);
fTree.setInput(fParentElement);
fTree.expandToLevel(fTreeExpandLevel);
if (fViewerSorter != null) {
fTree.setSorter(fViewerSorter);
}
fTreeControl.setEnabled(isEnabled());
if (fSelectionWhenEnabled != null) {
postSetSelection(fSelectionWhenEnabled);
}
}
return fTreeControl;
}
/**
* Returns the internally used table viewer.
*/
public TreeViewer getTreeViewer() {
return fTree;
}
/*
* Subclasses may override to specify a different style.
*/
protected int getTreeStyle() {
int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL;
return style;
}
protected TreeViewer createTreeViewer(Composite parent) {
Tree tree= new Tree(parent, getTreeStyle());
return new TreeViewer(tree);
}
protected Button createButton(Composite parent, String label, SelectionListener listener) {
Button button= new Button(parent, SWT.PUSH);
button.setText(label);
button.addSelectionListener(listener);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.grabExcessHorizontalSpace= true;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= SWTUtil.getButtonHeigthHint(button);
gd.widthHint= SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
return button;
}
private Label createSeparator(Composite parent) {
Label separator= new Label(parent, SWT.NONE);
separator.setVisible(false);
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.BEGINNING;
gd.heightHint= 4;
separator.setLayoutData(gd);
return separator;
}
/**
* Returns the composite containing the buttons. When called the first time, the control
* will be created.
* @param The parent composite when called the first time, or <code>null</code>
* after.
*/
public Composite getButtonBox(Composite parent) {
if (fButtonsControl == null) {
assertCompositeNotNull(parent);
SelectionListener listener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {
doButtonSelected(e);
}
public void widgetSelected(SelectionEvent e) {
doButtonSelected(e);
}
};
Composite contents= new Composite(parent, SWT.NULL);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
contents.setLayout(layout);
if (fButtonLabels != null) {
fButtonControls= new Button[fButtonLabels.length];
for (int i= 0; i < fButtonLabels.length; i++) {
String currLabel= fButtonLabels[i];
if (currLabel != null) {
fButtonControls[i]= createButton(contents, currLabel, listener);
fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]);
} else {
fButtonControls[i]= null;
createSeparator(contents);
}
}
}
fLastSeparator= createSeparator(contents);
updateButtonState();
fButtonsControl= contents;
}
return fButtonsControl;
}
private void doButtonSelected(SelectionEvent e) {
if (fButtonControls != null) {
for (int i= 0; i < fButtonControls.length; i++) {
if (e.widget == fButtonControls[i]) {
buttonPressed(i);
return;
}
}
}
}
/**
* Handles key events in the table viewer. Specifically
* when the delete key is pressed.
*/
protected void handleKeyPressed(KeyEvent event) {
if (event.character == SWT.DEL && event.stateMask == 0) {
if (fRemoveButtonIndex != -1 && isButtonEnabled(fTree.getSelection(), fRemoveButtonIndex)) {
managedButtonPressed(fRemoveButtonIndex);
return;
}
}
fTreeAdapter.keyPressed(this, event);
}
// ------ enable / disable management
/*
* @see DialogField#dialogFieldChanged
*/
public void dialogFieldChanged() {
super.dialogFieldChanged();
updateButtonState();
}
/*
* Updates the enable state of the all buttons
*/
protected void updateButtonState() {
if (fButtonControls != null) {
ISelection sel= fTree.getSelection();
for (int i= 0; i < fButtonControls.length; i++) {
Button button= fButtonControls[i];
if (isOkToUse(button)) {
button.setEnabled(isButtonEnabled(sel, i));
}
}
}
}
protected boolean containsAttributes(List selected) {
for (int i= 0; i < selected.size(); i++) {
if (!fElements.contains(selected.get(i))) {
return true;
}
}
return false;
}
protected boolean getManagedButtonState(ISelection sel, int index) {
List selected= getSelectedElements();
boolean hasAttributes= containsAttributes(selected);
if (index == fRemoveButtonIndex) {
return !selected.isEmpty() && !hasAttributes;
} else if (index == fUpButtonIndex) {
return !sel.isEmpty() && !hasAttributes && canMoveUp(selected);
} else if (index == fDownButtonIndex) {
return !sel.isEmpty() && !hasAttributes && canMoveDown(selected);
}
return true;
}
/*
* @see DialogField#updateEnableState
*/
protected void updateEnableState() {
super.updateEnableState();
boolean enabled= isEnabled();
if (isOkToUse(fTreeControl)) {
if (!enabled) {
fSelectionWhenEnabled= fTree.getSelection();
selectElements(null);
} else {
selectElements(fSelectionWhenEnabled);
fSelectionWhenEnabled= null;
}
fTreeControl.setEnabled(enabled);
}
updateButtonState();
}
/**
* Sets a button enabled or disabled.
*/
public void enableButton(int index, boolean enable) {
if (fButtonsEnabled != null && index < fButtonsEnabled.length) {
fButtonsEnabled[index]= enable;
updateButtonState();
}
}
private boolean isButtonEnabled(ISelection sel, int index) {
boolean extraState= getManagedButtonState(sel, index);
return isEnabled() && extraState && fButtonsEnabled[index];
}
// ------ model access
/**
* Sets the elements shown in the list.
*/
public void setElements(List elements) {
fElements= new ArrayList(elements);
refresh();
if (fTree != null) {
fTree.expandToLevel(fTreeExpandLevel);
}
dialogFieldChanged();
}
/**
* Gets the elements shown in the list.
* The list returned is a copy, so it can be modified by the user.
*/
public List getElements() {
return new ArrayList(fElements);
}
/**
* Gets the element shown at the given index.
*/
public Object getElement(int index) {
return fElements.get(index);
}
/**
* Gets the index of an element in the list or -1 if element is not in list.
*/
public int getIndexOfElement(Object elem) {
return fElements.indexOf(elem);
}
/**
* Replace an element.
*/
public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException {
int idx= fElements.indexOf(oldElement);
if (idx != -1) {
fElements.set(idx, newElement);
if (fTree != null) {
List selected= getSelectedElements();
if (selected.remove(oldElement)) {
selected.add(newElement);
}
boolean isExpanded= fTree.getExpandedState(oldElement);
fTree.remove(oldElement);
fTree.add(fParentElement, newElement);
if (isExpanded) {
fTree.expandToLevel(newElement, fTreeExpandLevel);
}
selectElements(new StructuredSelection(selected));
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Adds an element at the end of the tree list.
*/
public void addElement(Object element) {
if (fElements.contains(element)) {
return;
}
fElements.add(element);
if (fTree != null) {
fTree.add(fParentElement, element);
fTree.expandToLevel(element, fTreeExpandLevel);
}
dialogFieldChanged();
}
/**
* Adds elements at the end of the tree list.
*/
public void addElements(List elements) {
int nElements= elements.size();
if (nElements > 0) {
// filter duplicated
ArrayList elementsToAdd= new ArrayList(nElements);
for (int i= 0; i < nElements; i++) {
Object elem= elements.get(i);
if (!fElements.contains(elem)) {
elementsToAdd.add(elem);
}
}
fElements.addAll(elementsToAdd);
if (fTree != null) {
fTree.add(fParentElement, elementsToAdd.toArray());
for (int i= 0; i < elementsToAdd.size(); i++) {
fTree.expandToLevel(elementsToAdd.get(i), fTreeExpandLevel);
}
}
dialogFieldChanged();
}
}
/**
* Adds an element at a position.
*/
public void insertElementAt(Object element, int index) {
if (fElements.contains(element)) {
return;
}
fElements.add(index, element);
if (fTree != null) {
fTree.add(fParentElement, element);
if (fTreeExpandLevel != -1) {
fTree.expandToLevel(element, fTreeExpandLevel);
}
}
dialogFieldChanged();
}
/**
* Adds an element at a position.
*/
public void removeAllElements() {
if (fElements.size() > 0) {
fElements.clear();
refresh();
dialogFieldChanged();
}
}
/**
* Removes an element from the list.
*/
public void removeElement(Object element) throws IllegalArgumentException {
if (fElements.remove(element)) {
if (fTree != null) {
fTree.remove(element);
}
dialogFieldChanged();
} else {
throw new IllegalArgumentException();
}
}
/**
* Removes elements from the list.
*/
public void removeElements(List elements) {
if (elements.size() > 0) {
fElements.removeAll(elements);
if (fTree != null) {
fTree.remove(elements.toArray());
}
dialogFieldChanged();
}
}
/**
* Gets the number of elements
*/
public int getSize() {
return fElements.size();
}
public void selectElements(ISelection selection) {
fSelectionWhenEnabled= selection;
if (fTree != null) {
fTree.setSelection(selection, true);
}
}
public void selectFirstElement() {
Object element= null;
if (fViewerSorter != null) {
Object[] arr= fElements.toArray();
fViewerSorter.sort(fTree, arr);
if (arr.length > 0) {
element= arr[0];
}
} else {
if (fElements.size() > 0) {
element= fElements.get(0);
}
}
if (element != null) {
selectElements(new StructuredSelection(element));
}
}
public void postSetSelection(final ISelection selection) {
if (isOkToUse(fTreeControl)) {
Display d= fTreeControl.getDisplay();
d.asyncExec(new Runnable() {
public void run() {
if (isOkToUse(fTreeControl)) {
selectElements(selection);
}
}
});
}
}
/**
* Refreshes the tree.
*/
public void refresh() {
if (fTree != null) {
fTree.refresh();
}
}
/**
* Refreshes the tree.
*/
public void refresh(Object element) {
if (fTree != null) {
fTree.refresh(element);
}
}
// ------- list maintenance
private List moveUp(List elements, List move) {
int nElements= elements.size();
List res= new ArrayList(nElements);
Object floating= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (move.contains(curr)) {
res.add(curr);
} else {
if (floating != null) {
res.add(floating);
}
floating= curr;
}
}
if (floating != null) {
res.add(floating);
}
return res;
}
private void moveUp(List toMoveUp) {
if (toMoveUp.size() > 0) {
setElements(moveUp(fElements, toMoveUp));
fTree.reveal(toMoveUp.get(0));
}
}
private void moveDown(List toMoveDown) {
if (toMoveDown.size() > 0) {
setElements(reverse(moveUp(reverse(fElements), toMoveDown)));
fTree.reveal(toMoveDown.get(toMoveDown.size() - 1));
}
}
private List reverse(List p) {
List reverse= new ArrayList(p.size());
for (int i= p.size() - 1; i >= 0; i--) {
reverse.add(p.get(i));
}
return reverse;
}
private void remove() {
removeElements(getSelectedElements());
}
private void up() {
moveUp(getSelectedElements());
}
private void down() {
moveDown(getSelectedElements());
}
private boolean canMoveUp(List selectedElements) {
if (isOkToUse(fTreeControl)) {
int nSelected= selectedElements.size();
int nElements= fElements.size();
for (int i= 0; i < nElements && nSelected > 0; i++) {
if (!selectedElements.contains(fElements.get(i))) {
return true;
}
nSelected--;
}
}
return false;
}
private boolean canMoveDown(List selectedElements) {
if (isOkToUse(fTreeControl)) {
int nSelected= selectedElements.size();
for (int i= fElements.size() - 1; i >= 0 && nSelected > 0; i--) {
if (!selectedElements.contains(fElements.get(i))) {
return true;
}
nSelected--;
}
}
return false;
}
/**
* Returns the selected elements.
*/
public List getSelectedElements() {
ArrayList result= new ArrayList();
if (fTree != null) {
ISelection selection= fTree.getSelection();
if (selection instanceof IStructuredSelection) {
Iterator iter= ((IStructuredSelection)selection).iterator();
while (iter.hasNext()) {
result.add(iter.next());
}
}
}
return result;
}
public void expandElement(Object element, int level) {
if (fTree != null) {
fTree.expandToLevel(element, level);
}
}
// ------- TreeViewerAdapter
private class TreeViewerAdapter implements ITreeContentProvider, ISelectionChangedListener, IDoubleClickListener {
private final Object[] NO_ELEMENTS= new Object[0];
// ------- ITreeContentProvider Interface ------------
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
// will never happen
}
public boolean isDeleted(Object element) {
return false;
}
public void dispose() {
}
public Object[] getElements(Object obj) {
return fElements.toArray();
}
public Object[] getChildren(Object element) {
if (fTreeAdapter != null) {
return fTreeAdapter.getChildren(TreeListDialogField.this, element);
}
return NO_ELEMENTS;
}
public Object getParent(Object element) {
if (!fElements.contains(element) && fTreeAdapter != null) {
return fTreeAdapter.getParent(TreeListDialogField.this, element);
}
return fParentElement;
}
public boolean hasChildren(Object element) {
if (fTreeAdapter != null) {
return fTreeAdapter.hasChildren(TreeListDialogField.this, element);
}
return false;
}
// ------- ISelectionChangedListener Interface ------------
public void selectionChanged(SelectionChangedEvent event) {
doListSelected(event);
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent)
*/
public void doubleClick(DoubleClickEvent event) {
doDoubleClick(event);
}
}
protected void doListSelected(SelectionChangedEvent event) {
updateButtonState();
if (fTreeAdapter != null) {
fTreeAdapter.selectionChanged(this);
}
}
protected void doDoubleClick(DoubleClickEvent event) {
if (fTreeAdapter != null) {
fTreeAdapter.doubleClicked(this);
}
}
}
|
39,038 |
Bug 39038 method SWTUtil.getButtonHeigthHint is misspelled [misc]
|
"getButtonHeigthHint" should be spelled "getButtonHeightHint". The "Height" part is spelled incorrectly. This is an internal API -- package org.eclipse.jdt.internal.ui.util -- so this is not a user-visible bug, strictly speaking, but it would be trivial to fix.
|
resolved fixed
|
aee805e
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:26:29Z | 2003-06-17T20:00: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.List;
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.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
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.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.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.Template;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
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.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
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 IImportsStructure fImportsStructure;
/* package */ ImportsManager(IImportsStructure structure) {
fImportsStructure= structure;
}
/* package */ IImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
return fImportsStructure.addImport(qualifiedTypeName);
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= 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;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <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$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <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
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName("", true); //$NON-NLS-1$
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <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);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null));
}
/**
* 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);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
}
/**
* 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/ceckbox 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);
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);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* 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 dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons || 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 fragement 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 fragement 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 seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <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) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <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(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <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);
}
// ----------- validation ----------
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <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
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <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$
if (cu.getResource().exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <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 superinterfaces 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;
ImportsStructure imports;
int indent= 0;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
// create a working copy with a new owner
createdWorkingCopy= parentCU.getWorkingCopy(null);
imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(pack.getElementName(), getTypeName());
String typeContent= constructTypeStub(new ImportsManager(imports), lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsStructure(parentCU, prefOrder, threshold, true);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
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(new ImportsManager(imports), lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
boolean needsSave= !imports.getCompilationUnit().isWorkingCopy();
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
ICompilationUnit cu= createdType.getCompilationUnit();
synchronized(cu) {
cu.reconcile();
}
createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1));
// add imports
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
synchronized(cu) {
cu.reconcile();
}
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter);
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commit(false, new SubProgressMonitor(monitor, 1));
} else {
if (needsSave) {
buf.save(null, false);
}
monitor.worked(1);
}
if (createdWorkingCopy != null) {
fCreatedType= (IType) createdType.getPrimaryElement();
} else {
fCreatedType= createdType;
}
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.destroy();
}
monitor.done();
}
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
* @since 2.1
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
String typeComment= getTypeComment(cu, lineDelimiter);
IPackageFragment pack= (IPackageFragment) cu.getParent();
String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter);
if (content != null) {
CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray());
if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
return content;
}
}
StringBuffer buf= new StringBuffer();
if (!pack.isDefaultPackage()) {
buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
}
buf.append(lineDelimiter).append(lineDelimiter);
if (typeComment != null) {
buf.append(typeComment).append(lineDelimiter);
}
buf.append(typeContent);
return buf.toString();
}
/**
* Returns the created type. The method only returns a valid type
* after <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();
}
/**
* @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
//deprecated
}
/**
* Hook method that gets called from <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 formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </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 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
*/
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 evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor)
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor);
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <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 neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= null;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
hierarchy= type.newSupertypeHierarchy(monitor);
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
if (hierarchy == null) {
hierarchy= type.newSupertypeHierarchy(monitor);
}
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
35,905 |
Bug 35905 inline method: handles casts incorrectly (missing brackets) [refactoring]
|
20030326 public class Test { private void foo(Object string){ String s1= intern((String)string); } private static String intern(String string){ return string.intern(); } } inline intern(String) - you get compile errors (missing brackets)
|
resolved fixed
|
8f05e04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:34:07Z | 2003-04-01T09:40:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/cast_in/TestReceiverCast.java
| |
35,905 |
Bug 35905 inline method: handles casts incorrectly (missing brackets) [refactoring]
|
20030326 public class Test { private void foo(Object string){ String s1= intern((String)string); } private static String intern(String string){ return string.intern(); } } inline intern(String) - you get compile errors (missing brackets)
|
resolved fixed
|
8f05e04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:34:07Z | 2003-04-01T09:40:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/cast_out/TestReceiverCast.java
| |
35,905 |
Bug 35905 inline method: handles casts incorrectly (missing brackets) [refactoring]
|
20030326 public class Test { private void foo(Object string){ String s1= intern((String)string); } private static String intern(String string){ return string.intern(); } } inline intern(String) - you get compile errors (missing brackets)
|
resolved fixed
|
8f05e04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:34:07Z | 2003-04-01T09:40:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
35,905 |
Bug 35905 inline method: handles casts incorrectly (missing brackets) [refactoring]
|
20030326 public class Test { private void foo(Object string){ String s1= intern((String)string); } private static String intern(String string){ return string.intern(); } } inline intern(String) - you get compile errors (missing brackets)
|
resolved fixed
|
8f05e04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-07-31T16:34:07Z | 2003-04-01T09:40:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
| |
41,028 |
Bug 41028 Java Browsing, Members View: types for fields [browsing]
|
Currently, the Members View of the Java Browsing perspective shows return types for functions, and types for method parameters. It would be helpful to extend this so that fields were also displayed with their type indicated.
|
resolved fixed
|
463d0e7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-04T12:07:07Z | 2003-07-31T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/MembersView.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.browsing;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.jdt.core.IClassFile;
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.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
public class MembersView extends JavaBrowsingPart implements IPropertyChangeListener {
private MemberFilterActionGroup fMemberFilterActionGroup;
public MembersView() {
setHasWorkingSetFilter(false);
setHasCustomSetFilter(true);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES };
}
};
}
return super.getAdapter(key);
}
/**
* Creates and returns the label provider for this part.
*
* @return the label provider
* @see org.eclipse.jface.viewers.ILabelProvider
*/
protected JavaUILabelProvider createLabelProvider() {
return new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.MEMBERS_VIEW;
}
protected String getLinkToEditorKey() {
return PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR;
}
/**
* Creates the the viewer of this part.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI);
fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaUI.ID_MEMBERS_VIEW);
return viewer;
}
protected void fillToolBar(IToolBarManager tbm) {
tbm.add(new LexicalSortingAction(getViewer(), JavaUI.ID_MEMBERS_VIEW));
fMemberFilterActionGroup.contributeToToolBar(tbm);
super.fillToolBar(tbm);
}
/**
* Answers if the given <code>element</code> is a valid
* input for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid input
*/
protected boolean isValidInput(Object element) {
if (element instanceof IType) {
IType type= (IType)element;
return type.isBinary() || type.getDeclaringType() == null;
}
return false;
}
/**
* Answers if the given <code>element</code> is a valid
* element for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid element
*/
protected boolean isValidElement(Object element) {
if (element instanceof IMember)
return super.isValidElement(((IMember)element).getDeclaringType());
else if (element instanceof IImportDeclaration)
return isValidElement(((IJavaElement)element).getParent());
else if (element instanceof IImportContainer) {
Object input= getViewer().getInput();
if (input instanceof IJavaElement) {
ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT);
return cu.equals(importContainerCu);
} else {
IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE);
IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE);
return cf != null && cf.equals(importContainerCf);
}
}
}
return false;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
protected IJavaElement findElementToSelect(IJavaElement je) {
if (je == null)
return null;
switch (je.getElementType()) {
case IJavaElement.TYPE:
if (((IType)je).getDeclaringType() == null)
return null;
// fall through
case IJavaElement.METHOD:
// fall through
case IJavaElement.FIELD:
// fall through
case IJavaElement.PACKAGE_DECLARATION:
// fall through
case IJavaElement.IMPORT_CONTAINER:
return getSuitableJavaElement(je);
case IJavaElement.IMPORT_DECLARATION:
je= getSuitableJavaElement(je);
if (je != null) {
ICompilationUnit cu= (ICompilationUnit)je.getParent().getParent();
try {
if (cu.getImports()[0].equals(je)) {
Object selectedElement= getSingleElementFromSelection(getViewer().getSelection());
if (selectedElement instanceof IImportContainer)
return (IImportContainer)selectedElement;
}
} catch (JavaModelException ex) {
// return je;
}
return je;
}
break;
}
return null;
}
/**
* Finds the closest Java element which can be used as input for
* this part and has the given Java element as child
*
* @param je the Java element for which to search the closest input
* @return the closest Java element used as input for this part
*/
protected IJavaElement findInputForJavaElement(IJavaElement je) {
if (je == null || !je.exists())
return null;
switch (je.getElementType()) {
case IJavaElement.TYPE:
IType type= ((IType)je).getDeclaringType();
if (type == null)
return je;
else
return findInputForJavaElement(type);
case IJavaElement.COMPILATION_UNIT:
return getTypeForCU((ICompilationUnit)je);
case IJavaElement.CLASS_FILE:
try {
return findInputForJavaElement(((IClassFile)je).getType());
} catch (JavaModelException ex) {
return null;
}
case IJavaElement.IMPORT_DECLARATION:
return findInputForJavaElement(je.getParent());
case IJavaElement.PACKAGE_DECLARATION:
case IJavaElement.IMPORT_CONTAINER:
IJavaElement parent= je.getParent();
if (parent instanceof ICompilationUnit) {
return getTypeForCU((ICompilationUnit)parent);
}
else if (parent instanceof IClassFile)
return findInputForJavaElement(parent);
default:
if (je instanceof IMember)
return findInputForJavaElement(((IMember)je).getDeclaringType());
}
return null;
}
/*
* Implements method from IViewPart.
*/
public void saveState(IMemento memento) {
super.saveState(memento);
fMemberFilterActionGroup.saveState(memento);
}
protected void restoreState(IMemento memento) {
super.restoreState(memento);
fMemberFilterActionGroup.restoreState(memento);
getViewer().getControl().setRedraw(false);
getViewer().refresh();
getViewer().getControl().setRedraw(true);
}
protected void hookViewerListeners() {
super.hookViewerListeners();
getViewer().addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
TreeViewer viewer= (TreeViewer)getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element))
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
});
}
boolean isInputAWorkingCopy() {
Object input= getViewer().getInput();
if (input instanceof IJavaElement) {
ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
return cu.isWorkingCopy();
}
return false;
}
protected void restoreSelection() {
IEditorPart editor= getViewSite().getPage().getActiveEditor();
if (editor != null)
setSelectionFromEditor(editor);
}
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER)) {
getViewer().refresh();
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#dispose()
*/
public void dispose() {
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
super.dispose();
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
}
}
|
41,028 |
Bug 41028 Java Browsing, Members View: types for fields [browsing]
|
Currently, the Members View of the Java Browsing perspective shows return types for functions, and types for method parameters. It would be helpful to extend this so that fields were also displayed with their type indicated.
|
resolved fixed
|
463d0e7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-04T12:07:07Z | 2003-07-31T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.resources.IResource;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
public class JavaElementLabels {
/**
* Method names contain parameter types.
* e.g. <code>foo(int)</code>
*/
public final static int M_PARAMETER_TYPES= 1 << 0;
/**
* Method names contain parameter names.
* e.g. <code>foo(index)</code>
*/
public final static int M_PARAMETER_NAMES= 1 << 1;
/**
* Method names contain thrown exceptions.
* e.g. <code>foo throws IOException</code>
*/
public final static int M_EXCEPTIONS= 1 << 2;
/**
* Method names contain return type (appended)
* e.g. <code>foo : int</code>
*/
public final static int M_APP_RETURNTYPE= 1 << 3;
/**
* Method names contain return type (appended)
* e.g. <code>int foo</code>
*/
public final static int M_PRE_RETURNTYPE= 1 << 4;
/**
* Method names are fully qualified.
* e.g. <code>java.util.Vector.size</code>
*/
public final static int M_FULLY_QUALIFIED= 1 << 5;
/**
* Method names are post qualified.
* e.g. <code>size - java.util.Vector</code>
*/
public final static int M_POST_QUALIFIED= 1 << 6;
/**
* Initializer names are fully qualified.
* e.g. <code>java.util.Vector.{ ... }</code>
*/
public final static int I_FULLY_QUALIFIED= 1 << 7;
/**
* Type names are post qualified.
* e.g. <code>{ ... } - java.util.Map</code>
*/
public final static int I_POST_QUALIFIED= 1 << 8;
/**
* Field names contain the declared type (appended)
* e.g. <code>int fHello</code>
*/
public final static int F_APP_TYPE_SIGNATURE= 1 << 9;
/**
* Field names contain the declared type (prepended)
* e.g. <code>fHello : int</code>
*/
public final static int F_PRE_TYPE_SIGNATURE= 1 << 10;
/**
* Fields names are fully qualified.
* e.g. <code>java.lang.System.out</code>
*/
public final static int F_FULLY_QUALIFIED= 1 << 11;
/**
* Fields names are post qualified.
* e.g. <code>out - java.lang.System</code>
*/
public final static int F_POST_QUALIFIED= 1 << 12;
/**
* Type names are fully qualified.
* e.g. <code>java.util.Map.MapEntry</code>
*/
public final static int T_FULLY_QUALIFIED= 1 << 13;
/**
* Type names are type container qualified.
* e.g. <code>Map.MapEntry</code>
*/
public final static int T_CONTAINER_QUALIFIED= 1 << 14;
/**
* Type names are post qualified.
* e.g. <code>MapEntry - java.util.Map</code>
*/
public final static int T_POST_QUALIFIED= 1 << 15;
/**
* Declarations (import container / declarartion, package declarartion) are qualified.
* e.g. <code>java.util.Vector.class/import container</code>
*/
public final static int D_QUALIFIED= 1 << 16;
/**
* Declarations (import container / declarartion, package declarartion) are post qualified.
* e.g. <code>import container - java.util.Vector.class</code>
*/
public final static int D_POST_QUALIFIED= 1 << 17;
/**
* Class file names are fully qualified.
* e.g. <code>java.util.Vector.class</code>
*/
public final static int CF_QUALIFIED= 1 << 18;
/**
* Class file names are post qualified.
* e.g. <code>Vector.class - java.util</code>
*/
public final static int CF_POST_QUALIFIED= 1 << 19;
/**
* Compilation unit names are fully qualified.
* e.g. <code>java.util.Vector.java</code>
*/
public final static int CU_QUALIFIED= 1 << 20;
/**
* Compilation unit names are post qualified.
* e.g. <code>Vector.java - java.util</code>
*/
public final static int CU_POST_QUALIFIED= 1 << 21;
/**
* Package names are qualified.
* e.g. <code>MyProject/src/java.util</code>
*/
public final static int P_QUALIFIED= 1 << 22;
/**
* Package names are post qualified.
* e.g. <code>java.util - MyProject/src</code>
*/
public final static int P_POST_QUALIFIED= 1 << 23;
/**
* Package Fragment Roots contain variable name if from a variable.
* e.g. <code>JRE_LIB - c:\java\lib\rt.jar</code>
*/
public final static int ROOT_VARIABLE= 1 << 24;
/**
* Package Fragment Roots contain the project name if not an archive (prepended).
* e.g. <code>MyProject/src</code>
*/
public final static int ROOT_QUALIFIED= 1 << 25;
/**
* Package Fragment Roots contain the project name if not an archive (appended).
* e.g. <code>src - MyProject</code>
*/
public final static int ROOT_POST_QUALIFIED= 1 << 26;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int APPEND_ROOT_PATH= 1 << 27;
/**
* Add root path to all elements except Package Fragment Roots and Java projects.
* e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code>
* Option only applies to getElementLabel
*/
public final static int PREPEND_ROOT_PATH= 1 << 28;
/**
* Package names are compressed.
* e.g. <code>o*.e*.search</code>
*/
public final static int P_COMPRESSED= 1 << 29;
/**
* Post qualify referenced package fragement roots. For example
* <code>jdt.jar - org.eclipse.jdt.ui</code> if the jar is referenced
* from another project.
*/
public final static int REFERENCED_ROOT_POST_QUALIFIED= 1 << 30;
/**
* Qualify all elements
*/
public final static int ALL_FULLY_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED;
/**
* Post qualify all elements
*/
public final static int ALL_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED;
/**
* Default options (M_PARAMETER_TYPES enabled)
*/
public final static int ALL_DEFAULT= M_PARAMETER_TYPES;
/**
* Default qualify options (All except Root and Package)
*/
public final static int DEFAULT_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED;
/**
* Default post qualify options (All except Root and Package)
*/
public final static int DEFAULT_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED;
public final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$
public final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$
public final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$
public final static String DEFAULT_PACKAGE= JavaUIMessages.getString("JavaElementLabels.default_package"); // "(default package)" //$NON-NLS-1$
/*
* Package name compression
*/
private static String fgPkgNamePattern= ""; //$NON-NLS-1$
private static String fgPkgNamePrefix;
private static String fgPkgNamePostfix;
private static int fgPkgNameChars;
private static int fgPkgNameLength= -1;
private JavaElementLabels() {
}
private static boolean getFlag(int flags, int flag) {
return (flags & flag) != 0;
}
public static String getTextLabel(Object obj, int flags) {
if (obj instanceof IJavaElement) {
return getElementLabel((IJavaElement) obj, flags);
} else if (obj instanceof IAdaptable) {
IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class);
if (wbadapter != null) {
return wbadapter.getLabel(obj);
}
}
return ""; //$NON-NLS-1$
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static String getElementLabel(IJavaElement element, int flags) {
StringBuffer buf= new StringBuffer(60);
getElementLabel(element, flags, buf);
return buf.toString();
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) {
int type= element.getElementType();
IPackageFragmentRoot root= null;
if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT)
root= JavaModelUtil.getPackageFragmentRoot(element);
if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) {
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
buf.append(CONCAT_STRING);
}
switch (type) {
case IJavaElement.METHOD:
getMethodLabel((IMethod) element, flags, buf);
break;
case IJavaElement.FIELD:
getFieldLabel((IField) element, flags, buf);
break;
case IJavaElement.INITIALIZER:
getInitializerLabel((IInitializer) element, flags, buf);
break;
case IJavaElement.TYPE:
getTypeLabel((IType) element, flags, buf);
break;
case IJavaElement.CLASS_FILE:
getClassFileLabel((IClassFile) element, flags, buf);
break;
case IJavaElement.COMPILATION_UNIT:
getCompilationUnitLabel((ICompilationUnit) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT:
getPackageFragmentLabel((IPackageFragment) element, flags, buf);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf);
break;
case IJavaElement.IMPORT_CONTAINER:
case IJavaElement.IMPORT_DECLARATION:
case IJavaElement.PACKAGE_DECLARATION:
getDeclararionLabel(element, flags, buf);
break;
case IJavaElement.JAVA_PROJECT:
case IJavaElement.JAVA_MODEL:
buf.append(element.getElementName());
break;
default:
buf.append(element.getElementName());
}
if (root != null && getFlag(flags, APPEND_ROOT_PATH)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a method to a StringBuffer. Considers the M_* flags.
*/
public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) {
try {
// return type
if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
buf.append(' ');
}
// qualification
if (getFlag(flags, M_FULLY_QUALIFIED)) {
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(method.getElementName());
// parameters
if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) {
buf.append('(');
String[] types= getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null;
String[] names= (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null;
int nParams= types != null ? types.length : names.length;
for (int i= 0; i < nParams; i++) {
if (i > 0) {
buf.append(COMMA_STRING); //$NON-NLS-1$
}
if (types != null) {
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
if (names != null) {
if (types != null) {
buf.append(' ');
}
buf.append(names[i]);
}
}
buf.append(')');
}
if (getFlag(flags, M_EXCEPTIONS) && method.exists()) {
String[] types= method.getExceptionTypes();
if (types.length > 0) {
buf.append(" throws "); //$NON-NLS-1$
for (int i= 0; i < types.length; i++) {
if (i > 0) {
buf.append(COMMA_STRING);
}
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
}
}
if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) {
buf.append(DECL_STRING);
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
}
// post qualification
if (getFlag(flags, M_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a field to a StringBuffer. Considers the F_* flags.
*/
public static void getFieldLabel(IField field, int flags, StringBuffer buf) {
try {
if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) {
buf.append(Signature.toString(field.getTypeSignature()));
buf.append(' ');
}
// qualification
if (getFlag(flags, F_FULLY_QUALIFIED)) {
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(field.getElementName());
if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) {
buf.append(DECL_STRING);
buf.append(Signature.toString(field.getTypeSignature()));
}
// post qualification
if (getFlag(flags, F_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // NotExistsException will not reach this point
}
}
/**
* Appends the label for a initializer to a StringBuffer. Considers the I_* flags.
*/
public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) {
// qualification
if (getFlag(flags, I_FULLY_QUALIFIED)) {
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$
// post qualification
if (getFlag(flags, I_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
}
}
/**
* Appends the label for a type to a StringBuffer. Considers the T_* flags.
*/
public static void getTypeLabel(IType type, int flags, StringBuffer buf) {
if (getFlag(flags, T_FULLY_QUALIFIED)) {
IPackageFragment pack= type.getPackageFragment();
if (!pack.isDefaultPackage()) {
getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf);
buf.append('.');
}
buf.append(JavaModelUtil.getTypeQualifiedName(type));
} else if (getFlag(flags, T_CONTAINER_QUALIFIED)) {
buf.append(JavaModelUtil.getTypeQualifiedName(type));
} else {
buf.append(type.getElementName());
}
// post qualification
if (getFlag(flags, T_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
IType declaringType= type.getDeclaringType();
if (declaringType != null) {
getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf);
} else {
getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf);
}
}
}
/**
* Appends the label for a declaration to a StringBuffer. Considers the D_* flags.
*/
public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) {
if (getFlag(flags, D_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
buf.append('/');
}
}
if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) {
buf.append(JavaUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$
} else {
buf.append(declaration.getElementName());
}
// post qualification
if (getFlag(flags, D_POST_QUALIFIED)) {
IJavaElement openable= (IJavaElement) declaration.getOpenable();
if (openable != null) {
buf.append(CONCAT_STRING);
buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED));
}
}
}
/**
* Appends the label for a class file to a StringBuffer. Considers the CF_* flags.
*/
public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) {
if (getFlag(flags, CF_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) classFile.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(classFile.getElementName());
if (getFlag(flags, CF_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf);
}
}
/**
* Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags.
*/
public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) {
if (getFlag(flags, CU_QUALIFIED)) {
IPackageFragment pack= (IPackageFragment) cu.getParent();
if (!pack.isDefaultPackage()) {
buf.append(pack.getElementName());
buf.append('.');
}
}
buf.append(cu.getElementName());
if (getFlag(flags, CU_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf);
}
}
/**
* Appends the label for a package fragment to a StringBuffer. Considers the P_* flags.
*/
public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) {
if (getFlag(flags, P_QUALIFIED)) {
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
buf.append('/');
}
refreshPackageNamePattern();
if (pack.isDefaultPackage()) {
buf.append(DEFAULT_PACKAGE);
} else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) {
String name= pack.getElementName();
int start= 0;
int dot= name.indexOf('.', start);
while (dot > 0) {
if (dot - start > fgPkgNameLength-1) {
buf.append(fgPkgNamePrefix);
if (fgPkgNameChars > 0)
buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
buf.append(fgPkgNamePostfix);
} else
buf.append(name.substring(start, dot + 1));
start= dot + 1;
dot= name.indexOf('.', start);
}
buf.append(name.substring(start));
} else {
buf.append(pack.getElementName());
}
if (getFlag(flags, P_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf);
}
}
/**
* Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags.
*/
public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
if (root.isArchive())
getArchiveLabel(root, flags, buf);
else
getFolderLabel(root, flags, buf);
}
private static void getArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
// Handle variables different
if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf))
return;
boolean external= root.isExternal();
if (external)
getExternalArchiveLabel(root, flags, buf);
else
getInternalArchiveLabel(root, flags, buf);
}
private static boolean getVariableLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
try {
IClasspathEntry rawEntry= root.getRawClasspathEntry();
if (rawEntry != null) {
if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
buf.append(rawEntry.getPath().makeRelative());
buf.append(CONCAT_STRING);
if (root.isExternal())
buf.append(root.getPath().toOSString());
else
buf.append(root.getPath().makeRelative().toString());
return true;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // problems with class path
}
return false;
}
private static void getExternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
IPath path= root.getPath();
if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) {
int segements= path.segmentCount();
if (segements > 0) {
buf.append(path.segment(segements - 1));
if (segements > 1 || path.getDevice() != null) {
buf.append(CONCAT_STRING);
buf.append(path.removeLastSegments(1).toOSString());
}
} else {
buf.append(path.toOSString());
}
} else {
buf.append(path.toOSString());
}
}
private static void getInternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
IResource resource= root.getResource();
boolean rootQualified= getFlag(flags, ROOT_QUALIFIED);
boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null;
if (rootQualified) {
buf.append(root.getPath().makeRelative().toString());
} else {
buf.append(root.getElementName());
if (referencedQualified) {
buf.append(CONCAT_STRING);
buf.append(resource.getParent().getFullPath().makeRelative().toString());
} else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getPath().makeRelative().toString());
}
}
}
private static void getFolderLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) {
IResource resource= root.getResource();
boolean rootQualified= getFlag(flags, ROOT_QUALIFIED);
boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null;
if (rootQualified) {
buf.append(root.getPath().makeRelative().toString());
} else {
if (resource != null)
buf.append(resource.getProjectRelativePath().toString());
else
buf.append(root.getElementName());
if (referencedQualified) {
buf.append(CONCAT_STRING);
buf.append(resource.getProject().getName());
} else if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getElementName());
}
}
}
private static void refreshPackageNamePattern() {
String pattern= getPkgNamePatternForPackagesView();
if (pattern.equals(fgPkgNamePattern))
return;
else if (pattern.equals("")) { //$NON-NLS-1$
fgPkgNamePattern= ""; //$NON-NLS-1$
fgPkgNameLength= -1;
return;
}
fgPkgNamePattern= pattern;
int i= 0;
fgPkgNameChars= 0;
fgPkgNamePrefix= ""; //$NON-NLS-1$
fgPkgNamePostfix= ""; //$NON-NLS-1$
while (i < pattern.length()) {
char ch= pattern.charAt(i);
if (Character.isDigit(ch)) {
fgPkgNameChars= ch-48;
if (i > 0)
fgPkgNamePrefix= pattern.substring(0, i);
if (i >= 0)
fgPkgNamePostfix= pattern.substring(i+1);
fgPkgNameLength= fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length();
return;
}
i++;
}
fgPkgNamePrefix= pattern;
fgPkgNameLength= pattern.length();
}
private static String getPkgNamePatternForPackagesView() {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES))
return ""; //$NON-NLS-1$
return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW);
}
}
|
40,787 |
Bug 40787 [plan item] Affordance for F2 opportunity in Java editor
|
There should be a small label explaining that F2 pins the hover.
|
resolved fixed
|
ca92e59
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-04T13:00:25Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/AbstractJavaEditorTextHover.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.hover;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.text.java.hover.IJavaEditorTextHover;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.text.JavaWordFinder;
/**
* Abstract class for providing hover information for Java elements.
*
* @since 2.1
*/
public abstract class AbstractJavaEditorTextHover implements IJavaEditorTextHover {
private IEditorPart fEditor;
/*
* @see IJavaEditorTextHover#setEditor(IEditorPart)
*/
public void setEditor(IEditorPart editor) {
fEditor= editor;
}
protected IEditorPart getEditor() {
return fEditor;
}
protected ICodeAssist getCodeAssist() {
if (fEditor != null) {
IEditorInput input= fEditor.getEditorInput();
if (input instanceof IClassFileEditorInput) {
IClassFileEditorInput cfeInput= (IClassFileEditorInput) input;
return cfeInput.getClassFile();
}
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(input);
}
return null;
}
/*
* @see ITextHover#getHoverRegion(ITextViewer, int)
*/
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
return JavaWordFinder.findWord(textViewer.getDocument(), offset);
}
/*
* @see ITextHover#getHoverInfo(ITextViewer, IRegion)
*/
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
ICodeAssist resolve= getCodeAssist();
if (resolve != null) {
try {
IJavaElement[] result= null;
synchronized (resolve) {
result= resolve.codeSelect(hoverRegion.getOffset(), hoverRegion.getLength());
}
if (result == null)
return null;
int nResults= result.length;
if (nResults == 0)
return null;
return getHoverInfo(result);
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
}
return null;
}
/**
* Provides hover information for the given Java elements.
*
* @return the hover information string
* @since 2.1
*/
protected String getHoverInfo(IJavaElement[] javaElements) {
return null;
}
}
|
40,787 |
Bug 40787 [plan item] Affordance for F2 opportunity in Java editor
|
There should be a small label explaining that F2 pins the hover.
|
resolved fixed
|
ca92e59
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-04T13:00:25Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/JavaSourceHover.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.hover;
import java.io.IOException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.ITextHoverExtension;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaModelException;
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.text.JavaCodeReader;
/**
* Provides source as hover info for Java elements.
*/
public class JavaSourceHover extends AbstractJavaEditorTextHover implements ITextHoverExtension, IInformationProviderExtension2 {
/*
* @see JavaElementHover
*/
protected String getHoverInfo(IJavaElement[] result) {
int nResults= result.length;
if (nResults > 1)
return null;
IJavaElement curr= result[0];
if (curr instanceof IMember && curr instanceof ISourceReference) {
try {
String source= ((ISourceReference) curr).getSource();
if (source == null)
return null;
source= removeLeadingComments(source);
String delim= null;
try {
delim= StubUtility.getLineDelimiterUsed(result[0]);
} catch (JavaModelException e) {
delim= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
}
String[] sourceLines= Strings.convertIntoLines(source);
String firstLine= sourceLines[0];
if (!Character.isWhitespace(firstLine.charAt(0)))
sourceLines[0]= ""; //$NON-NLS-1$
CodeFormatterUtil.removeIndentation(sourceLines);
if (!Character.isWhitespace(firstLine.charAt(0)))
sourceLines[0]= firstLine;
source= source= Strings.concatenate(sourceLines, delim);
return source;
} catch (JavaModelException ex) {
}
}
return null;
}
private String removeLeadingComments(String source) {
JavaCodeReader reader= new JavaCodeReader();
IDocument document= new Document(source);
int i;
try {
reader.configureForwardReader(document, 0, document.getLength(), true, false);
int c= reader.read();
while (c != -1 && (c == '\r' || c == '\n')) {
c= reader.read();
}
i= reader.getOffset();
reader.close();
} catch (IOException ex) {
i= 0;
} finally {
try {
if (reader != null)
reader.close();
} catch (IOException ex) {
JavaPlugin.log(ex);
}
}
if (i < 0)
return source;
return source.substring(i);
}
/*
* @see org.eclipse.jface.text.ITextHoverExtension#getInformationControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationControlCreator() {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
return new SourceViewerInformationControl(parent);
}
};
}
/*
* @see IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
int shellStyle= SWT.RESIZE;
int style= SWT.V_SCROLL | SWT.H_SCROLL;
return new SourceViewerInformationControl(parent, shellStyle, style);
}
};
}
}
|
40,787 |
Bug 40787 [plan item] Affordance for F2 opportunity in Java editor
|
There should be a small label explaining that F2 pins the hover.
|
resolved fixed
|
ca92e59
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-04T13:00:25Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/hover/SourceViewerInformationControl.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.hover;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlExtension;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer;
/**
* Source viewer based implementation of <code>IInformationControl</code>.
* Displays information in a source viewer.
*
* @since 3.0
*/
public class SourceViewerInformationControl implements IInformationControl, IInformationControlExtension {
/**
* Layout used to achive the "tool tip" look, i.e., flat with a thin boarder.
*/
private static class BorderFillLayout extends Layout {
/** The border widths. */
final int fBorderSize;
/**
* Creates a fill layout with a border.
*
* @param borderSize the size of the border
*/
public BorderFillLayout(int borderSize) {
if (borderSize < 0)
throw new IllegalArgumentException();
fBorderSize= borderSize;
}
/**
* Returns the border size.
*
* @return the border size
*/
public int getBorderSize() {
return fBorderSize;
}
/*
* @see org.eclipse.swt.widgets.Layout#computeSize(org.eclipse.swt.widgets.Composite, int, int, boolean)
*/
protected Point computeSize(Composite composite, int wHint, int hHint, boolean flushCache) {
Control[] children= composite.getChildren();
Point minSize= new Point(0, 0);
if (children != null) {
for (int i= 0; i < children.length; i++) {
Point size= children[i].computeSize(wHint, hHint, flushCache);
minSize.x= Math.max(minSize.x, size.x);
minSize.y= Math.max(minSize.y, size.y);
}
}
minSize.x += fBorderSize * 2 + RIGHT_MARGIN;
minSize.y += fBorderSize * 2;
return minSize;
}
/*
* @see org.eclipse.swt.widgets.Layout#layout(org.eclipse.swt.widgets.Composite, boolean)
*/
protected void layout(Composite composite, boolean flushCache) {
Control[] children= composite.getChildren();
Point minSize= new Point(composite.getClientArea().width, composite.getClientArea().height);
if (children != null) {
for (int i= 0; i < children.length; i++) {
Control child= children[i];
child.setSize(minSize.x - fBorderSize * 2, minSize.y - fBorderSize * 2);
child.setLocation(fBorderSize, fBorderSize);
}
}
}
}
/** Border thickness in pixels. */
private static final int BORDER= 1;
/** Right margin in pixels. */
private static final int RIGHT_MARGIN= 3;
/** The control's shell */
private Shell fShell;
/** The control's text widget */
private StyledText fText;
/** The control's source viewer */
private SourceViewer fViewer;
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed. The given
* styles are applied to the created styled text widget.
*
* @param parent the parent shell
* @param shellStyle the additional styles for the shell
* @param style the additional styles for the styled text widget
*/
public SourceViewerInformationControl(Shell parent, int shellStyle, int style) {
fShell= new Shell(parent, SWT.NO_FOCUS | SWT.ON_TOP | shellStyle);
fViewer= new JavaSourceViewer(fShell, null, null, false, style);
fViewer.configure(new JavaSourceViewerConfiguration(JavaPlugin.getDefault().getJavaTextTools(), null));
fViewer.setEditable(false);
fText= fViewer.getTextWidget();
fText.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND));
fText.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND));
Display display= fShell.getDisplay();
int border= ((shellStyle & SWT.NO_TRIM) == 0) ? 0 : BORDER;
fShell.setLayout(new BorderFillLayout(border));
fShell.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
fText.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.character == 0x1B) // ESC
fShell.dispose();
}
public void keyReleased(KeyEvent e) {}
});
}
/**
* Creates a default information control with the given shell as parent. The given
* information presenter is used to process the information to be displayed. The given
* styles are applied to the created styled text widget.
*
* @param parent the parent shell
* @param style the additional styles for the styled text widget
* @param presenter the presenter to be used
*/
public SourceViewerInformationControl(Shell parent,int style) {
this(parent, SWT.NO_TRIM, style);
}
/**
* Creates a default information control with the given shell as parent.
* No information presenter is used to process the information
* to be displayed. No additional styles are applied to the styled text widget.
*
* @param parent the parent shell
*/
public SourceViewerInformationControl(Shell parent) {
this(parent, SWT.NONE);
}
/*
* @see org.eclipse.jface.text.IInformationControlExtension2#setInput(java.lang.Object)
*/
public void setInput(Object input) {
if (input instanceof String)
setInformation((String)input);
else
setInformation(null);
}
/*
* @see IInformationControl#setInformation(String)
*/
public void setInformation(String content) {
if (content == null) {
fViewer.setInput(null);
return;
}
IDocument doc= new Document(content);
IDocumentPartitioner dp= JavaPlugin.getDefault().getJavaTextTools().createDocumentPartitioner();
if (dp != null) {
doc.setDocumentPartitioner(dp);
dp.connect(doc);
}
fViewer.setInput(doc);
}
/*
* @see IInformationControl#setVisible(boolean)
*/
public void setVisible(boolean visible) {
fShell.setVisible(visible);
}
/*
* @see IInformationControl#dispose()
*/
public void dispose() {
if (fShell != null) {
if (!fShell.isDisposed())
fShell.dispose();
fShell= null;
fText= null;
}
}
/*
* @see IInformationControl#setSize(int, int)
*/
public void setSize(int width, int height) {
fShell.setSize(width, height);
}
/*
* @see IInformationControl#setLocation(Point)
*/
public void setLocation(Point location) {
Rectangle trim= fShell.computeTrim(0, 0, 0, 0);
Point textLocation= fText.getLocation();
location.x += trim.x - textLocation.x;
location.y += trim.y - textLocation.y;
fShell.setLocation(location);
}
/*
* @see IInformationControl#setSizeConstraints(int, int)
*/
public void setSizeConstraints(int maxWidth, int maxHeight) {
}
/*
* @see IInformationControl#computeSizeHint()
*/
public Point computeSizeHint() {
return fShell.computeSize(SWT.DEFAULT, SWT.DEFAULT);
}
/*
* @see IInformationControl#addDisposeListener(DisposeListener)
*/
public void addDisposeListener(DisposeListener listener) {
fShell.addDisposeListener(listener);
}
/*
* @see IInformationControl#removeDisposeListener(DisposeListener)
*/
public void removeDisposeListener(DisposeListener listener) {
fShell.removeDisposeListener(listener);
}
/*
* @see IInformationControl#setForegroundColor(Color)
*/
public void setForegroundColor(Color foreground) {
fText.setForeground(foreground);
}
/*
* @see IInformationControl#setBackgroundColor(Color)
*/
public void setBackgroundColor(Color background) {
fText.setBackground(background);
}
/*
* @see IInformationControl#isFocusControl()
*/
public boolean isFocusControl() {
return fText.isFocusControl();
}
/*
* @see IInformationControl#setFocus()
*/
public void setFocus() {
fShell.forceFocus();
fText.setFocus();
}
/*
* @see IInformationControl#addFocusListener(FocusListener)
*/
public void addFocusListener(FocusListener listener) {
fText.addFocusListener(listener);
}
/*
* @see IInformationControl#removeFocusListener(FocusListener)
*/
public void removeFocusListener(FocusListener listener) {
fText.removeFocusListener(listener);
}
/*
* @see IInformationControlExtension#hasContents()
*/
public boolean hasContents() {
return fText.getCharCount() > 0;
}
protected ISourceViewer getViewer() {
return fViewer;
}
}
|
40,904 |
Bug 40904 NPE during Debug Session
|
NPE is thrown during debug session and stepping through the code. After the NPE occured, the callstack is updated during stepping, but the corresponding source file will not be opened by Eclipse anymore. I have to exit Eclipse to debug again. Attached is the part of the .log file with the Exception. !ENTRY org.eclipse.jface 4 2 Jul 29, 2003 18:35:02.427 !MESSAGE Problems occurred when invoking code from plug- in: "org.eclipse.jface". !STACK 0 java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.uninsta llSelectionListener(QuickAssistLightBulbUpdater.java:122) at org.eclipse.jdt.internal.ui.text.correction.QuickAssistLightBulbUpdater.uninsta ll(QuickAssistLightBulbUpdater.java:143) at org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant.uninstall (JavaCorrectionAssistant.java:124) at org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor$AdaptedSourceViewe r.handleDispose(CompilationUnitEditor.java:179) at org.eclipse.jface.text.TextViewer$1.widgetDisposed (TextViewer.java:1297) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:100) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:872) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:853) at org.eclipse.swt.widgets.Widget.releaseWidget(Widget.java:760) at org.eclipse.swt.widgets.Control.releaseWidget(Control.java:1421) at org.eclipse.swt.widgets.Scrollable.releaseWidget (Scrollable.java:188) at org.eclipse.swt.widgets.Composite.releaseWidget(Composite.java:369) at org.eclipse.swt.widgets.Canvas.releaseWidget(Canvas.java:118) at org.eclipse.swt.widgets.Widget.releaseResources(Widget.java:725) at org.eclipse.swt.widgets.Composite.releaseChildren (Composite.java:320) at org.eclipse.swt.widgets.Composite.releaseWidget(Composite.java:368) at org.eclipse.swt.widgets.Canvas.releaseWidget(Canvas.java:118) at org.eclipse.swt.widgets.Widget.releaseResources(Widget.java:725) at org.eclipse.swt.widgets.Composite.releaseChildren (Composite.java:320) at org.eclipse.swt.widgets.Composite.releaseWidget(Composite.java:368) at org.eclipse.swt.widgets.Widget.releaseResources(Widget.java:725) at org.eclipse.swt.widgets.Composite.releaseChildren (Composite.java:320) at org.eclipse.swt.widgets.Composite.releaseWidget(Composite.java:368) at org.eclipse.swt.widgets.Widget.releaseResources(Widget.java:725) at org.eclipse.swt.widgets.Composite.releaseChildren (Composite.java:320) at org.eclipse.swt.widgets.Composite.releaseWidget(Composite.java:368) at org.eclipse.swt.widgets.Widget.releaseResources(Widget.java:725) at org.eclipse.swt.widgets.Composite.releaseChildren (Composite.java:320) at org.eclipse.swt.widgets.Composite.releaseWidget(Composite.java:368) at org.eclipse.swt.widgets.Widget.dispose(Widget.java:376) at org.eclipse.ui.internal.PartPane.dispose(PartPane.java:205) at org.eclipse.ui.internal.EditorPresentation.closeEditor (EditorPresentation.java:82) at org.eclipse.ui.internal.EditorPresentation.closeEditor (EditorPresentation.java:70) at org.eclipse.ui.internal.EditorManager.closeEditor (EditorManager.java:127) at org.eclipse.ui.internal.WorkbenchPage.closeEditor (WorkbenchPage.java:846) at org.eclipse.debug.internal.ui.views.launch.LaunchView.openEditor (LaunchView.java:846) at org.eclipse.debug.internal.ui.views.launch.LaunchView.openEditorForStackFrame (LaunchView.java:655) at org.eclipse.debug.internal.ui.views.launch.LaunchView.showEditorForCurrentSelec tion(LaunchView.java:574) at org.eclipse.debug.internal.ui.views.launch.LaunchView.selectionChanged (LaunchView.java:450) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java:1015) at org.eclipse.core.runtime.Platform.run(Platform.java:420) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:1012) at org.eclipse.debug.internal.ui.views.launch.LaunchView.autoExpand (LaunchView.java:964) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler.doHandleSuspe ndThreadEvent(LaunchViewEventHandler.java:232) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler.doHandleSuspe ndEvent(LaunchViewEventHandler.java:182) at org.eclipse.debug.internal.ui.views.launch.LaunchViewEventHandler.doHandleDebug Events(LaunchViewEventHandler.java:103) at org.eclipse.debug.internal.ui.views.AbstractDebugEventHandler$1.run (AbstractDebugEventHandler.java:70) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:102) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:2165) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1882) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) 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:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
9b5dcff
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-06T10:43:48Z | 2003-07-29T17:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/QuickAssistLightBulbUpdater.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.Iterator;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.IPostSelectionProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.java.*;
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.javaeditor.IJavaAnnotation;
import org.eclipse.jdt.internal.ui.javaeditor.JavaAnnotationIterator;
/**
*
*/
public class QuickAssistLightBulbUpdater {
private static class AssistAnnotation extends Annotation {
private Image fImage;
public AssistAnnotation() {
setLayer(MarkerAnnotation.PROBLEM_LAYER + 1);
}
private Image getImage() {
if (fImage == null) {
fImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_QUICK_ASSIST);
}
return fImage;
}
/* (non-Javadoc)
* @see org.eclipse.jface.text.source.Annotation#paint(org.eclipse.swt.graphics.GC, org.eclipse.swt.widgets.Canvas, org.eclipse.swt.graphics.Rectangle)
*/
public void paint(GC gc, Canvas canvas, Rectangle r) {
drawImage(getImage(), gc, canvas, r, SWT.CENTER, SWT.TOP);
}
}
private Annotation fAnnotation;
private boolean fIsAnnotationShown;
private IEditorPart fEditor;
private ITextViewer fViewer;
private ISelectionChangedListener fListener;
private IPropertyChangeListener fPropertyChangeListener;
public QuickAssistLightBulbUpdater(IEditorPart part, ITextViewer viewer) {
fEditor= part;
fViewer= viewer;
fAnnotation= new AssistAnnotation();
fIsAnnotationShown= false;
fPropertyChangeListener= null;
}
public boolean isSetInPreferences() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB);
}
private void installSelectionListener() {
ISelectionProvider provider= fViewer.getSelectionProvider();
if (provider instanceof IPostSelectionProvider) {
fListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged();
}
};
((IPostSelectionProvider) provider).addPostSelectionChangedListener(fListener);
}
}
private void uninstallSelectionListener() {
if (fListener != null) {
IPostSelectionProvider provider= (IPostSelectionProvider) fViewer.getSelectionProvider();
provider.removePostSelectionChangedListener(fListener);
fListener= null;
if (fIsAnnotationShown) {
getAnnotationModel().removeAnnotation(fAnnotation);
fIsAnnotationShown= false;
}
}
}
public void install() {
if (isSetInPreferences()) {
installSelectionListener();
}
if (fPropertyChangeListener == null) {
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChanged(event.getProperty());
}
};
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
}
}
public void uninstall() {
uninstallSelectionListener();
if (fPropertyChangeListener != null) {
PreferenceConstants.getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
}
protected void doPropertyChanged(String property) {
if (property.equals(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB)) {
if (isSetInPreferences()) {
installSelectionListener();
doSelectionChanged();
} else {
uninstallSelectionListener();
}
}
}
private ICompilationUnit getCompilationUnit(IEditorInput input) {
if (input instanceof FileEditorInput) {
IFile file= ((FileEditorInput) input).getFile();
ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
if (cu != null) {
return JavaModelUtil.toWorkingCopy(cu);
}
}
return null;
}
private IAnnotationModel getAnnotationModel() {
return JavaUI.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput());
}
private IDocument getDocument() {
return JavaUI.getDocumentProvider().getDocument(fEditor.getEditorInput());
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
private void doSelectionChanged() {
Point point= fViewer.getSelectedRange();
int offset= point.x;
int length= point.y;
final IAnnotationModel model= getAnnotationModel();
boolean hasQuickFix= hasQuickFixLightBulb(model, offset);
ICompilationUnit cu= getCompilationUnit(fEditor.getEditorInput());
if (hasQuickFix || cu == null) {
if (fIsAnnotationShown) {
model.removeAnnotation(fAnnotation);
}
return;
}
final IInvocationContext context= new AssistContext(cu, offset, length);
calculateLightBulb(model, context);
//Runnable runnable= new Runnable() {
// public void run() {
// calculateLightBulb(model, context);
// }
//};
//runnable.run();
}
private void calculateLightBulb(IAnnotationModel model, IInvocationContext context) {
boolean needsAnnotation= JavaCorrectionProcessor.hasAssists(context);
if (fIsAnnotationShown) {
model.removeAnnotation(fAnnotation);
}
if (needsAnnotation) {
model.addAnnotation(fAnnotation, new Position(context.getSelectionOffset(), context.getSelectionLength()));
}
fIsAnnotationShown= needsAnnotation;
}
/*
* Tests if there is already a quick fix light bulb on the current line
*/
private boolean hasQuickFixLightBulb(IAnnotationModel model, int offset) {
try {
IDocument document= getDocument();
int currLine= document.getLineOfOffset(offset);
Iterator iter= new JavaAnnotationIterator(model, true);
while (iter.hasNext()) {
IJavaAnnotation annot= (IJavaAnnotation) iter.next();
Position pos= model.getPosition((Annotation) annot);
int startLine= document.getLineOfOffset(pos.getOffset());
if (startLine == currLine && JavaCorrectionProcessor.hasCorrections(annot)) {
return true;
}
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return false;
}
}
|
40,880 |
Bug 40880 Wrong error range for 'indirect static access'
| null |
verified fixed
|
45de7cd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-06T12:30:17Z | 2003-07-29T06:26:40Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
public class LocalCorrectionsQuickFixTest extends QuickFixTest {
private static final Class THIS= LocalCorrectionsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public LocalCorrectionsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new LocalCorrectionsQuickFixTest("testIndirectStaticAccess2"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fJProject1= ProjectTestSetup.getProject();
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testFieldAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return (new File(\"x.txt\")).separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.File;\n");
buf.append("public class E {\n");
buf.append(" public char foo() {\n");
buf.append(" return File.separatorChar;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testInheritedAccessOnStatic() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public static void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" b.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public void foo(B b) {\n");
buf.append(" A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class A {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testQualifiedAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" t.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Thread t) {\n");
buf.append(" Thread.sleep(10);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testThisAccessToStatic() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" E.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testThisAccessToStaticField() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public static int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" E.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("\n");
buf.append(" public void foo() {\n");
buf.append(" this.fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= o;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Thread th= (Thread) o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o) {\n");
buf.append(" Object th= o;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class Container {\n");
buf.append(" public List[] getLists() {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("Container.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Container c) {\n");
buf.append(" List[] lists= c.getLists();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInVarDecl3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" Thread th= foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 0);
}
public void testCastMissingInFieldDecl() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= System.currentTimeMillis();\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" int time= (int) System.currentTimeMillis();\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" long time= System.currentTimeMillis();\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastMissingInAssignment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Iterator;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Iterator iter) {\n");
buf.append(" String str;\n");
buf.append(" str= (String) iter.next();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testCastMissingInExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public String[] foo(List list) {\n");
buf.append(" return (String[]) list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public Object[] foo(List list) {\n");
buf.append(" return list.toArray(new List[list.size()]);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testCastOnCastExpression() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" ArrayList a= (ArrayList) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.ArrayList;\n");
buf.append("import java.util.List;\n");
buf.append("public class E {\n");
buf.append(" public void foo(List list) {\n");
buf.append(" Cloneable a= (Cloneable) list;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtException2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" goo().substring(2);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public String goo() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo().substring(2);\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionRemoveMoreSpecific() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException {\n");
buf.append(" this.goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.net.SocketException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws SocketException {\n");
buf.append(" try {\n");
buf.append(" this.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUncaughtExceptionToSurroundingTry() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() throws ParseException {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (ParseException e1) {\n");
buf.append(" }\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public static void goo() throws IOException, ParseException {\n");
buf.append(" return;\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" E.goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testUncaughtExceptionOnSuper1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.FileInputStream;\n");
buf.append("import java.io.FileNotFoundException;\n");
buf.append("public class E extends FileInputStream {\n");
buf.append(" public E() throws FileNotFoundException {\n");
buf.append(" super(\"x\");\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnSuper2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A() throws Exception {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E() throws Exception {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUncaughtExceptionOnThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public E() throws IOException {\n");
buf.append(" this(null);\n");
buf.append(" }\n");
buf.append(" public E(Object x) throws IOException {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
boolean BUG_25417= true;
public void testUncaughtExceptionDuplicate() throws Exception {
if (BUG_25417) {
return;
}
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class MyException extends Exception {\n");
buf.append("}\n");
pack1.createCompilationUnit("MyException.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException, ParseException, MyException {\n");
buf.append(" m2();\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void m1() throws IOException {\n");
buf.append(" try {\n");
buf.append(" m2();\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" } catch (MyException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append(" public void m2() throws IOException, ParseException, MyException {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testMultipleUncaughtExceptions() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() throws IOException, ParseException {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException, ParseException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnneededCatchBlock() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } catch (ParseException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("import java.text.ParseException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() throws IOException {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockSingle() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" goo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnneededCatchBlockWithFinally() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } catch (IOException e) {\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class E {\n");
buf.append(" public void goo() {\n");
buf.append(" }\n");
buf.append(" public void foo() {\n");
buf.append(" try {\n");
buf.append(" goo();\n");
buf.append(" } finally {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnimplementedMethods() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.Inter;\n");
buf.append("public abstract class E implements Inter{\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.Inter;\n");
buf.append("public class E implements Inter{\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnimplementedMethods2() throws Exception {
IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public interface Inter {\n");
buf.append(" int getCount(Object[] o) throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("Inter.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test2;\n");
buf.append("import java.io.IOException;\n");
buf.append("public abstract class InterImpl implements Inter {\n");
buf.append(" protected abstract int[] getMusic() throws IOException;\n");
buf.append("}\n");
pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import test2.InterImpl;\n");
buf.append("public abstract class E extends InterImpl {\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("import test2.InterImpl;\n");
buf.append("public class E extends InterImpl {\n");
buf.append("\n");
buf.append(" protected int[] getMusic() throws IOException {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public int getCount(Object[] o) throws IOException {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testUnitializedVariable() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" int s = 0;\n");
buf.append(" try {\n");
buf.append(" s= 1;\n");
buf.append(" } catch (Exception e) {\n");
buf.append(" System.out.println(s);\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUndefinedConstructorInDefaultConstructor2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F(Runnable runnable) throws IOException {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public F(int i, Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(int i, Runnable runnable) {\n");
buf.append(" super(i, runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) throws IOException {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testNotVisibleConstructorInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F {\n");
buf.append(" private F() {\n");
buf.append(" }\n");
buf.append(" public F(Runnable runnable) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E(Runnable runnable) {\n");
buf.append(" super(runnable);\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnhandledExceptionInDefaultConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.io.IOException;\n");
buf.append("public class F {\n");
buf.append(" public F() throws IOException{\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("F.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends F {\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.io.IOException;\n");
buf.append("\n");
buf.append("public class E extends F {\n");
buf.append("\n");
buf.append(" public E() throws IOException {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount, fColor= fCount;\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateField2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private int fCount= 0;\n");
buf.append(" public void foo() {\n");
buf.append(" fCount= 1 + 2;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" boolean res= process();\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" res= (super.hashCode() == 1);\n");
buf.append(" }\n");
buf.append(" public boolean process() {\n");
buf.append(" return true;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] i, j= new Object[0];\n");
buf.append(" i= j = null;\n");
buf.append(" i= (new Object[] { null, null });\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private Object[] foo() {\n");
buf.append(" Object[] j= new Object[0];\n");
buf.append(" j = null;\n");
buf.append(" return j;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedVariable2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int j= 0, i= 0; i < 3; i++) {\n");
buf.append(" j= i;\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" for (int i= 0; i < 3; i++) {\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedParam() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR);
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo(Object str) {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private void foo() {\n");
buf.append(" {\n");
buf.append(" str= toString();\n");
buf.append(" str= new String[] { toString(), toString() };\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateMethod() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append(" \n");
buf.append(" private void foo() {\n");
buf.append(" fCount= 1;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int fCount;\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateConstructor() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" private E(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnusedPrivateType() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private class F {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = (int) i;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = i;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" String r = ((String) s);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" String r = s;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testUnnecessaryCast3() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = ((int) 1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s = (1 + 2) * 3;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testSuperfluousSemicolon() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s= 1;;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int s= 1;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess1() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append(" public static final int CONST=1;\n");
buf.append("}\n");
other.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends other.A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public int foo(B b) {\n");
buf.append(" return B.CONST;\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import other.A;\n");
buf.append("import pack.B;\n");
buf.append("public class E {\n");
buf.append(" public int foo(B b) {\n");
buf.append(" return A.CONST;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testIndirectStaticAccess2() throws Exception {
Hashtable hashtable= JavaCore.getOptions();
hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR);
JavaCore.setOptions(hashtable);
IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append(" public static int foo() {\n");
buf.append(" return 1;\n");
buf.append(" }\n");
buf.append("}\n");
other.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null);
buf= new StringBuffer();
buf.append("package pack;\n");
buf.append("public class B extends other.A {\n");
buf.append("}\n");
pack0.createCompilationUnit("B.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public int foo() {\n");
buf.append(" return pack.B.foo();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import other.A;\n");
buf.append("\n");
buf.append("public class E {\n");
buf.append(" public int foo() {\n");
buf.append(" return A.foo();\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
}
|
40,830 |
Bug 40830 hierarchy view not up to date after rename [type hierarchy]
|
If you use the standard java perspective layout and have the following file --------------------------------A.java------------------------ public class A { } class B extends A { } -------------------------------------------------------------- double click on the first 'A' and press F4 (hierarchy view) then click on the package explorer (so as to hide the hierarchy view). then rename the class A to class C (using refactoring) double click on the new class name and click F4 the hierarchy still displays with 'A' at the root and not the new name ('C')
|
resolved fixed
|
e259d96
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-06T15:38:02Z | 2003-07-28T11:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.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.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartListener2;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.PageBook;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.ITypeHierarchyViewPart;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectAllAction;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener;
import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* view showing the supertypes/subtypes of its input.
*/
public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider {
public static final int VIEW_ID_TYPE= 2;
public static final int VIEW_ID_SUPER= 0;
public static final int VIEW_ID_SUB= 1;
public static final int VIEW_ORIENTATION_VERTICAL= 0;
public static final int VIEW_ORIENTATION_HORIZONTAL= 1;
public static final int VIEW_ORIENTATION_SINGLE= 2;
private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$
private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$
private static final String TAG_INPUT= "input"; //$NON-NLS-1$
private static final String TAG_VIEW= "view"; //$NON-NLS-1$
private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$
private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$
private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$
private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$
// the selected type in the hierarchy view
private IType fSelectedType;
// input element or null
private IJavaElement fInputElement;
// history of input elements. No duplicates
private ArrayList fInputHistory;
private IMemento fMemento;
private IDialogSettings fDialogSettings;
private TypeHierarchyLifeCycle fHierarchyLifeCycle;
private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener;
private IPropertyChangeListener fPropertyChangeListener;
private SelectionProviderMediator fSelectionProviderMediator;
private ISelectionChangedListener fSelectionChangedListener;
private IPartListener2 fPartListener;
private int fCurrentOrientation;
private boolean fLinkingEnabled;
private boolean fIsVisible;
private boolean fNeedRefresh;
private boolean fIsEnableMemberFilter;
private boolean fIsRefreshRunnablePosted;
private int fCurrentViewerIndex;
private TypeHierarchyViewer[] fAllViewers;
private MethodsViewer fMethodsViewer;
private SashForm fTypeMethodsSplitter;
private PageBook fViewerbook;
private PageBook fPagebook;
private Label fNoHierarchyShownLabel;
private Label fEmptyTypesViewer;
private ViewForm fTypeViewerViewForm;
private ViewForm fMethodViewerViewForm;
private CLabel fMethodViewerPaneLabel;
private JavaUILabelProvider fPaneLabelProvider;
private ToggleViewAction[] fViewActions;
private ToggleLinkingAction fToggleLinkingAction;
private HistoryDropDownAction fHistoryDropDownAction;
private ToggleOrientationAction[] fToggleOrientationActions;
private EnableMemberFilterAction fEnableMemberFilterAction;
private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction;
private AddMethodStubAction fAddStubAction;
private FocusOnTypeAction fFocusOnTypeAction;
private FocusOnSelectionAction fFocusOnSelectionAction;
private CompositeActionGroup fActionGroups;
private CCPActionGroup fCCPActionGroup;
private SelectAllAction fSelectAllAction;
public TypeHierarchyViewPart() {
fSelectedType= null;
fInputElement= null;
fIsVisible= false;
fIsRefreshRunnablePosted= false;
boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS));
fHierarchyLifeCycle= new TypeHierarchyLifeCycle();
fHierarchyLifeCycle.setReconciled(isReconciled);
fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() {
public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) {
doTypeHierarchyChanged(typeHierarchy, changedTypes);
}
};
fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener);
fPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
doPropertyChange(event);
}
};
PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener);
fIsEnableMemberFilter= false;
fInputHistory= new ArrayList();
fAllViewers= null;
fViewActions= new ToggleViewAction[] {
new ToggleViewAction(this, VIEW_ID_TYPE),
new ToggleViewAction(this, VIEW_ID_SUPER),
new ToggleViewAction(this, VIEW_ID_SUB)
};
fDialogSettings= JavaPlugin.getDefault().getDialogSettings();
fHistoryDropDownAction= new HistoryDropDownAction(this);
fHistoryDropDownAction.setEnabled(false);
fToggleOrientationActions= new ToggleOrientationAction[] {
new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL),
new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE)
};
fEnableMemberFilterAction= new EnableMemberFilterAction(this, false);
fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false);
fFocusOnTypeAction= new FocusOnTypeAction(this);
fPaneLabelProvider= new JavaUILabelProvider();
fAddStubAction= new AddMethodStubAction();
fFocusOnSelectionAction= new FocusOnSelectionAction(this);
fPartListener= new IPartListener2() {
public void partVisible(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(true);
}
}
public void partHidden(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part == TypeHierarchyViewPart.this) {
visibilityChanged(false);
}
}
public void partActivated(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partInputChanged(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPartReference ref) {}
public void partClosed(IWorkbenchPartReference ref) {}
public void partDeactivated(IWorkbenchPartReference ref) {}
public void partOpened(IWorkbenchPartReference ref) {}
};
fSelectionChangedListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
}
/**
* Method doPropertyChange.
* @param event
*/
protected void doPropertyChange(PropertyChangeEvent event) {
if (fMethodsViewer != null) {
if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(event.getProperty())) {
fMethodsViewer.refresh();
}
}
}
/**
* Adds the entry if new. Inserted at the beginning of the history entries list.
*/
private void addHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
fInputHistory.remove(entry);
}
fInputHistory.add(0, entry);
fHistoryDropDownAction.setEnabled(true);
}
private void updateHistoryEntries() {
for (int i= fInputHistory.size() - 1; i >= 0; i--) {
IJavaElement type= (IJavaElement) fInputHistory.get(i);
if (!type.exists()) {
fInputHistory.remove(i);
}
}
fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty());
}
/**
* Goes to the selected entry, without updating the order of history entries.
*/
public void gotoHistoryEntry(IJavaElement entry) {
if (fInputHistory.contains(entry)) {
updateInput(entry);
}
}
/**
* Gets all history entries.
*/
public IJavaElement[] getHistoryEntries() {
if (fInputHistory.size() > 0) {
updateHistoryEntries();
}
return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]);
}
/**
* Sets the history entries
*/
public void setHistoryEntries(IJavaElement[] elems) {
fInputHistory.clear();
for (int i= 0; i < elems.length; i++) {
fInputHistory.add(elems[i]);
}
updateHistoryEntries();
}
/**
* Selects an member in the methods list or in the current hierarchy.
*/
public void selectMember(IMember member) {
if (member.getElementType() != IJavaElement.TYPE) {
// methods are working copies
if (fHierarchyLifeCycle.isReconciled()) {
member= JavaModelUtil.toWorkingCopy(member);
}
Control methodControl= fMethodsViewer.getControl();
if (methodControl != null && !methodControl.isDisposed()) {
methodControl.setFocus();
}
fMethodsViewer.setSelection(new StructuredSelection(member), true);
} else {
Control viewerControl= getCurrentViewer().getControl();
if (viewerControl != null && !viewerControl.isDisposed()) {
viewerControl.setFocus();
}
// types are originals
member= JavaModelUtil.toOriginal(member);
if (!member.equals(fSelectedType)) {
getCurrentViewer().setSelection(new StructuredSelection(member), true);
}
}
}
/**
* @deprecated
*/
public IType getInput() {
if (fInputElement instanceof IType) {
return (IType) fInputElement;
}
return null;
}
/**
* Sets the input to a new type
* @deprecated
*/
public void setInput(IType type) {
setInputElement(type);
}
/**
* Returns the input element of the type hierarchy.
* Can be of type <code>IType</code> or <code>IPackageFragment</code>
*/
public IJavaElement getInputElement() {
return fInputElement;
}
/**
* Sets the input to a new element.
*/
public void setInputElement(IJavaElement element) {
if (element != null) {
if (element instanceof IMember) {
if (element.getElementType() != IJavaElement.TYPE) {
element= ((IMember) element).getDeclaringType();
}
element= JavaModelUtil.toOriginal((IMember) element);
if (!element.exists()) {
MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
} else {
int kind= element.getElementType();
if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) {
element= null;
JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$
}
}
}
if (element != null && !element.equals(fInputElement)) {
addHistoryEntry(element);
}
updateInput(element);
}
/**
* Changes the input to a new type
*/
private void updateInput(IJavaElement inputElement) {
IJavaElement prevInput= fInputElement;
// Make sure the UI got repainted before we execute a long running
// operation. This can be removed if we refresh the hierarchy in a
// separate thread.
// Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881
processOutstandingEvents();
if (inputElement == null) {
clearInput();
} else {
fInputElement= inputElement;
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, JavaPlugin.getActiveWorkbenchWindow());
// fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
if (inputElement.getElementType() != IJavaElement.TYPE) {
setView(VIEW_ID_TYPE);
}
// turn off member filtering
setMemberFilter(null);
fIsEnableMemberFilter= false;
if (!inputElement.equals(prevInput)) {
updateHierarchyViewer(true);
}
IType root= getSelectableType(inputElement);
internalSelectType(root, true);
updateMethodViewer(root);
updateToolbarButtons();
updateTitle();
enableMemberFilter(false);
fPagebook.showPage(fTypeMethodsSplitter);
}
}
private void processOutstandingEvents() {
Display display= getDisplay();
if (display != null && !display.isDisposed())
display.update();
}
private void clearInput() {
fInputElement= null;
fHierarchyLifeCycle.freeHierarchy();
updateHierarchyViewer(false);
updateToolbarButtons();
}
/*
* @see IWorbenchPart#setFocus
*/
public void setFocus() {
fPagebook.setFocus();
}
/*
* @see IWorkbenchPart#dispose
*/
public void dispose() {
fHierarchyLifeCycle.freeHierarchy();
fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener);
fPaneLabelProvider.dispose();
if (fMethodsViewer != null) {
fMethodsViewer.dispose();
}
if (fPropertyChangeListener != null) {
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
getSite().getPage().removePartListener(fPartListener);
if (fActionGroups != null)
fActionGroups.dispose();
super.dispose();
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key == IShowInSource.class) {
return getShowInSource();
}
if (key == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(key);
}
private Control createTypeViewerControl(Composite parent) {
fViewerbook= new PageBook(parent, SWT.NULL);
KeyListener keyListener= createKeyListener();
// Create the viewers
TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW);
TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW);
TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this);
initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW);
fAllViewers= new TypeHierarchyViewer[3];
fAllViewers[VIEW_ID_SUPER]= superTypesViewer;
fAllViewers[VIEW_ID_SUB]= subTypesViewer;
fAllViewers[VIEW_ID_TYPE]= vajViewer;
int currViewerIndex;
try {
currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW);
if (currViewerIndex < 0 || currViewerIndex > 2) {
currViewerIndex= VIEW_ID_TYPE;
}
} catch (NumberFormatException e) {
currViewerIndex= VIEW_ID_TYPE;
}
fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setInput(fAllViewers[i]);
}
// force the update
fCurrentViewerIndex= -1;
setView(currViewerIndex);
return fViewerbook;
}
private KeyListener createKeyListener() {
return new KeyAdapter() {
public void keyReleased(KeyEvent event) {
if (event.stateMask == 0) {
if (event.keyCode == SWT.F5) {
updateHierarchyViewer(false);
return;
} else if (event.character == SWT.DEL){
if (fCCPActionGroup.getDeleteAction().isEnabled())
fCCPActionGroup.getDeleteAction().run();
return;
}
}
}
};
}
private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) {
typesViewer.getControl().setVisible(false);
typesViewer.getControl().addKeyListener(keyListener);
typesViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillTypesViewerContextMenu(typesViewer, menu);
}
}, cotextHelpId, getSite());
typesViewer.addPostSelectionChangedListener(fSelectionChangedListener);
typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames());
}
private Control createMethodViewerControl(Composite parent) {
fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this);
fMethodsViewer.initContextMenu(new IMenuListener() {
public void menuAboutToShow(IMenuManager menu) {
fillMethodsViewerContextMenu(menu);
}
}, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite());
fMethodsViewer.addPostSelectionChangedListener(fSelectionChangedListener);
Control control= fMethodsViewer.getTable();
control.addKeyListener(createKeyListener());
return control;
}
private void initDragAndDrop() {
Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() };
int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK;
for (int i= 0; i < fAllViewers.length; i++) {
addDragAdapters(fAllViewers[i], ops, transfers);
addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers);
}
addDragAdapters(fMethodsViewer, ops, transfers);
//dnd on empty hierarchy
DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT);
dropTarget.setTransfer(transfers);
dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0]));
}
private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new TypeHierarchyTransferDropAdapter(this, viewer)
};
viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
}
private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) {
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(viewer)
};
viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners));
}
/**
* Returns the inner component in a workbench part.
* @see IWorkbenchPart#createPartControl
*/
public void createPartControl(Composite container) {
fPagebook= new PageBook(container, SWT.NONE);
// page 1 of pagebook (viewers)
fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL);
fTypeMethodsSplitter.setVisible(false);
fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm);
fTypeViewerViewForm.setContent(typeViewerControl);
fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE);
fTypeMethodsSplitter.setWeights(new int[] {35, 65});
Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm);
fMethodViewerViewForm.setContent(methodViewerPart);
fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE);
fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel);
ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP);
fMethodViewerViewForm.setTopCenter(methodViewerToolBar);
// page 2 of pagebook (no hierarchy label)
fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP);
fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$
initDragAndDrop();
MenuManager menu= new MenuManager();
menu.add(fFocusOnTypeAction);
fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel));
fPagebook.showPage(fNoHierarchyShownLabel);
int orientation;
try {
orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION);
if (orientation < 0 || orientation > 2) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
} catch (NumberFormatException e) {
orientation= VIEW_ORIENTATION_VERTICAL;
}
// force the update
fCurrentOrientation= -1;
// will fill the main tool bar
setOrientation(orientation);
if (fMemento != null) { // restore state before creating action
restoreLinkingEnabled(fMemento);
}
fToggleLinkingAction= new ToggleLinkingAction(this);
// set the filter menu items
IActionBars actionBars= getViewSite().getActionBars();
IMenuManager viewMenu= actionBars.getMenuManager();
for (int i= 0; i < fViewActions.length; i++) {
viewMenu.add(fViewActions[i]);
}
viewMenu.add(new Separator());
for (int i= 0; i < fToggleOrientationActions.length; i++) {
viewMenu.add(fToggleOrientationActions[i]);
}
viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
viewMenu.add(fShowQualifiedTypeNamesAction);
viewMenu.add(fToggleLinkingAction);
// fill the method viewer toolbar
ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar);
lowertbmanager.add(fEnableMemberFilterAction);
lowertbmanager.add(new Separator());
fMethodsViewer.contributeToToolBar(lowertbmanager);
lowertbmanager.update(true);
// selection provider
int nHierarchyViewers= fAllViewers.length;
Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1];
for (int i= 0; i < nHierarchyViewers; i++) {
trackedViewers[i]= fAllViewers[i];
}
trackedViewers[nHierarchyViewers]= fMethodsViewer;
fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager));
getSite().setSelectionProvider(fSelectionProviderMediator);
getSite().getPage().addPartListener(fPartListener);
// see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657
IJavaElement input= null; //determineInputElement();
if (fMemento != null) {
restoreState(fMemento, input);
} else if (input != null) {
setInputElement(input);
} else {
setViewerVisibility(false);
}
WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new GenerateActionGroup(this),
new RefactorActionGroup(this),
new JavaSearchActionGroup(this)});
fActionGroups.fillActionBars(actionBars);
fSelectAllAction= new SelectAllAction(fMethodsViewer);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.SELECT_ALL, fSelectAllAction);
}
/**
* called from ToggleOrientationAction.
* @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL
*/
public void setOrientation(int orientation) {
if (fCurrentOrientation != orientation) {
boolean methodViewerNeedsUpdate= false;
if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed()
&& fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) {
if (orientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(false);
enableMemberFilter(false);
updateMethodViewer(null);
} else {
if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) {
fMethodViewerViewForm.setVisible(true);
methodViewerNeedsUpdate= true;
}
boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL;
fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL);
}
updateMainToolbar(orientation);
fTypeMethodsSplitter.layout();
}
for (int i= 0; i < fToggleOrientationActions.length; i++) {
fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation());
}
fCurrentOrientation= orientation;
if (methodViewerNeedsUpdate) {
updateMethodViewer(fSelectedType);
}
fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation);
}
}
private void updateMainToolbar(int orientation) {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager tbmanager= actionBars.getToolBarManager();
if (orientation == VIEW_ORIENTATION_HORIZONTAL) {
clearMainToolBar(tbmanager);
ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP);
fillMainToolBar(new ToolBarManager(typeViewerToolBar));
fTypeViewerViewForm.setTopLeft(typeViewerToolBar);
} else {
fTypeViewerViewForm.setTopLeft(null);
fillMainToolBar(tbmanager);
}
}
private void fillMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.add(fHistoryDropDownAction);
for (int i= 0; i < fViewActions.length; i++) {
tbmanager.add(fViewActions[i]);
}
tbmanager.update(false);
}
private void clearMainToolBar(IToolBarManager tbmanager) {
tbmanager.removeAll();
tbmanager.update(false);
}
/**
* Creates the context menu for the hierarchy viewers
*/
private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS));
// viewer entries
viewer.contributeToContextMenu(menu);
if (fFocusOnSelectionAction.canActionBeAdded())
menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction);
menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction);
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Creates the context menu for the method viewer
*/
private void fillMethodsViewerContextMenu(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
// viewer entries
fMethodsViewer.contributeToContextMenu(menu);
if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction);
}
fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection()));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
/**
* Toggles between the empty viewer page and the hierarchy
*/
private void setViewerVisibility(boolean showHierarchy) {
if (showHierarchy) {
fViewerbook.showPage(getCurrentViewer().getControl());
} else {
fViewerbook.showPage(fEmptyTypesViewer);
}
}
/**
* Sets the member filter. <code>null</code> disables member filtering.
*/
private void setMemberFilter(IMember[] memberFilter) {
Assert.isNotNull(fAllViewers);
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setMemberFilter(memberFilter);
}
}
private IType getSelectableType(IJavaElement elem) {
if (elem.getElementType() != IJavaElement.TYPE) {
return null; //(IType) getCurrentViewer().getTreeRootType();
} else {
return (IType) elem;
}
}
private void internalSelectType(IMember elem, boolean reveal) {
TypeHierarchyViewer viewer= getCurrentViewer();
viewer.removePostSelectionChangedListener(fSelectionChangedListener);
viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal);
viewer.addPostSelectionChangedListener(fSelectionChangedListener);
}
/**
* When the input changed or the hierarchy pane becomes visible,
* <code>updateHierarchyViewer<code> brings up the correct view and refreshes
* the current tree
*/
private void updateHierarchyViewer(final boolean doExpand) {
if (fInputElement == null) {
fPagebook.showPage(fNoHierarchyShownLabel);
} else {
if (getCurrentViewer().containsElements() != null) {
Runnable runnable= new Runnable() {
public void run() {
getCurrentViewer().updateContent(doExpand); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) {
setViewerVisibility(true);
}
} else {
fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$
setViewerVisibility(false);
}
}
}
private void updateMethodViewer(final IType input) {
if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) {
if (input == fMethodsViewer.getInput()) {
if (input != null) {
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.refresh(); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
} else {
if (input != null) {
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input));
} else {
fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$
fMethodViewerPaneLabel.setImage(null);
}
Runnable runnable= new Runnable() {
public void run() {
fMethodsViewer.setInput(input); // refresh
}
};
BusyIndicator.showWhile(getDisplay(), runnable);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent e) {
if (e.getSelectionProvider() == fMethodsViewer) {
methodSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(true);
} else {
typeSelectionChanged(e.getSelection());
fSelectAllAction.setEnabled(false);
}
}
private void methodSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (fIsEnableMemberFilter) {
IMember[] memberFilter= null;
if (nSelected > 0) {
memberFilter= new IMember[nSelected];
selected.toArray(memberFilter);
}
setMemberFilter(memberFilter);
updateHierarchyViewer(true);
updateTitle();
internalSelectType(fSelectedType, true);
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), fMethodsViewer);
}
}
}
private void typeSelectionChanged(ISelection sel) {
if (sel instanceof IStructuredSelection) {
List selected= ((IStructuredSelection)sel).toList();
int nSelected= selected.size();
if (nSelected != 0) {
List types= new ArrayList(nSelected);
for (int i= nSelected-1; i >= 0; i--) {
Object elem= selected.get(i);
if (elem instanceof IType && !types.contains(elem)) {
types.add(elem);
}
}
if (types.size() == 1) {
fSelectedType= (IType) types.get(0);
updateMethodViewer(fSelectedType);
} else if (types.size() == 0) {
// method selected, no change
}
if (nSelected == 1) {
revealElementInEditor(selected.get(0), getCurrentViewer());
}
} else {
fSelectedType= null;
updateMethodViewer(null);
}
}
}
private void revealElementInEditor(Object elem, Viewer originViewer) {
// only allow revealing when the type hierarchy is the active pagae
// no revealing after selection events due to model changes
if (getSite().getPage().getActivePart() != this) {
return;
}
if (fSelectionProviderMediator.getViewerInFocus() != originViewer) {
return;
}
IEditorPart editorPart= EditorUtility.isOpenInEditor(elem);
if (editorPart != null && (elem instanceof IJavaElement)) {
getSite().getPage().removePartListener(fPartListener);
getSite().getPage().bringToTop(editorPart);
EditorUtility.revealInEditor(editorPart, (IJavaElement) elem);
getSite().getPage().addPartListener(fPartListener);
}
}
private Display getDisplay() {
if (fPagebook != null && !fPagebook.isDisposed()) {
return fPagebook.getDisplay();
}
return null;
}
private boolean isChildVisible(Composite pb, Control child) {
Control[] children= pb.getChildren();
for (int i= 0; i < children.length; i++) {
if (children[i] == child && children[i].isVisible())
return true;
}
return false;
}
private void updateTitle() {
String viewerTitle= getCurrentViewer().getTitle();
String tooltip;
String title;
if (fInputElement != null) {
String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) };
title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$
tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$
} else {
title= viewerTitle;
tooltip= viewerTitle;
}
setTitle(title);
setTitleToolTip(tooltip);
}
private void updateToolbarButtons() {
boolean isType= fInputElement instanceof IType;
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
if (action.getViewerIndex() == VIEW_ID_TYPE) {
action.setEnabled(fInputElement != null);
} else {
action.setEnabled(isType);
}
}
}
/**
* Sets the current view (see view id)
* called from ToggleViewAction. Must be called after creation of the viewpart.
*/
public void setView(int viewerIndex) {
Assert.isNotNull(fAllViewers);
if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) {
fCurrentViewerIndex= viewerIndex;
updateHierarchyViewer(true);
if (fInputElement != null) {
ISelection currSelection= getCurrentViewer().getSelection();
if (currSelection == null || currSelection.isEmpty()) {
internalSelectType(getSelectableType(fInputElement), false);
currSelection= getCurrentViewer().getSelection();
}
if (!fIsEnableMemberFilter) {
typeSelectionChanged(currSelection);
}
}
updateTitle();
fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex);
getCurrentViewer().getTree().setFocus();
}
for (int i= 0; i < fViewActions.length; i++) {
ToggleViewAction action= fViewActions[i];
action.setChecked(fCurrentViewerIndex == action.getViewerIndex());
}
}
/**
* Gets the curret active view index.
*/
public int getViewIndex() {
return fCurrentViewerIndex;
}
private TypeHierarchyViewer getCurrentViewer() {
return fAllViewers[fCurrentViewerIndex];
}
/**
* called from EnableMemberFilterAction.
* Must be called after creation of the viewpart.
*/
public void enableMemberFilter(boolean on) {
if (on != fIsEnableMemberFilter) {
fIsEnableMemberFilter= on;
if (!on) {
IType methodViewerInput= (IType) fMethodsViewer.getInput();
setMemberFilter(null);
updateHierarchyViewer(true);
updateTitle();
if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) {
// avoid that the method view changes content by selecting the previous input
internalSelectType(methodViewerInput, true);
} else if (fSelectedType != null) {
// choose a input that exists
internalSelectType(fSelectedType, true);
updateMethodViewer(fSelectedType);
}
} else {
methodSelectionChanged(fMethodsViewer.getSelection());
}
}
fEnableMemberFilterAction.setChecked(on);
}
/**
* called from ShowQualifiedTypeNamesAction. Must be called after creation
* of the viewpart.
*/
public void showQualifiedTypeNames(boolean on) {
if (fAllViewers == null) {
return;
}
for (int i= 0; i < fAllViewers.length; i++) {
fAllViewers[i].setQualifiedTypeName(on);
}
}
private boolean isShowQualifiedTypeNames() {
return fShowQualifiedTypeNamesAction.isChecked();
}
/**
* Called from ITypeHierarchyLifeCycleListener.
* Can be called from any thread
*/
protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) {
if (!fIsVisible) {
fNeedRefresh= true;
return;
}
if (fIsRefreshRunnablePosted) {
return;
}
Display display= getDisplay();
if (display != null) {
fIsRefreshRunnablePosted= true;
display.asyncExec(new Runnable() {
public void run() {
try {
if (fPagebook != null && !fPagebook.isDisposed()) {
doTypeHierarchyChangedOnViewers(changedTypes);
}
} finally {
fIsRefreshRunnablePosted= false;
}
}
});
}
}
protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) {
if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) {
clearInput();
} else {
if (changedTypes == null) {
// hierarchy change
try {
fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow());
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$
clearInput();
return;
} catch (InterruptedException e) {
return;
}
fMethodsViewer.refresh();
updateHierarchyViewer(false);
} else {
// elements in hierarchy modified
Object methodViewerInput= fMethodsViewer.getInput();
fMethodsViewer.refresh();
fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(methodViewerInput));
fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(methodViewerInput));
if (getCurrentViewer().isMethodFiltering()) {
if (changedTypes.length == 1) {
getCurrentViewer().refresh(changedTypes[0]);
} else {
updateHierarchyViewer(false);
}
} else {
getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } );
}
}
}
}
/*
* @see IViewPart#init
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* @see ViewPart#saveState(IMemento)
*/
public void saveState(IMemento memento) {
if (fPagebook == null) {
// part has not been created
if (fMemento != null) { //Keep the old state;
memento.putMemento(fMemento);
}
return;
}
if (fInputElement != null) {
String handleIndentifier= fInputElement.getHandleIdentifier();
if (fInputElement instanceof IType) {
ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy();
if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) {
// for startup performance reasons do not try to recover huge hierarchies
handleIndentifier= null;
}
}
memento.putString(TAG_INPUT, handleIndentifier);
}
memento.putInteger(TAG_VIEW, getViewIndex());
memento.putInteger(TAG_ORIENTATION, fCurrentOrientation);
int weigths[]= fTypeMethodsSplitter.getWeights();
int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]);
memento.putInteger(TAG_RATIO, ratio);
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putInteger(TAG_VERTICAL_SCROLL, position);
IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement();
if (selection != null) {
memento.putString(TAG_SELECTION, selection.getHandleIdentifier());
}
fMethodsViewer.saveState(memento);
saveLinkingEnabled(memento);
}
private void saveLinkingEnabled(IMemento memento) {
memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0);
}
/**
* Restores the type hierarchy settings from a memento.
*/
private void restoreState(IMemento memento, IJavaElement defaultInput) {
IJavaElement input= defaultInput;
String elementId= memento.getString(TAG_INPUT);
if (elementId != null) {
input= JavaCore.create(elementId);
if (input != null && !input.exists()) {
input= null;
}
if (!AllTypesCache.isIndexUpToDate()) {
input= null;
}
}
setInputElement(input);
Integer viewerIndex= memento.getInteger(TAG_VIEW);
if (viewerIndex != null) {
setView(viewerIndex.intValue());
}
Integer orientation= memento.getInteger(TAG_ORIENTATION);
if (orientation != null) {
setOrientation(orientation.intValue());
}
Integer ratio= memento.getInteger(TAG_RATIO);
if (ratio != null) {
fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() });
}
ScrollBar bar= getCurrentViewer().getTree().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
//String selectionId= memento.getString(TAG_SELECTION);
// do not restore type hierarchy contents
// if (selectionId != null) {
// IJavaElement elem= JavaCore.create(selectionId);
// if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) {
// internalSelectType((IMember)elem, false);
// }
// }
fMethodsViewer.restoreState(memento);
}
private void restoreLinkingEnabled(IMemento memento) {
Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR);
if (val != null) {
fLinkingEnabled= val.intValue() != 0;
}
}
/**
* view part becomes visible
*/
protected void visibilityChanged(boolean isVisible) {
fIsVisible= isVisible;
if (isVisible && fNeedRefresh) {
doTypeHierarchyChanged(fHierarchyLifeCycle, null);
}
fNeedRefresh= false;
}
/**
* Link selection to active editor.
*/
protected void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled()) {
return;
}
if (fInputElement == null) {
// no type hierarchy shown
return;
}
IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class);
try {
TypeHierarchyViewer currentViewer= getCurrentViewer();
if (elem instanceof IClassFile) {
IType type= ((IClassFile)elem).getType();
if (currentViewer.isElementShown(type)) {
internalSelectType(type, true);
updateMethodViewer(type);
}
} else if (elem instanceof ICompilationUnit) {
IType[] allTypes= ((ICompilationUnit)elem).getAllTypes();
for (int i= 0; i < allTypes.length; i++) {
if (currentViewer.isElementShown(allTypes[i])) {
internalSelectType(allTypes[i], true);
updateMethodViewer(allTypes[i]);
return;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return fInputElement;
}
/**
* Returns the <code>IShowInSource</code> for this view.
*/
protected IShowInSource getShowInSource() {
return new IShowInSource() {
public ShowInContext getShowInContext() {
return new ShowInContext(
null,
getSite().getSelectionProvider().getSelection());
}
};
}
boolean isLinkingEnabled() {
return fLinkingEnabled;
}
public void setLinkingEnabled(boolean enabled) {
fLinkingEnabled= enabled;
PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, enabled);
if (enabled) {
IEditorPart editor = getSite().getPage().getActiveEditor();
if (editor != null) {
editorActivated(editor);
}
}
}
}
|
40,830 |
Bug 40830 hierarchy view not up to date after rename [type hierarchy]
|
If you use the standard java perspective layout and have the following file --------------------------------A.java------------------------ public class A { } class B extends A { } -------------------------------------------------------------- double click on the first 'A' and press F4 (hierarchy view) then click on the package explorer (so as to hide the hierarchy view). then rename the class A to class C (using refactoring) double click on the new class name and click F4 the hierarchy still displays with 'A' at the root and not the new name ('C')
|
resolved fixed
|
e259d96
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-06T15:38:02Z | 2003-07-28T11:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.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.util;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.util.Assert;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
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.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.actions.OpenActionUtil;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart;
public class OpenTypeHierarchyUtil {
private OpenTypeHierarchyUtil() {
}
public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) {
IJavaElement[] candidates= getCandidates(element);
if (candidates != null) {
return open(candidates, window);
}
return null;
}
public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) {
Assert.isTrue(candidates != null && candidates.length != 0);
IJavaElement input= null;
if (candidates.length > 1) {
String title= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message"); //$NON-NLS-1$
input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message);
} else {
input= candidates[0];
}
if (input == null)
return null;
try {
if (PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.OPEN_TYPE_HIERARCHY))) {
return openInPerspective(window, input);
} else {
return openInViewPart(window, input);
}
} catch (WorkbenchException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$
e.getMessage());
} catch (JavaModelException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$
e.getMessage());
}
return null;
}
private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) {
IWorkbenchPage page= window.getActivePage();
try {
TypeHierarchyViewPart result= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY);
result.setInputElement(input);
if (input instanceof IMember) {
result.selectMember((IMember) input);
openEditor(input, false);
}
return result;
} catch (CoreException e) {
ExceptionHandler.handle(e, window.getShell(),
JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$
}
return null;
}
private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input) throws WorkbenchException, JavaModelException {
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
// The problem is that the input element can be a working copy. So we first convert it to the original element if
// it exists.
IJavaElement perspectiveInput= input;
if (input instanceof IMember) {
input= JavaModelUtil.toOriginal((IMember)input);
if (input.getElementType() != IJavaElement.TYPE) {
perspectiveInput= ((IMember)input).getDeclaringType();
} else {
perspectiveInput= input;
}
}
IWorkbenchPage page= workbench.showPerspective(JavaUI.ID_HIERARCHYPERSPECTIVE, window, perspectiveInput);
TypeHierarchyViewPart part= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY);
part.setInputElement(perspectiveInput);
if (input instanceof IMember) {
openEditor(input, false);
}
return part;
}
private static void openEditor(Object input, boolean activate) throws PartInitException, JavaModelException {
IEditorPart part= EditorUtility.openInEditor(input, activate);
if (input instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) input);
}
/**
* Converts the input to a possible input candidates
*/
public static IJavaElement[] getCandidates(Object input) {
if (!(input instanceof IJavaElement)) {
return null;
}
try {
IJavaElement elem= (IJavaElement) input;
switch (elem.getElementType()) {
case IJavaElement.INITIALIZER:
case IJavaElement.METHOD:
case IJavaElement.FIELD:
case IJavaElement.TYPE:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
case IJavaElement.JAVA_PROJECT:
return new IJavaElement[] { elem };
case IJavaElement.PACKAGE_FRAGMENT:
if (((IPackageFragment)elem).containsJavaResources())
return new IJavaElement[] {elem};
break;
case IJavaElement.PACKAGE_DECLARATION:
return new IJavaElement[] { elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT) };
case IJavaElement.IMPORT_DECLARATION:
IImportDeclaration decl= (IImportDeclaration) elem;
if (decl.isOnDemand()) {
elem= JavaModelUtil.findTypeContainer(elem.getJavaProject(), Signature.getQualifier(elem.getElementName()));
} else {
elem= elem.getJavaProject().findType(elem.getElementName());
}
if (elem == null)
return null;
return new IJavaElement[] {elem};
case IJavaElement.CLASS_FILE:
return new IJavaElement[] { ((IClassFile)input).getType() };
case IJavaElement.COMPILATION_UNIT: {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
IType[] types= cu.getTypes();
if (types.length > 0) {
return types;
}
}
break;
}
default:
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
}
|
39,473 |
Bug 39473 [quick fix] "Create method" quickfix offers to create duplicate method in enclosing type
|
200306250800 1. have a class, e.g. public class MyAction implements IEditorActionDelegate { public void run(IAction action) {} void myMethod() { Runnable r= new Runnable() { public void run() { Action a; <HERE> run(a); } } } } 2. correctly, an error is displayed at <LINE> 3. Quickfix offers to create a local method matching the parameter, which is fine, but also: - Change method run(IAction) to run(IAction) which is idempotent - Create method run(IAction) in MyAction The latter inserts a method run(Action) in the enclosing type which will be marked as a duplicate. -> Enhancement and fix request: add quickfix "change to call to enclosing type" should produce the following code at <LINE> MyAction.this.run(a);
|
resolved fixed
|
ff5d886
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T09:29:57Z | 2003-06-30T13:33:20Z |
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/UnresolvedMethodsQuickFixTest.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.tests.quickfix;
import java.util.ArrayList;
import java.util.Hashtable;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.eclipse.jdt.testplugin.JavaProjectHelper;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.tests.core.ProjectTestSetup;
import org.eclipse.jdt.internal.corext.dom.TypeRules;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal;
import org.eclipse.jdt.internal.ui.text.correction.NewMethodCompletionProposal;
public class UnresolvedMethodsQuickFixTest extends QuickFixTest {
private static final Class THIS= UnresolvedMethodsQuickFixTest.class;
private IJavaProject fJProject1;
private IPackageFragmentRoot fSourceFolder;
public UnresolvedMethodsQuickFixTest(String name) {
super(name);
}
public static Test allTests() {
return new ProjectTestSetup(new TestSuite(THIS));
}
public static Test suite() {
if (true) {
return allTests();
} else {
TestSuite suite= new TestSuite();
suite.addTest(new UnresolvedMethodsQuickFixTest("testParameterMismatchMoreArguments4"));
return new ProjectTestSetup(suite);
}
}
protected void setUp() throws Exception {
Hashtable options= JavaCore.getDefaultOptions();
options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE);
options.put(JavaCore.FORMATTER_TAB_SIZE, "4");
options.put(JavaCore.COMPILER_PB_NO_EFFECT_ASSIGNMENT, JavaCore.IGNORE);
JavaCore.setOptions(options);
IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore();
store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false);
fJProject1= ProjectTestSetup.getProject();
CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern("");
CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern("");
fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src");
}
protected void tearDown() throws Exception {
JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath());
}
public void testMethodInSameType() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInForInit() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo() {\n");
buf.append(" for (int i= 0, j= goo(3); i < 0; i++) {\n");
buf.append(" }\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(int i) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInInfixExpression1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) || f(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) || f(2);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private boolean f(int i) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInInfixExpression2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) == f(2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot, 2);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" private boolean foo() {\n");
buf.append(" return f(1) == f(2);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private Object f(int i) {\n");
buf.append(" return null;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing0EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing1EmptyLine() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacing2EmptyLines() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append(" \n");
buf.append(" \n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingComment() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append("//comment\n");
buf.append("\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /**\n");
buf.append(" * javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodSpacingNonJavadoc() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append("\n");
buf.append(" void fred() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" /*\n");
buf.append(" * non javadoc\n");
buf.append(" */\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInSameTypeUsingThis() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" void foo(Vector vec) {\n");
buf.append(" int i= this.goo(vec, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private int goo(Vector vec, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInDifferentClass() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(1, 2.1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append("\n");
buf.append(" public boolean goo(int i, double d) {\n");
buf.append(" return false;\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testMethodInAnonymous1() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void xoo() {\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" protected void xoo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" foo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testMethodInAnonymous2() throws Exception {
IPackageFragment pack0= fSourceFolder.createPackageFragment("other", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack0.createCompilationUnit("A.java", buf.toString(), false, null);
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import other.A;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" new Runnable() {\n");
buf.append(" public void run() {\n");
buf.append(" A.xoo();\n");
buf.append(" }\n");
buf.append(" };\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package other;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public static void xoo() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
assertEqualString(preview1, expected1);
}
public void testMethodInDifferentInterface() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" void foo(X x) {\n");
buf.append(" boolean i= x.goo(getClass());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu, true);
ArrayList proposals= collectCorrections(cu, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public interface X {\n");
buf.append("\n");
buf.append(" boolean goo(Class class1);\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testParameterMismatchCast() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo((int) (x + 1));\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(long l) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(long l) {\n");
buf.append(" long x= 0;\n");
buf.append(" foo(x + 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchCast2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((float) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" double x= 0.0;\n");
buf.append(" X.xoo((int) x, this);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(float f, E e) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(float f, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x, o);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int i, Object o) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchLessArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(null);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo() {\n");
buf.append(" X.xoo(0, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public static void xoo(Object object) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public static void xoo(Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructorLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public X(Object o, int i) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public E() {\n");
buf.append(" super(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public E() {\n");
buf.append(" super(new Vector(), 0);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public X(Object o, int i) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public X(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public X(Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testConstructorInvocationLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" }\n");
buf.append(" public E() {\n");
buf.append(" this(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" }\n");
buf.append(" public E() {\n");
buf.append(" this(new Vector(), 0);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E(Object o) {\n");
buf.append(" }\n");
buf.append(" public E() {\n");
buf.append(" this(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" }\n");
buf.append(" public E() {\n");
buf.append(" this(new Vector());\n");
buf.append(" }\n");
buf.append(" public E(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, 1, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, int j, Object o) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i, Object o) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(int i, int j, X x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments2() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(String s, int x) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(String s, int x2) {\n");
buf.append(" int x= 0;\n");
buf.append(" foo(s, x);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchMoreArguments3() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(Collections.EMPTY_SET, 1, 2);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Collections;\n");
buf.append("public class E {\n");
buf.append(" public void foo(X x) {\n");
buf.append(" x.xoo(1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(Set set, int i, int k) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Set;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public void xoo(int i) {\n");
buf.append(" int j= 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void xoo(Set set, int i, int j) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructorMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public X() {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public E() {\n");
buf.append(" super(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public E() {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public X() {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public X(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public X(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testConstructorInvocationMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" this(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" this();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E(Vector vector) {\n");
buf.append(" }\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" this(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E {\n");
buf.append(" public E() {\n");
buf.append(" }\n");
buf.append(" public E(Object o, int i) {\n");
buf.append(" this(new Vector());\n");
buf.append(" }\n");
buf.append(" public E(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testParameterMismatchSwap() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(i - 1, new Object[] { o });\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i, Object o) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" private void foo(Object[] objects, int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(Object o, int i) {\n");
buf.append(" foo(new Object[] { o }, i - 1);\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperConstructor() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public E(int i) {\n");
buf.append(" super();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testClassInstanceCreation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 2);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A();\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 });
}
public void testClassInstanceCreationMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i, String.valueOf(i), true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i, String string, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public A(int i, String string, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testClassInstanceCreationLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A();\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i, String s) {\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" A a= new A(i, null);\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append(" public A(int i, String s) {\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public A() {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testConstructorInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E {\n");
buf.append(" public E(int i) {\n");
buf.append(" this(i, true);\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public E(int i, boolean b) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
assertEqualString(preview1, expected1);
}
public void testSuperMethodInvocation() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class E extends A {\n");
buf.append(" public void foo(int i) {\n");
buf.append(" super.foo(i);\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("}\n");
pack1.createCompilationUnit("A.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 1);
assertCorrectLabels(proposals);
NewMethodCompletionProposal proposal= (NewMethodCompletionProposal) proposals.get(0);
String preview= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class A {\n");
buf.append("\n");
buf.append(" public void foo(int i) {\n");
buf.append(" }\n");
buf.append("}\n");
assertEqualString(preview, buf.toString());
}
public void testSuperMethodMoreArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public int foo() {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public void xoo() {\n");
buf.append(" super.foo(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public void xoo() {\n");
buf.append(" super.foo();\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public int foo(Vector vector) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public int foo() {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void foo(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testSuperMethodLessArguments() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public int foo(Object o, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
pack1.createCompilationUnit("X.java", buf.toString(), false, null);
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public void xoo() {\n");
buf.append(" super.foo(new Vector());\n");
buf.append(" }\n");
buf.append("}\n");
ICompilationUnit cu1= pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
ArrayList proposals= collectCorrections(cu1, astRoot);
assertNumberOf("proposals", proposals.size(), 3);
assertCorrectLabels(proposals);
CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0);
String preview1= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("public class E extends X {\n");
buf.append(" public void xoo() {\n");
buf.append(" super.foo(new Vector(), false);\n");
buf.append(" }\n");
buf.append("}\n");
String expected1= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(1);
String preview2= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class X {\n");
buf.append(" public int foo(Object o) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("}\n");
String expected2= buf.toString();
proposal= (CUCorrectionProposal) proposals.get(2);
String preview3= proposal.getCompilationUnitChange().getPreviewContent();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("\n");
buf.append("import java.util.Vector;\n");
buf.append("\n");
buf.append("public class X {\n");
buf.append(" public int foo(Object o, boolean b) {\n");
buf.append(" return 0;\n");
buf.append(" }\n");
buf.append("\n");
buf.append(" public void foo(Vector vector) {\n");
buf.append(" }\n");
buf.append("}\n");
String expected3= buf.toString();
assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 });
}
public void testCanAssign() throws Exception {
IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null);
StringBuffer buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("import java.util.Vector;\n");
buf.append("import java.util.Collection;\n");
buf.append("import java.io.Serializable;\n");
buf.append("public class E {\n");
buf.append(" boolean bool;\n");
buf.append(" char c;\n");
buf.append(" byte b;\n");
buf.append(" short s;\n");
buf.append(" int i;\n");
buf.append(" long l;\n");
buf.append(" float f;\n");
buf.append(" double d;\n");
buf.append(" Object object;\n");
buf.append(" Vector vector;\n");
buf.append(" Cloneable cloneable;\n");
buf.append(" Collection collection;\n");
buf.append(" Serializable serializable;\n");
buf.append(" Object[] objectArr;\n");
buf.append(" int[] int_arr;\n");
buf.append(" long[] long_arr;\n");
buf.append(" Vector[] vector_arr;\n");
buf.append(" Collection[] collection_arr;\n");
buf.append(" Object[][] objectArrArr;\n");
buf.append(" Collection[][] collection_arrarr;\n");
buf.append(" Vector[][] vector_arrarr;\n");
buf.append("}\n");
ICompilationUnit cu1=pack1.createCompilationUnit("E.java", buf.toString(), false, null);
CompilationUnit astRoot= AST.parseCompilationUnit(cu1, true);
IProblem[] problems= astRoot.getProblems();
assertNumberOf("problems", problems.length, 0);
TypeDeclaration type= findTypeDeclaration(astRoot, "E");
VariableDeclarationFragment bool= findFieldDeclaration(type, "bool");
VariableDeclarationFragment c= findFieldDeclaration(type, "c");
VariableDeclarationFragment b= findFieldDeclaration(type, "b");
VariableDeclarationFragment s= findFieldDeclaration(type, "s");
VariableDeclarationFragment i= findFieldDeclaration(type, "i");
VariableDeclarationFragment l= findFieldDeclaration(type, "l");
VariableDeclarationFragment f= findFieldDeclaration(type, "f");
VariableDeclarationFragment d= findFieldDeclaration(type, "d");
VariableDeclarationFragment object= findFieldDeclaration(type, "object");
VariableDeclarationFragment vector= findFieldDeclaration(type, "vector");
VariableDeclarationFragment cloneable= findFieldDeclaration(type, "cloneable");
VariableDeclarationFragment collection= findFieldDeclaration(type, "collection");
VariableDeclarationFragment serializable= findFieldDeclaration(type, "serializable");
VariableDeclarationFragment objectArr= findFieldDeclaration(type, "objectArr");
VariableDeclarationFragment int_arr= findFieldDeclaration(type, "int_arr");
VariableDeclarationFragment long_arr= findFieldDeclaration(type, "long_arr");
VariableDeclarationFragment vector_arr= findFieldDeclaration(type, "vector_arr");
VariableDeclarationFragment collection_arr= findFieldDeclaration(type, "collection_arr");
VariableDeclarationFragment objectArrArr= findFieldDeclaration(type, "objectArrArr");
VariableDeclarationFragment collection_arrarr= findFieldDeclaration(type, "collection_arrarr");
VariableDeclarationFragment vector_arrarr= findFieldDeclaration(type, "vector_arrarr");
VariableDeclarationFragment[] targets= new VariableDeclarationFragment[] {
bool, c, b, s, i, l, f, d, object, vector, cloneable, serializable, collection, objectArr, int_arr, long_arr,
vector_arr, collection_arr, objectArrArr, collection_arrarr, vector_arrarr
};
for (int k= 0; k < targets.length; k++) {
for (int n= 0; n < targets.length; n++) {
VariableDeclarationFragment f1= targets[k];
VariableDeclarationFragment f2= targets[n];
String line= f2.getName().getIdentifier() + "= " + f1.getName().getIdentifier();
buf= new StringBuffer();
buf.append("package test1;\n");
buf.append("public class F extends E {\n");
buf.append(" void foo() {\n");
buf.append(" ").append(line).append(";\n");
buf.append(" }\n");
buf.append("}\n");
char[] content= buf.toString().toCharArray();
astRoot= AST.parseCompilationUnit(content, "F.java", cu1.getJavaProject());
problems= astRoot.getProblems();
ITypeBinding b1= f1.resolveBinding().getType();
assertNotNull(b1);
ITypeBinding b2= f2.resolveBinding().getType();
assertNotNull(b2);
boolean res= TypeRules.canAssign(b1, b2.getQualifiedName());
assertEquals(line, problems.length == 0, res);
boolean res2= TypeRules.canAssign(b1, b2);
assertEquals(line, problems.length == 0, res2);
}
}
}
}
|
39,473 |
Bug 39473 [quick fix] "Create method" quickfix offers to create duplicate method in enclosing type
|
200306250800 1. have a class, e.g. public class MyAction implements IEditorActionDelegate { public void run(IAction action) {} void myMethod() { Runnable r= new Runnable() { public void run() { Action a; <HERE> run(a); } } } } 2. correctly, an error is displayed at <LINE> 3. Quickfix offers to create a local method matching the parameter, which is fine, but also: - Change method run(IAction) to run(IAction) which is idempotent - Create method run(IAction) in MyAction The latter inserts a method run(Action) in the enclosing type which will be marked as a duplicate. -> Enhancement and fix request: add quickfix "change to call to enclosing type" should produce the following code at <LINE> MyAction.this.run(a);
|
resolved fixed
|
ff5d886
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T09:29:57Z | 2003-06-30T13:33:20Z |
org.eclipse.jdt.ui/core
| |
39,473 |
Bug 39473 [quick fix] "Create method" quickfix offers to create duplicate method in enclosing type
|
200306250800 1. have a class, e.g. public class MyAction implements IEditorActionDelegate { public void run(IAction action) {} void myMethod() { Runnable r= new Runnable() { public void run() { Action a; <HERE> run(a); } } } } 2. correctly, an error is displayed at <LINE> 3. Quickfix offers to create a local method matching the parameter, which is fine, but also: - Change method run(IAction) to run(IAction) which is idempotent - Create method run(IAction) in MyAction The latter inserts a method run(Action) in the enclosing type which will be marked as a duplicate. -> Enhancement and fix request: add quickfix "change to call to enclosing type" should produce the following code at <LINE> MyAction.this.run(a);
|
resolved fixed
|
ff5d886
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T09:29:57Z | 2003-06-30T13:33:20Z |
extension/org/eclipse/jdt/internal/corext/dom/Bindings.java
| |
39,473 |
Bug 39473 [quick fix] "Create method" quickfix offers to create duplicate method in enclosing type
|
200306250800 1. have a class, e.g. public class MyAction implements IEditorActionDelegate { public void run(IAction action) {} void myMethod() { Runnable r= new Runnable() { public void run() { Action a; <HERE> run(a); } } } } 2. correctly, an error is displayed at <LINE> 3. Quickfix offers to create a local method matching the parameter, which is fine, but also: - Change method run(IAction) to run(IAction) which is idempotent - Create method run(IAction) in MyAction The latter inserts a method run(Action) in the enclosing type which will be marked as a duplicate. -> Enhancement and fix request: add quickfix "change to call to enclosing type" should produce the following code at <LINE> MyAction.this.run(a);
|
resolved fixed
|
ff5d886
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T09:29:57Z | 2003-06-30T13:33: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 <[email protected]> - 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.ui.text.java.*;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
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.textmanipulation.SimpleTextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
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.preferences.JavaPreferencesSettings;
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;
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 suggestVariablePropasals= true;
int typeKind= 0;
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) {
suggestVariablePropasals= false;
typeKind= SimilarElementsRequestor.REF_TYPES;
}
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;
suggestVariablePropasals= node.isSimpleName();
}
if (selectedNode.getParent() instanceof SimpleType) {
typeKind= SimilarElementsRequestor.REF_TYPES;
suggestVariablePropasals= 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(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if (!suggestVariablePropasals) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
addSimilarVariableProposals(cu, astRoot, simpleName, proposals);
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image));
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
senderBinding= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!senderBinding.isAnonymous()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image));
}
}
}
}
if (binding == null) {
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 5, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 7, 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= new ASTRewrite(statement.getParent());
rewrite.markAsRemoved(statement);
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);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
}
}
private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, Collection proposals) {
IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES);
if (varsInScope.length > 0) {
// avoid corrections like int i= i;
String assignedName= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier();
}
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();
if (!currName.equals(assignedName)) {
int relevance= 0;
if (NameMatcher.isSimilarName(currName, identifier)) {
relevance += 3; // variable with a similar name than the unresolved variable
}
if (guessedType != null && TypeRules.canAssign(guessedType, curr.getType())) {
relevance += 2; // unresolved variable can be assign to this variable
}
if (relevance > 0) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance));
}
}
}
}
}
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 variablefragment
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.REF_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;
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 simlar 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 JavaModelException {
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 JavaModelException {
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importEdit.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importEdit.isEmpty()) {
root.add(importEdit); //$NON-NLS-1$
}
String[] arg= { simpleName, Signature.getQualifier(fullName) };
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg)); //$NON-NLS-1$
proposal.setRelevance(relevance + 20);
} else {
root.add(SimpleTextEdit.createReplace(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg)); //$NON-NLS-1$
proposal.setRelevance(relevance);
}
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTResolving.getSimpleName(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't sugest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 24347
// IBinding binding= qualifierName.resolveBinding();
// if (binding instanceof ITypeBinding) {
// enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject());
IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
if (res!= null && res.length > 0 && res[0] instanceof IType) {
enclosingType= (IType) res[0];
} else {
qualifier= qualifierName;
enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
}
}
// new top level type
if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance));
}
}
// new member type
if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) {
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance));
}
}
}
node= qualifier;
} while (node != null);
}
public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, 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) && needsNewName) {
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 ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6));
}
}
addParameterMissmatchProposals(context, problem, parameterMismatchs, 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)) {
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));
}
}
}
}
}
}
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, 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, 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, arguments, argTypes, elem, proposals);
} else {
doMoreArguments(context, problem, arguments, argTypes, elem, proposals);
}
}
}
private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, 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();
ASTNode nameNode= problem.getCoveringNode(astRoot);
if (nameNode == null) {
return;
}
// 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(), nameNode, arguments, indexSkipped, paramTypes, 8);
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD));
proposal.ensureNoModifications();
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, nameNode, methodBinding, changeDesc, 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 void doMoreArguments(IInvocationContext context, IProblemLocation problem, 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();
ASTNode nameNode= problem.getCoveringNode(astRoot);
if (nameNode == null) {
return;
}
// remove arguments
{
ASTNode selectedNode= problem.getCoveringNode(astRoot);
ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent());
for (int i= diff - 1; i >= 0; i--) {
rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i]));
}
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);
proposal.ensureNoModifications();
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 (isDifferentCU && 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, nameNode, methodBinding, changeDesc, 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;
}
}
CompilationUnit unit= AST.parsePartialCompilationUnit(targetCU, 0, true);
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, 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 == 1) { // one argument missmatching: try to fix
int idx= indexOfDiff[0];
Expression nodeToCast= (Expression) arguments.get(idx);
String castType= paramTypes[idx].getQualifiedName();
ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.getCastProposal(context, castType, nodeToCast, 6);
if (proposal != null) { // null returned when no cast is possible
proposals.add(proposal);
String[] arg= new String[] { String.valueOf(idx + 1), castType };
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$
}
}
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= new ASTRewrite(arg1.getParent());
rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2));
rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1));
{
String[] arg= new String[] { String.valueOf(idx1 + 1), String.valueOf(idx2 + 1) };
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);
proposal.ensureNoModifications();
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[] { argTypes[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, nameNode, methodBinding, changeDesc, 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);
}
String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) };
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, nameNode, methodBinding, changeDesc, 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;
}
curr= Bindings.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
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, 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= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
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) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image);
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importEdit.addImport(qualifiedTypeName);
importEdit.setFindAmbiguosImports(true);
proposal.getRootTextEdit().add(importEdit);
proposals.add(proposal);
}
}
}
}
|
31,543 |
Bug 31543 Outliner - Override indicator fooled by visibility issue [render]
|
Build 20030206 On the following example, the compiler will report that method Test.foo() isn't overriding the package private one from Base, however the outliner still shows the override indicator on it. ========================== foo/Base.java package foo; public class Base { void foo(){} } ========================== bar/Test.java package bar; public class Test extends foo.Base { void foo(){} // doesn't override Base.foo() }
|
resolved fixed
|
b1175d5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T10:05:45Z | 2003-02-11T13:26:40Z |
org.eclipse.jdt.ui/core
| |
31,543 |
Bug 31543 Outliner - Override indicator fooled by visibility issue [render]
|
Build 20030206 On the following example, the compiler will report that method Test.foo() isn't overriding the package private one from Base, however the outliner still shows the override indicator on it. ========================== foo/Base.java package foo; public class Base { void foo(){} } ========================== bar/Test.java package bar; public class Test extends foo.Base { void foo(){} // doesn't override Base.foo() }
|
resolved fixed
|
b1175d5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T10:05:45Z | 2003-02-11T13:26:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
31,543 |
Bug 31543 Outliner - Override indicator fooled by visibility issue [render]
|
Build 20030206 On the following example, the compiler will report that method Test.foo() isn't overriding the package private one from Base, however the outliner still shows the override indicator on it. ========================== foo/Base.java package foo; public class Base { void foo(){} } ========================== bar/Test.java package bar; public class Test extends foo.Base { void foo(){} // doesn't override Base.foo() }
|
resolved fixed
|
b1175d5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T10:05:45Z | 2003-02-11T13:26:40Z |
org.eclipse.jdt.ui/core
| |
31,543 |
Bug 31543 Outliner - Override indicator fooled by visibility issue [render]
|
Build 20030206 On the following example, the compiler will report that method Test.foo() isn't overriding the package private one from Base, however the outliner still shows the override indicator on it. ========================== foo/Base.java package foo; public class Base { void foo(){} } ========================== bar/Test.java package bar; public class Test extends foo.Base { void foo(){} // doesn't override Base.foo() }
|
resolved fixed
|
b1175d5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T10:05:45Z | 2003-02-11T13:26:40Z |
extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java
| |
31,543 |
Bug 31543 Outliner - Override indicator fooled by visibility issue [render]
|
Build 20030206 On the following example, the compiler will report that method Test.foo() isn't overriding the package private one from Base, however the outliner still shows the override indicator on it. ========================== foo/Base.java package foo; public class Base { void foo(){} } ========================== bar/Test.java package bar; public class Test extends foo.Base { void foo(){} // doesn't override Base.foo() }
|
resolved fixed
|
b1175d5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T10:05:45Z | 2003-02-11T13:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HierarchyInformationControl.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.lang.reflect.InvocationTargetException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
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.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.AbstractInformationControl;
import org.eclipse.jdt.internal.ui.typehierarchy.TraditionalHierarchyViewer.TraditionalHierarchyContentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
*
*/
public class HierarchyInformationControl extends AbstractInformationControl {
private class HierarchyInformationControlLabelProvider extends HierarchyLabelProvider {
public HierarchyInformationControlLabelProvider(TypeHierarchyLifeCycle lifeCycle) {
super(lifeCycle);
}
protected boolean isDifferentScope(IType type) {
if (fFocus == null) {
return super.isDifferentScope(type);
}
IMethod[] methods= type.findMethods(fFocus);
if (methods != null && methods.length > 0) {
try {
// check visibility
IPackageFragment pack= (IPackageFragment) fFocus.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
for (int i= 0; i < methods.length; i++) {
IMethod curr= methods[i];
if (Flags.isProtected(curr.getFlags()) || JavaModelUtil.isVisible(curr, pack)) {
return false;
}
}
} catch (JavaModelException e) {
// ignore
JavaPlugin.log(e);
}
}
return true;
}
}
private TypeHierarchyLifeCycle fLifeCycle;
private HierarchyInformationControlLabelProvider fLabelProvider;
private Label fLabel;
private IMethod fFocus; // method to filter for or null if type hierarchy
private boolean fDoFilter= true;
public HierarchyInformationControl(Shell parent, int shellStyle, int treeStyle) {
super(parent, shellStyle, treeStyle);
}
protected Text createFilterText(Composite parent) {
fLabel= new Label(parent, SWT.NONE);
// text set later
fLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fLabel.setFont(JFaceResources.getBannerFont());
return super.createFilterText(parent);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl#createTreeViewer(org.eclipse.swt.widgets.Composite, int)
*/
protected TreeViewer createTreeViewer(Composite parent, int style) {
Tree tree= new Tree(parent, SWT.SINGLE | (style & ~SWT.MULTI));
tree.setLayoutData(new GridData(GridData.FILL_BOTH));
TreeViewer treeViewer= new TreeViewer(tree);
treeViewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
return element instanceof IType;
}
});
fLifeCycle= new TypeHierarchyLifeCycle(false);
treeViewer.setSorter(new HierarchyViewerSorter(fLifeCycle));
treeViewer.setAutoExpandLevel(AbstractTreeViewer.ALL_LEVELS);
fLabelProvider= new HierarchyInformationControlLabelProvider(fLifeCycle);
fLabelProvider.setTextFlags(JavaElementLabels.ALL_DEFAULT | JavaElementLabels.T_POST_QUALIFIED);
treeViewer.setLabelProvider(new DecoratingJavaLabelProvider(fLabelProvider, true, false));
return treeViewer;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#setForegroundColor(org.eclipse.swt.graphics.Color)
*/
public void setForegroundColor(Color foreground) {
super.setForegroundColor(foreground);
fLabel.setForeground(foreground);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#setBackgroundColor(org.eclipse.swt.graphics.Color)
*/
public void setBackgroundColor(Color background) {
super.setBackgroundColor(background);
fLabel.setBackground(background);
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.JavaOutlineInformationControl#setInput(java.lang.Object)
*/
public void setInput(Object information) {
if (!(information instanceof IJavaElement)) {
inputChanged(null, null);
return;
}
IJavaElement input= null;
IMethod locked= null;
try {
IJavaElement elem= (IJavaElement) information;
switch (elem.getElementType()) {
case IJavaElement.JAVA_PROJECT :
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
case IJavaElement.PACKAGE_FRAGMENT :
case IJavaElement.TYPE :
input= elem;
break;
case IJavaElement.COMPILATION_UNIT :
input= ((ICompilationUnit) elem).findPrimaryType();
break;
case IJavaElement.CLASS_FILE :
input= ((IClassFile) elem).getType();
break;
case IJavaElement.METHOD :
IMethod method= (IMethod) elem;
if (!method.isConstructor()) {
locked= method;
}
input= method.getDeclaringType();
break;
case IJavaElement.FIELD :
case IJavaElement.INITIALIZER :
input= ((IMember) elem).getDeclaringType();
break;
case IJavaElement.PACKAGE_DECLARATION :
input= elem.getParent().getParent();
break;
case IJavaElement.IMPORT_DECLARATION :
IImportDeclaration decl= (IImportDeclaration) elem;
if (decl.isOnDemand()) {
input= JavaModelUtil.findTypeContainer(decl.getJavaProject(), Signature.getQualifier(decl.getElementName()));
} else {
input= decl.getJavaProject().findType(decl.getElementName());
}
break;
default :
input= null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
fLabel.setText(getHeaderLabel(locked == null ? input : locked));
try {
fLifeCycle.ensureRefreshedTypeHierarchy(input, JavaPlugin.getActiveWorkbenchWindow());
} catch (InvocationTargetException e1) {
input= null;
} catch (InterruptedException e1) {
dispose();
return;
}
TraditionalHierarchyContentProvider contentProvider= new TraditionalHierarchyContentProvider(fLifeCycle);
contentProvider.setMemberFilter(locked != null ? new IMember[] { locked } : null);
getTreeViewer().setContentProvider(contentProvider);
fFocus= locked;
Object[] topLevelObjects= contentProvider.getElements(fLifeCycle);
if (topLevelObjects.length > 0 && contentProvider.getChildren(topLevelObjects[0]).length > 40) {
fDoFilter= false;
} else {
getTreeViewer().addFilter(new NamePatternFilter());
}
Object selection= null;
if (input instanceof IMember) {
selection= input;
} else if (topLevelObjects.length > 0) {
selection= topLevelObjects[0];
}
inputChanged(fLifeCycle, selection);
}
protected void stringMatcherUpdated() {
if (fDoFilter) {
super.stringMatcherUpdated(); // refresh the view
} else {
selectFirstMatch();
}
}
private String getHeaderLabel(IJavaElement input) {
if (input instanceof IMethod) {
String[] args= { input.getParent().getElementName(), JavaElementLabels.getElementLabel(input, JavaElementLabels.ALL_DEFAULT) };
return TypeHierarchyMessages.getFormattedString("HierarchyInformationControl.methodhierarchy.label", args); //$NON-NLS-1$
} else {
String arg= JavaElementLabels.getElementLabel(input, JavaElementLabels.DEFAULT_QUALIFIED);
return TypeHierarchyMessages.getFormattedString("HierarchyInformationControl.hierarchy.label", arg); //$NON-NLS-1$
}
}
/*
* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.text.AbstractInformationControl#getSelectedElement()
*/
protected Object getSelectedElement() {
Object selectedElement= super.getSelectedElement();
if (selectedElement instanceof IType && fFocus != null) {
IMethod[] methods= ((IType) selectedElement).findMethods(fFocus);
if (methods != null && methods.length > 0) {
return methods[0];
}
}
return selectedElement;
}
}
|
31,543 |
Bug 31543 Outliner - Override indicator fooled by visibility issue [render]
|
Build 20030206 On the following example, the compiler will report that method Test.foo() isn't overriding the package private one from Base, however the outliner still shows the override indicator on it. ========================== foo/Base.java package foo; public class Base { void foo(){} } ========================== bar/Test.java package bar; public class Test extends foo.Base { void foo(){} // doesn't override Base.foo() }
|
resolved fixed
|
b1175d5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T10:05:45Z | 2003-02-11T13:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/OverrideIndicatorLabelDecorator.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;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.viewers.IDecoration;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ILightweightLabelDecorator;
import org.eclipse.jdt.core.Flags;
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.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.JavaPluginImages;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ImageImageDescriptor;
/**
* LabelDecorator that decorates an method's image with override or implements overlays.
* The viewer using this decorator is responsible for updating the images on element changes.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OverrideIndicatorLabelDecorator implements ILabelDecorator, ILightweightLabelDecorator {
private ImageDescriptorRegistry fRegistry;
private boolean fUseNewRegistry= false;
/**
* Creates a decorator. The decorator creates an own image registry to cache
* images.
*/
public OverrideIndicatorLabelDecorator() {
this(null);
fUseNewRegistry= true;
}
/*
* Creates decorator with a shared image registry.
*
* @param registry The registry to use or <code>null</code> to use the Java plugin's
* image registry.
*/
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OverrideIndicatorLabelDecorator(ImageDescriptorRegistry registry) {
fRegistry= registry;
}
private ImageDescriptorRegistry getRegistry() {
if (fRegistry == null) {
fRegistry= fUseNewRegistry ? new ImageDescriptorRegistry() : JavaPlugin.getImageDescriptorRegistry();
}
return fRegistry;
}
/* (non-Javadoc)
* @see ILabelDecorator#decorateText(String, Object)
*/
public String decorateText(String text, Object element) {
return text;
}
/* (non-Javadoc)
* @see ILabelDecorator#decorateImage(Image, Object)
*/
public Image decorateImage(Image image, Object element) {
int adornmentFlags= computeAdornmentFlags(element);
if (adornmentFlags != 0) {
ImageDescriptor baseImage= new ImageImageDescriptor(image);
Rectangle bounds= image.getBounds();
return getRegistry().get(new JavaElementImageDescriptor(baseImage, adornmentFlags, new Point(bounds.width, bounds.height)));
}
return image;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
public int computeAdornmentFlags(Object element) {
if (element instanceof IMethod) {
if (!PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR)) {
return 0;
}
try {
IMethod method= (IMethod) element;
if (!method.getJavaProject().isOnClasspath(method)) {
return 0;
}
int flags= method.getFlags();
if (method.getDeclaringType().isClass() && !method.isConstructor() && !Flags.isPrivate(flags) && !Flags.isStatic(flags)) {
return getOverrideIndicators(method);
}
} catch (JavaModelException e) {
if (!e.isDoesNotExist()) {
JavaPlugin.log(e);
}
}
}
return 0;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected int getOverrideIndicators(IMethod method) throws JavaModelException {
IType type= method.getDeclaringType();
ITypeHierarchy hierarchy= SuperTypeHierarchyCache.getTypeHierarchy(type);
if (hierarchy != null) {
return findInHierarchy(type, hierarchy, method.getElementName(), method.getParameterTypes());
}
return 0;
}
/**
* Note: This method is for internal use only. Clients should not call this method.
*/
protected int findInHierarchy(IType type, ITypeHierarchy hierarchy, String name, String[] paramTypes) throws JavaModelException {
IMethod impl= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, name, paramTypes, false);
if (impl != null) {
IMethod overridden= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, name, paramTypes, false);
if (overridden != null) {
return JavaElementImageDescriptor.OVERRIDES;
} else {
return JavaElementImageDescriptor.IMPLEMENTS;
}
}
return 0;
}
/* (non-Javadoc)
* @see IBaseLabelProvider#addListener(ILabelProviderListener)
*/
public void addListener(ILabelProviderListener listener) {
}
/* (non-Javadoc)
* @see IBaseLabelProvider#dispose()
*/
public void dispose() {
if (fRegistry != null && fUseNewRegistry) {
fRegistry.dispose();
}
}
/* (non-Javadoc)
* @see IBaseLabelProvider#isLabelProperty(Object, String)
*/
public boolean isLabelProperty(Object element, String property) {
return true;
}
/* (non-Javadoc)
* @see IBaseLabelProvider#removeListener(ILabelProviderListener)
*/
public void removeListener(ILabelProviderListener listener) {
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ILightweightLabelDecorator#decorate(java.lang.Object, org.eclipse.jface.viewers.IDecoration)
*/
public void decorate(Object element, IDecoration decoration) {
int adornmentFlags= computeAdornmentFlags(element);
if (adornmentFlags != 0) {
decoration.addOverlay(JavaPluginImages.DESC_OVR_OVERRIDES);
}
}
}
|
35,526 |
Bug 35526 Error not surfaced on failed quick fix [quick fix]
|
Build: 2.1 RC3a 1) Create a java file, A.java: public class A { } 2) In the java editor, change the class name to "Com1". 3) The word "Com1" will be underlined because it doesn't match the compilation unit name. Select the name and invoke quick fix. 4) Choose the quick fix option, "Rename the compilation unit to Com1.java" -> Nothing happens. The log file contains several stack traces Expectation: The error should be reported to the user, not to the log (since it's a user error, not a program failure).
|
resolved fixed
|
2be3e04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T14:28:07Z | 2003-03-21T20:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ChangeCorrectionProposal.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 org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
import org.eclipse.jdt.internal.corext.refactoring.base.Change;
import org.eclipse.jdt.internal.corext.refactoring.base.ChangeAbortException;
import org.eclipse.jdt.internal.corext.refactoring.base.ChangeContext;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.refactoring.changes.AbortChangeExceptionHandler;
public class ChangeCorrectionProposal implements IJavaCompletionProposal {
private Change fChange;
private String fName;
private int fRelevance;
private Image fImage;
public ChangeCorrectionProposal(String name, Change change, int relevance) {
this(name, change, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE));
}
public ChangeCorrectionProposal(String name, Change change, int relevance, Image image) {
fName= name;
fChange= change;
fRelevance= relevance;
fImage= image;
}
/*
* @see ICompletionProposal#apply(IDocument)
*/
public void apply(IDocument document) {
Change change= null;
try {
change= getChange();
if (change != null) {
ChangeContext context= new ChangeContext(new AbortChangeExceptionHandler());
change.aboutToPerform(context, new NullProgressMonitor());
change.perform(context, new NullProgressMonitor());
}
} catch (ChangeAbortException e) {
JavaPlugin.log(e);
} catch(CoreException e) {
JavaPlugin.log(e);
} finally {
if (change != null) {
change.performed();
}
}
}
/*
* @see ICompletionProposal#getAdditionalProposalInfo()
*/
public String getAdditionalProposalInfo() {
StringBuffer buf= new StringBuffer();
buf.append("<p>"); //$NON-NLS-1$
try {
Change change= getChange();
if (change != null) {
buf.append(change.getName());
} else {
return null;
}
} catch (CoreException e) {
JavaPlugin.log(e);
buf.append(getDisplayString());
}
buf.append("</p>"); //$NON-NLS-1$
return buf.toString();
}
/*
* @see ICompletionProposal#getContextInformation()
*/
public IContextInformation getContextInformation() {
return null;
}
/*
* @see ICompletionProposal#getDisplayString()
*/
public String getDisplayString() {
return fName;
}
/*
* @see ICompletionProposal#getImage()
*/
public Image getImage() {
return fImage;
}
/*
* @see ICompletionProposal#getSelection(IDocument)
*/
public Point getSelection(IDocument document) {
return null;
}
/**
* Sets the proposal's image.
*
* @param image the desired image. Can be <code>null</code>
*/
public void setImage(Image image) {
fImage= image;
}
/**
* Gets the change element.
* @return Returns a Change
*/
protected Change getChange() throws CoreException {
return fChange;
}
/**
* Sets the change element.
* @param change the change
*/
protected void setChange(Change change) throws CoreException {
fChange= change;
}
/**
* Sets the display name.
* @param name The name to set
*/
public void setDisplayName(String name) {
fName= name;
}
/**
* Gets the relevance.
* @return Returns an int
*/
public int getRelevance() {
return fRelevance;
}
/**
* Sets the relevance.
* @param relevance The relevance to set
*/
public void setRelevance(int relevance) {
fRelevance= relevance;
}
}
|
35,526 |
Bug 35526 Error not surfaced on failed quick fix [quick fix]
|
Build: 2.1 RC3a 1) Create a java file, A.java: public class A { } 2) In the java editor, change the class name to "Com1". 3) The word "Com1" will be underlined because it doesn't match the compilation unit name. Select the name and invoke quick fix. 4) Choose the quick fix option, "Rename the compilation unit to Com1.java" -> Nothing happens. The log file contains several stack traces Expectation: The error should be reported to the user, not to the log (since it's a user error, not a program failure).
|
resolved fixed
|
2be3e04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-07T14:28:07Z | 2003-03-21T20:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.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.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.ui.actions.OrganizeImportsAction;
import org.eclipse.jdt.ui.text.java.*;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.ASTRewrite;
import org.eclipse.jdt.internal.corext.refactoring.CompositeChange;
import org.eclipse.jdt.internal.corext.refactoring.changes.CreatePackageChange;
import org.eclipse.jdt.internal.corext.refactoring.changes.MoveCompilationUnitChange;
import org.eclipse.jdt.internal.corext.refactoring.changes.RenameCompilationUnitChange;
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.javaeditor.JavaEditor;
public class ReorgCorrectionsSubProcessor {
public static void getWrongTypeNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length == 2) {
ICompilationUnit cu= context.getCompilationUnit();
boolean isLinked= JavaModelUtil.toOriginal(cu).getResource().isLinked();
// rename type
proposals.add(new CorrectMainTypeNameProposal(cu, args[1], 5));
String newCUName= args[1] + ".java"; //$NON-NLS-1$
ICompilationUnit newCU= ((IPackageFragment) (cu.getParent())).getCompilationUnit(newCUName);
if (!newCU.exists() && !isLinked) {
RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName);
// rename cu
String label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.renamecu.description", newCUName); //$NON-NLS-1$
proposals.add(new ChangeCorrectionProposal(label, change, 6, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME)));
}
}
}
public static void getWrongPackageDeclNameProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
String[] args= problem.getProblemArguments();
if (args.length == 1) {
ICompilationUnit cu= context.getCompilationUnit();
boolean isLinked= JavaModelUtil.toOriginal(cu).getResource().isLinked();
// correct pack decl
proposals.add(new CorrectPackageDeclarationProposal(cu, problem, 5));
// move to pack
IPackageDeclaration[] packDecls= cu.getPackageDeclarations();
String newPackName= packDecls.length > 0 ? packDecls[0].getElementName() : ""; //$NON-NLS-1$
IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(cu);
IPackageFragment newPack= root.getPackageFragment(newPackName);
ICompilationUnit newCU= newPack.getCompilationUnit(cu.getElementName());
if (!newCU.exists() && !isLinked) {
String label;
if (newPack.isDefaultPackage()) {
label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.movecu.default.description", cu.getElementName()); //$NON-NLS-1$
} else {
label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.movecu.description", new Object[] { cu.getElementName(), newPack.getElementName() }); //$NON-NLS-1$
}
CompositeChange composite= new CompositeChange(label);
composite.add(new CreatePackageChange(newPack));
composite.add(new MoveCompilationUnitChange(cu, newPack));
proposals.add(new ChangeCorrectionProposal(label, composite, 6, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_MOVE)));
}
}
}
public static void removeImportStatementProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());
if (selectedNode != null) {
ASTNode node= ASTNodes.getParent(selectedNode, ASTNode.IMPORT_DECLARATION);
if (node instanceof ImportDeclaration) {
ASTRewrite rewrite= new ASTRewrite(node.getParent());
rewrite.markAsRemoved(node);
String label= CorrectionMessages.getString("ReorgCorrectionsSubProcessor.unusedimport.description"); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_DELETE_IMPORT);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image);
proposal.ensureNoModifications();
proposals.add(proposal);
}
}
String name= CorrectionMessages.getString("ReorgCorrectionsSubProcessor.organizeimports.description"); //$NON-NLS-1$
ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5) {
public void apply(IDocument document) {
IEditorInput input= new FileEditorInput((IFile) JavaModelUtil.toOriginal(cu).getResource());
IWorkbenchPage p= JavaPlugin.getActivePage();
if (p == null) {
return;
}
IEditorPart part= p.findEditor(input);
if (part instanceof JavaEditor) {
OrganizeImportsAction action= new OrganizeImportsAction((JavaEditor) part);
action.run(cu);
}
}
};
proposals.add(proposal);
}
}
|
16,287 |
Bug 16287 Feature request: "Search in project" option
|
Hi, I guess a "search in selected project" option in the search dialog would be a good feature. It could also be added to the "References", "Declarations" and "Implementators" popup menu.
|
resolved fixed
|
fdeb12c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-08T13:47:33Z | 2002-05-17T18:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPage.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.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.DialogPage;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.IWorkbenchAdapter;
import org.eclipse.search.ui.ISearchPage;
import org.eclipse.search.ui.ISearchPageContainer;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.RowLayouter;
public class JavaSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants {
public static final String EXTENSION_POINT_ID= "org.eclipse.jdt.ui.JavaSearchPage"; //$NON-NLS-1$
// Dialog store id constants
private final static String PAGE_NAME= "JavaSearchPage"; //$NON-NLS-1$
private final static String STORE_CASE_SENSITIVE= PAGE_NAME + "CASE_SENSITIVE"; //$NON-NLS-1$
private static List fgPreviousSearchPatterns= new ArrayList(20);
private SearchPatternData fInitialData;
private IStructuredSelection fStructuredSelection;
private IJavaElement fJavaElement;
private boolean fFirstTime= true;
private IDialogSettings fDialogSettings;
private boolean fIsCaseSensitive;
private Combo fPattern;
private ISearchPageContainer fContainer;
private Button fCaseSensitive;
private Button[] fSearchFor;
private String[] fSearchForText= {
SearchMessages.getString("SearchPage.searchFor.type"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.method"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.package"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.constructor"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.searchFor.field")}; //$NON-NLS-1$
private Button[] fLimitTo;
private String[] fLimitToText= {
SearchMessages.getString("SearchPage.limitTo.declarations"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.implementors"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.references"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.allOccurrences"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.readReferences"), //$NON-NLS-1$
SearchMessages.getString("SearchPage.limitTo.writeReferences")}; //$NON-NLS-1$
private static class SearchPatternData {
int searchFor;
int limitTo;
String pattern;
boolean isCaseSensitive;
IJavaElement javaElement;
int scope;
IWorkingSet[] workingSets;
public SearchPatternData(int s, int l, boolean i, String p, IJavaElement element) {
this(s, l, p, i, element, ISearchPageContainer.WORKSPACE_SCOPE, null);
}
public SearchPatternData(int s, int l, String p, boolean i, IJavaElement element, int scope, IWorkingSet[] workingSets) {
searchFor= s;
limitTo= l;
pattern= p;
isCaseSensitive= i;
javaElement= element;
this.scope= scope;
this.workingSets= workingSets;
}
}
//---- Action Handling ------------------------------------------------
public boolean performAction() {
SearchUI.activateSearchResultView();
SearchPatternData data= getPatternData();
IWorkspace workspace= JavaPlugin.getWorkspace();
// Setup search scope
IJavaSearchScope scope= null;
String scopeDescription= ""; //$NON-NLS-1$
switch (getContainer().getSelectedScope()) {
case ISearchPageContainer.WORKSPACE_SCOPE:
scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$
scope= SearchEngine.createWorkspaceScope();
break;
case ISearchPageContainer.SELECTION_SCOPE:
scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection);
break;
case ISearchPageContainer.WORKING_SET_SCOPE:
IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets();
// should not happen - just to be sure
if (workingSets == null || workingSets.length < 1)
return false;
scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$
scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets());
SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets());
}
JavaSearchResultCollector collector= new JavaSearchResultCollector();
JavaSearchOperation op= null;
if (data.javaElement != null && getPattern().equals(fInitialData.pattern)) {
op= new JavaSearchOperation(workspace, data.javaElement, data.limitTo, scope, scopeDescription, collector);
if (data.limitTo == IJavaSearchConstants.REFERENCES)
SearchUtil.warnIfBinaryConstant(data.javaElement, getShell());
} else {
data.javaElement= null;
op= new JavaSearchOperation(workspace, data.pattern, data.isCaseSensitive, data.searchFor, data.limitTo, scope, scopeDescription, collector);
}
Shell shell= getControl().getShell();
try {
getContainer().getRunnableContext().run(true, true, op);
} catch (InvocationTargetException ex) {
ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$
return false;
} catch (InterruptedException ex) {
return false;
}
return true;
}
private int getLimitTo() {
for (int i= 0; i < fLimitTo.length; i++) {
if (fLimitTo[i].getSelection())
return i;
}
return -1;
}
private void setLimitTo(int searchFor) {
fLimitTo[DECLARATIONS].setEnabled(true);
fLimitTo[IMPLEMENTORS].setEnabled(false);
fLimitTo[REFERENCES].setEnabled(true);
fLimitTo[ALL_OCCURRENCES].setEnabled(true);
fLimitTo[READ_ACCESSES].setEnabled(false);
fLimitTo[WRITE_ACCESSES].setEnabled(false);
if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) {
fLimitTo[IMPLEMENTORS].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) {
fLimitTo[getLimitTo()].setSelection(false);
fLimitTo[REFERENCES].setSelection(true);
}
switch (searchFor) {
case TYPE:
case INTERFACE:
fLimitTo[IMPLEMENTORS].setEnabled(true);
break;
case FIELD:
fLimitTo[READ_ACCESSES].setEnabled(true);
fLimitTo[WRITE_ACCESSES].setEnabled(true);
break;
default :
break;
}
}
private String[] getPreviousSearchPatterns() {
// Search results are not persistent
int patternCount= fgPreviousSearchPatterns.size();
String [] patterns= new String[patternCount];
for (int i= 0; i < patternCount; i++)
patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).pattern;
return patterns;
}
private int getSearchFor() {
for (int i= 0; i < fSearchFor.length; i++) {
if (fSearchFor[i].getSelection())
return i;
}
Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$
return -1;
}
private String getPattern() {
return fPattern.getText();
}
/**
* Return search pattern data and update previous searches.
* An existing entry will be updated.
*/
private SearchPatternData getPatternData() {
String pattern= getPattern();
SearchPatternData match= null;
int i= 0;
int size= fgPreviousSearchPatterns.size();
while (match == null && i < size) {
match= (SearchPatternData) fgPreviousSearchPatterns.get(i);
i++;
if (!pattern.equals(match.pattern))
match= null;
}
if (match == null) {
match= new SearchPatternData(
getSearchFor(),
getLimitTo(),
pattern,
fCaseSensitive.getSelection(),
fJavaElement,
getContainer().getSelectedScope(),
getContainer().getSelectedWorkingSets());
fgPreviousSearchPatterns.add(match);
}
else {
match.searchFor= getSearchFor();
match.limitTo= getLimitTo();
match.isCaseSensitive= fCaseSensitive.getSelection();
match.javaElement= fJavaElement;
match.scope= getContainer().getSelectedScope();
match.workingSets= getContainer().getSelectedWorkingSets();
}
return match;
}
/*
* Implements method from IDialogPage
*/
public void setVisible(boolean visible) {
if (visible && fPattern != null) {
if (fFirstTime) {
fFirstTime= false;
// Set item and text here to prevent page from resizing
fPattern.setItems(getPreviousSearchPatterns());
initSelections();
}
fPattern.setFocus();
getContainer().setPerformActionEnabled(fPattern.getText().length() > 0);
}
super.setVisible(visible);
}
public boolean isValid() {
return true;
}
//---- Widget creation ------------------------------------------------
/**
* Creates the page's content.
*/
public void createControl(Composite parent) {
initializeDialogUnits(parent);
readConfiguration();
GridData gd;
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout(2, false);
layout.horizontalSpacing= 10;
result.setLayout(layout);
result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
RowLayouter layouter= new RowLayouter(layout.numColumns);
gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL;
layouter.setDefaultGridData(gd, 0);
layouter.setDefaultGridData(gd, 1);
layouter.setDefaultSpan();
layouter.perform(createExpression(result));
layouter.perform(createSearchFor(result), createLimitTo(result), -1);
SelectionAdapter javaElementInitializer= new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
if (getSearchFor() == fInitialData.searchFor)
fJavaElement= fInitialData.javaElement;
else
fJavaElement= null;
setLimitTo(getSearchFor());
updateCaseSensitiveCheckbox();
}
};
fSearchFor[TYPE].addSelectionListener(javaElementInitializer);
fSearchFor[METHOD].addSelectionListener(javaElementInitializer);
fSearchFor[FIELD].addSelectionListener(javaElementInitializer);
fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer);
fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer);
setControl(result);
Dialog.applyDialogFont(result);
WorkbenchHelp.setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE);
}
private Control createExpression(Composite parent) {
Composite result= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout(2, false);
result.setLayout(layout);
GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalSpan= 2;
gd.horizontalIndent= 0;
result.setLayoutData(gd);
// Pattern text + info
Label label= new Label(result, SWT.LEFT);
label.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$
gd= new GridData(GridData.BEGINNING);
gd.horizontalSpan= 2;
// gd.horizontalIndent= -gd.horizontalIndent;
label.setLayoutData(gd);
// Pattern combo
fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER);
fPattern.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handlePatternSelected();
}
});
fPattern.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
getContainer().setPerformActionEnabled(getPattern().length() > 0);
updateCaseSensitiveCheckbox();
}
});
gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL);
gd.horizontalIndent= -gd.horizontalIndent;
fPattern.setLayoutData(gd);
// Ignore case checkbox
fCaseSensitive= new Button(result, SWT.CHECK);
fCaseSensitive.setText(SearchMessages.getString("SearchPage.expression.caseSensitive")); //$NON-NLS-1$
gd= new GridData();
fCaseSensitive.setLayoutData(gd);
fCaseSensitive.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fIsCaseSensitive= fCaseSensitive.getSelection();
writeConfiguration();
}
});
return result;
}
private void updateCaseSensitiveCheckbox() {
if (fInitialData != null && getPattern().equals(fInitialData.pattern) && fJavaElement != null) {
fCaseSensitive.setEnabled(false);
fCaseSensitive.setSelection(true);
}
else {
fCaseSensitive.setEnabled(true);
fCaseSensitive.setSelection(fIsCaseSensitive);
}
}
private void handlePatternSelected() {
if (fPattern.getSelectionIndex() < 0)
return;
int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex();
fInitialData= (SearchPatternData) fgPreviousSearchPatterns.get(index);
for (int i= 0; i < fSearchFor.length; i++)
fSearchFor[i].setSelection(false);
for (int i= 0; i < fLimitTo.length; i++)
fLimitTo[i].setSelection(false);
fSearchFor[fInitialData.searchFor].setSelection(true);
setLimitTo(fInitialData.searchFor);
fLimitTo[fInitialData.limitTo].setSelection(true);
fPattern.setText(fInitialData.pattern);
fIsCaseSensitive= fInitialData.isCaseSensitive;
fJavaElement= fInitialData.javaElement;
fCaseSensitive.setEnabled(fJavaElement == null);
fCaseSensitive.setSelection(fInitialData.isCaseSensitive);
if (fInitialData.workingSets != null)
getContainer().setSelectedWorkingSets(fInitialData.workingSets);
else
getContainer().setSelectedScope(fInitialData.scope);
}
private Control createSearchFor(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 3;
result.setLayout(layout);
fSearchFor= new Button[fSearchForText.length];
for (int i= 0; i < fSearchForText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fSearchForText[i]);
fSearchFor[i]= button;
}
// Fill with dummy radio buttons
Button filler= new Button(result, SWT.RADIO);
filler.setVisible(false);
filler= new Button(result, SWT.RADIO);
filler.setVisible(false);
return result;
}
private Control createLimitTo(Composite parent) {
Group result= new Group(parent, SWT.NONE);
result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$
GridLayout layout= new GridLayout();
layout.numColumns= 2;
result.setLayout(layout);
fLimitTo= new Button[fLimitToText.length];
for (int i= 0; i < fLimitToText.length; i++) {
Button button= new Button(result, SWT.RADIO);
button.setText(fLimitToText[i]);
fLimitTo[i]= button;
}
return result;
}
private void initSelections() {
fStructuredSelection= asStructuredSelection();
fInitialData= tryStructuredSelection(fStructuredSelection);
if (fInitialData == null)
fInitialData= trySimpleTextSelection(getContainer().getSelection());
if (fInitialData == null)
fInitialData= getDefaultInitValues();
fJavaElement= fInitialData.javaElement;
fCaseSensitive.setSelection(fInitialData.isCaseSensitive);
fCaseSensitive.setEnabled(fInitialData.javaElement == null);
fSearchFor[fInitialData.searchFor].setSelection(true);
setLimitTo(fInitialData.searchFor);
fLimitTo[fInitialData.limitTo].setSelection(true);
fPattern.setText(fInitialData.pattern);
}
private SearchPatternData tryStructuredSelection(IStructuredSelection selection) {
if (selection == null || selection.size() > 1)
return null;
Object o= selection.getFirstElement();
if (o instanceof IJavaElement) {
return determineInitValuesFrom((IJavaElement)o);
} else if (o instanceof ISearchResultViewEntry) {
IJavaElement element= SearchUtil.getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker());
return determineInitValuesFrom(element);
} else if (o instanceof LogicalPackage) {
LogicalPackage lp= (LogicalPackage)o;
return new SearchPatternData(PACKAGE, REFERENCES, fIsCaseSensitive, lp.getElementName(), null);
} else if (o instanceof IAdaptable) {
IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class);
if (element != null) {
return determineInitValuesFrom(element);
} else {
IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class);
if (adapter != null)
return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, adapter.getLabel(o), null);
}
}
return null;
}
private SearchPatternData determineInitValuesFrom(IJavaElement element) {
if (element == null)
return null;
int searchFor= UNKNOWN;
int limitTo= UNKNOWN;
String pattern= null;
switch (element.getElementType()) {
case IJavaElement.PACKAGE_FRAGMENT:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.PACKAGE_DECLARATION:
searchFor= PACKAGE;
limitTo= REFERENCES;
pattern= element.getElementName();
break;
case IJavaElement.IMPORT_DECLARATION:
pattern= element.getElementName();
IImportDeclaration declaration= (IImportDeclaration)element;
if (declaration.isOnDemand()) {
searchFor= PACKAGE;
int index= pattern.lastIndexOf('.');
pattern= pattern.substring(0, index);
} else {
searchFor= TYPE;
}
limitTo= DECLARATIONS;
break;
case IJavaElement.TYPE:
searchFor= TYPE;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName((IType)element);
break;
case IJavaElement.COMPILATION_UNIT:
ICompilationUnit cu= (ICompilationUnit)element;
String mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$
IType mainType= cu.getType(mainTypeName);
mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType);
try {
mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName);
if (mainType == null) {
// fetch type which is declared first in the file
IType[] types= cu.getTypes();
if (types.length > 0)
mainType= types[0];
else
break;
}
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
searchFor= TYPE;
element= mainType;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName(mainType);
break;
case IJavaElement.CLASS_FILE:
IClassFile cf= (IClassFile)element;
try {
mainType= cf.getType();
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
if (mainType == null)
break;
element= mainType;
searchFor= TYPE;
limitTo= REFERENCES;
pattern= JavaModelUtil.getFullyQualifiedName(mainType);
break;
case IJavaElement.FIELD:
searchFor= FIELD;
limitTo= REFERENCES;
IType type= ((IField)element).getDeclaringType();
StringBuffer buffer= new StringBuffer();
buffer.append(JavaModelUtil.getFullyQualifiedName(type));
buffer.append('.');
buffer.append(element.getElementName());
pattern= buffer.toString();
break;
case IJavaElement.METHOD:
searchFor= METHOD;
try {
IMethod method= (IMethod)element;
if (method.isConstructor())
searchFor= CONSTRUCTOR;
} catch (JavaModelException ex) {
ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$
break;
}
limitTo= REFERENCES;
pattern= PrettySignature.getMethodSignature((IMethod)element);
break;
}
if (searchFor != UNKNOWN && limitTo != UNKNOWN && pattern != null)
return new SearchPatternData(searchFor, limitTo, true, pattern, element);
return null;
}
private SearchPatternData trySimpleTextSelection(ISelection selection) {
SearchPatternData result= null;
if (selection instanceof ITextSelection) {
BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText()));
String text;
try {
text= reader.readLine();
if (text == null)
text= ""; //$NON-NLS-1$
} catch (IOException ex) {
text= ""; //$NON-NLS-1$
}
result= new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, text, null);
}
return result;
}
private SearchPatternData getDefaultInitValues() {
return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, "", null); //$NON-NLS-1$
}
/*
* Implements method from ISearchPage
*/
public void setContainer(ISearchPageContainer container) {
fContainer= container;
}
/**
* Returns the search page's container.
*/
private ISearchPageContainer getContainer() {
return fContainer;
}
/**
* Returns the structured selection from the selection.
*/
private IStructuredSelection asStructuredSelection() {
IWorkbenchWindow wbWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (wbWindow != null) {
IWorkbenchPage page= wbWindow.getActivePage();
if (page != null) {
IWorkbenchPart part= page.getActivePart();
if (part != null)
try {
return SelectionConverter.getStructuredSelection(part);
} catch (JavaModelException ex) {
}
}
}
return StructuredSelection.EMPTY;
}
//--------------- Configuration handling --------------
/**
* Returns the page settings for this Java search page.
*
* @return the page settings to be used
*/
private IDialogSettings getDialogSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
fDialogSettings= settings.getSection(PAGE_NAME);
if (fDialogSettings == null)
fDialogSettings= settings.addNewSection(PAGE_NAME);
return fDialogSettings;
}
/**
* Initializes itself from the stored page settings.
*/
private void readConfiguration() {
IDialogSettings s= getDialogSettings();
fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE);
}
/**
* Stores it current configuration in the dialog store.
*/
private void writeConfiguration() {
IDialogSettings s= getDialogSettings();
s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive);
}
}
|
16,287 |
Bug 16287 Feature request: "Search in project" option
|
Hi, I guess a "search in selected project" option in the search dialog would be a good feature. It could also be added to the "References", "Declarations" and "Implementators" popup menu.
|
resolved fixed
|
fdeb12c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-08T13:47:33Z | 2002-05-17T18:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchScopeFactory.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.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.IWorkingSetSelectionDialog;
import org.eclipse.search.ui.ISearchResultViewEntry;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
public class JavaSearchScopeFactory {
private static JavaSearchScopeFactory fgInstance;
private static IJavaSearchScope EMPTY_SCOPE= SearchEngine.createJavaSearchScope(new IJavaElement[] {});
private JavaSearchScopeFactory() {
}
public static JavaSearchScopeFactory getInstance() {
if (fgInstance == null)
fgInstance= new JavaSearchScopeFactory();
return fgInstance;
}
public IWorkingSet[] queryWorkingSets() throws JavaModelException {
Shell shell= JavaPlugin.getActiveWorkbenchShell();
if (shell == null)
return null;
IWorkingSetSelectionDialog dialog= PlatformUI.getWorkbench().getWorkingSetManager().createWorkingSetSelectionDialog(shell, true);
if (dialog.open() == Window.OK) {
IWorkingSet[] workingSets= dialog.getSelection();
if (workingSets.length > 0)
return workingSets;
}
return null;
}
public IJavaSearchScope createJavaSearchScope(IWorkingSet[] workingSets) {
if (workingSets == null || workingSets.length < 1)
return EMPTY_SCOPE;
Set javaElements= new HashSet(workingSets.length * 10);
for (int i= 0; i < workingSets.length; i++)
addJavaElements(javaElements, workingSets[i]);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(IWorkingSet workingSet) {
Set javaElements= new HashSet(10);
addJavaElements(javaElements, workingSet);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(IResource[] resources) {
if (resources == null)
return EMPTY_SCOPE;
Set javaElements= new HashSet(resources.length);
addJavaElements(javaElements, resources);
return createJavaSearchScope(javaElements);
}
public IJavaSearchScope createJavaSearchScope(ISelection selection) {
if (selection instanceof IStructuredSelection && !selection.isEmpty()) {
Iterator iter= ((IStructuredSelection)selection).iterator();
Set javaElements= new HashSet(((IStructuredSelection)selection).size());
while (iter.hasNext()) {
Object selectedElement= iter.next();
// Unpack search result view entry
if (selectedElement instanceof ISearchResultViewEntry)
selectedElement= ((ISearchResultViewEntry)selectedElement).getGroupByKey();
if (selectedElement instanceof IJavaElement)
addJavaElements(javaElements, (IJavaElement)selectedElement);
else if (selectedElement instanceof IResource)
addJavaElements(javaElements, (IResource)selectedElement);
else if (selectedElement instanceof LogicalPackage)
addJavaElements(javaElements, (LogicalPackage)selectedElement);
else if (selectedElement instanceof IAdaptable) {
IResource resource= (IResource)((IAdaptable)selectedElement).getAdapter(IResource.class);
if (resource != null)
addJavaElements(javaElements, resource);
}
}
return createJavaSearchScope(javaElements);
}
return EMPTY_SCOPE;
}
private IJavaSearchScope createJavaSearchScope(Set javaElements) {
return SearchEngine.createJavaSearchScope((IJavaElement[])javaElements.toArray(new IJavaElement[javaElements.size()]));
}
private void addJavaElements(Set javaElements, IResource[] resources) {
for (int i= 0; i < resources.length; i++)
addJavaElements(javaElements, resources[i]);
}
private void addJavaElements(Set javaElements, IAdaptable resource) {
IJavaElement javaElement= (IJavaElement)resource.getAdapter(IJavaElement.class);
if (javaElement == null)
// not a Java resource
return;
if (javaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
// add other possible package fragments
try {
addJavaElements(javaElements, ((IFolder)resource).members());
} catch (CoreException ex) {
// don't add elements
}
}
addJavaElements(javaElements, javaElement);
}
private void addJavaElements(Set javaElements, IJavaElement javaElement) {
switch (javaElement.getElementType()) {
case IJavaElement.JAVA_PROJECT:
addJavaElements(javaElements, (IJavaProject)javaElement);
break;
default:
javaElements.add(javaElement);
}
}
private void addJavaElements(Set javaElements, IJavaProject javaProject) {
IPackageFragmentRoot[] roots;
try {
roots= javaProject.getPackageFragmentRoots();
} catch (JavaModelException ex) {
return;
}
for (int i= 0; i < roots.length; i++)
if (!roots[i].isExternal())
javaElements.add(roots[i]);
}
private void addJavaElements(Set javaElements, IWorkingSet workingSet) {
if (workingSet == null)
return;
IAdaptable[] elements= workingSet.getElements();
for (int i= 0; i < elements.length; i++) {
if (elements[i] instanceof IJavaElement)
addJavaElements(javaElements, (IJavaElement)elements[i]);
else
addJavaElements(javaElements, elements[i]);
}
}
public void addJavaElements(Set javaElements, LogicalPackage selectedElement) {
IPackageFragment[] packages= selectedElement.getFragments();
for (int i= 0; i < packages.length; i++)
addJavaElements(javaElements, packages[i]);
}
}
|
41,195 |
Bug 41195 ASTRewrite: strange output when deactivating part of edits
|
I20030730++ - create class package p; class A { int field; } - select field -> Encapsulate Field - go to preview page - open tree for A and only select Add Getter Method. ==> observe the output: class A { int field;int getField() { return field; } }
|
resolved fixed
|
9a4552d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T10:33:19Z | 2003-08-06T14:26:40Z |
org.eclipse.jdt.ui/core
| |
41,195 |
Bug 41195 ASTRewrite: strange output when deactivating part of edits
|
I20030730++ - create class package p; class A { int field; } - select field -> Encapsulate Field - go to preview page - open tree for A and only select Add Getter Method. ==> observe the output: class A { int field;int getField() { return field; } }
|
resolved fixed
|
9a4552d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T10:33:19Z | 2003-08-06T14:26:40Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteAnalyzer.java
| |
38,705 |
Bug 38705 wizards should default with current editor selection [code manipulation]
|
Build 20030605 When using open-type wizard, or create class wizard, the initial type name should be using the current user editor selection if any, so as to ease the typing.
|
resolved fixed
|
76015ef
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T12:49:44Z | 2003-06-10T13:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewContainerWizardPage.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 org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
/**
* Wizard page that acts as a base class for wizard pages that create new Java elements.
* The class provides a input field for source folders (called container in this class) and
* API to validate the enter source folder name.
*
* @since 2.0
*/
public abstract class NewContainerWizardPage extends NewElementWizardPage {
/** Id of the container field */
protected static final String CONTAINER= "NewContainerWizardPage.container"; //$NON-NLS-1$
/** The status of the last validation. */
protected IStatus fContainerStatus;
private StringButtonDialogField fContainerDialogField;
/*
* package fragment root corresponding to the input type (can be null)
*/
private IPackageFragmentRoot fCurrRoot;
private IWorkspaceRoot fWorkspaceRoot;
/**
* Create a new <code>NewContainerWizardPage</code>
*
* @param name the wizard page's name
*/
public NewContainerWizardPage(String name) {
super(name);
fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot();
ContainerFieldAdapter adapter= new ContainerFieldAdapter();
fContainerDialogField= new StringButtonDialogField(adapter);
fContainerDialogField.setDialogFieldListener(adapter);
fContainerDialogField.setLabelText(NewWizardMessages.getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$
fContainerDialogField.setButtonLabel(NewWizardMessages.getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$
fContainerStatus= new StatusInfo();
fCurrRoot= null;
}
/**
* Initializes the source folder field with a valid package fragement root.
* The package fragement root is computed from the given Java element.
*
* @param elem the Java element used to compute the initial package
* fragment root used as the source folder
*/
protected void initContainerPage(IJavaElement elem) {
IPackageFragmentRoot initRoot= null;
if (elem != null) {
initRoot= JavaModelUtil.getPackageFragmentRoot(elem);
if (initRoot == null || initRoot.isArchive()) {
IJavaProject jproject= elem.getJavaProject();
if (jproject != null) {
try {
initRoot= null;
if (jproject.exists()) {
IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) {
initRoot= roots[i];
break;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (initRoot == null) {
initRoot= jproject.getPackageFragmentRoot(jproject.getResource());
}
}
}
}
setPackageFragmentRoot(initRoot, true);
}
/**
* Utility method to inspect a selection to find a Java element.
*
* @param selection the selection to be inspected
* @return a Java element to be used as the initial selection, or <code>null</code>,
* if no Java element exists in the given selection
*/
protected IJavaElement getInitialJavaElement(IStructuredSelection selection) {
IJavaElement jelem= null;
if (selection != null && !selection.isEmpty()) {
Object selectedElement= selection.getFirstElement();
if (selectedElement instanceof IAdaptable) {
IAdaptable adaptable= (IAdaptable) selectedElement;
jelem= (IJavaElement) adaptable.getAdapter(IJavaElement.class);
if (jelem == null) {
IResource resource= (IResource) adaptable.getAdapter(IResource.class);
if (resource != null && resource.getType() != IResource.ROOT) {
while (jelem == null && resource.getType() != IResource.PROJECT) {
resource= resource.getParent();
jelem= (IJavaElement) resource.getAdapter(IJavaElement.class);
}
if (jelem == null) {
jelem= JavaCore.create(resource); // java project
}
}
}
}
}
if (jelem == null) {
IWorkbenchPart part= JavaPlugin.getActivePage().getActivePart();
if (part instanceof ContentOutline) {
part= JavaPlugin.getActivePage().getActiveEditor();
}
if (part instanceof IViewPartInputProvider) {
Object elem= ((IViewPartInputProvider)part).getViewPartInput();
if (elem instanceof IJavaElement) {
jelem= (IJavaElement) elem;
}
}
}
if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) {
try {
IJavaProject[] projects= JavaCore.create(getWorkspaceRoot()).getJavaProjects();
if (projects.length == 1) {
jelem= projects[0];
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return jelem;
}
/**
* Returns the recommended maximum width for text fields (in pixels). This
* method requires that createContent has been called before this method is
* call. Subclasses may override to change the maximum width for text
* fields.
*
* @return the recommended maximum width for text fields.
*/
protected int getMaxFieldWidth() {
return convertWidthInCharsToPixels(40);
}
/**
* Creates the necessary controls (label, text field and browse button) to edit
* the source folder location. The method expects that the parent composite
* uses a <code>GridLayout</code> as its layout manager and that the
* grid layout has at least 3 columns.
*
* @param parent the parent composite
* @param nColumns the number of columns to span. This number must be
* greater or equal three
*/
protected void createContainerControls(Composite parent, int nColumns) {
fContainerDialogField.doFillIntoGrid(parent, nColumns);
LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Sets the focus to the source folder's text field.
*/
protected void setFocusOnContainer() {
fContainerDialogField.setFocus();
}
// -------- ContainerFieldAdapter --------
private class ContainerFieldAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
containerChangeControlPressed(field);
}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
containerDialogFieldChanged(field);
}
}
private void containerChangeControlPressed(DialogField field) {
// take the current jproject as init element of the dialog
IPackageFragmentRoot root= getPackageFragmentRoot();
root= chooseSourceContainer(root);
if (root != null) {
setPackageFragmentRoot(root, true);
}
}
private void containerDialogFieldChanged(DialogField field) {
if (field == fContainerDialogField) {
fContainerStatus= containerChanged();
}
// tell all others
handleFieldChanged(CONTAINER);
}
// ----------- validation ----------
/**
* This method is a hook which gets called after the source folder's
* text input field has changed. This default implementation updates
* the model and returns an error status. The underlying model
* is only valid if the returned status is OK.
*
* @return the model's error status
*/
protected IStatus containerChanged() {
StatusInfo status= new StatusInfo();
fCurrRoot= null;
String str= getPackageFragmentRootText();
if (str.length() == 0) {
status.setError(NewWizardMessages.getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$
return status;
}
IPath path= new Path(str);
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
int resType= res.getType();
if (resType == IResource.PROJECT || resType == IResource.FOLDER) {
IProject proj= res.getProject();
if (!proj.isOpen()) {
status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$
return status;
}
IJavaProject jproject= JavaCore.create(proj);
fCurrRoot= jproject.getPackageFragmentRoot(res);
if (res.exists()) {
try {
if (!proj.hasNature(JavaCore.NATURE_ID)) {
if (resType == IResource.PROJECT) {
status.setError(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$
} else {
status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); //$NON-NLS-1$
}
return status;
}
} catch (CoreException e) {
status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$
}
if (!jproject.isOnClasspath(fCurrRoot)) {
status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", str)); //$NON-NLS-1$
}
if (fCurrRoot.isArchive()) {
status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", str)); //$NON-NLS-1$
return status;
}
}
return status;
} else {
status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$
return status;
}
} else {
status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$
return status;
}
}
// -------- update message ----------------
/**
* Hook method that gets called when a field on this page has changed. For this page the
* method gets called when the source folder field changes.
* <p>
* Every sub type is responsible to call this method when a field on its page has changed.
* Subtypes override (extend) the method to add verification when a own field has a
* dependency to an other field. For example the class name input must be verified
* again when the package field changes (check for duplicated class names).
*
* @param fieldName The name of the field that has changed (field id). For the
* source folder the field id is <code>CONTAINER</code>
*/
protected void handleFieldChanged(String fieldName) {
}
// ---- get ----------------
/**
* Returns the workspace root.
*
* @return the workspace root
*/
protected IWorkspaceRoot getWorkspaceRoot() {
return fWorkspaceRoot;
}
/**
* Returns the <code>IPackageFragmentRoot</code> that corresponds to the current
* value of the source folder field.
*
* @return the IPackageFragmentRoot or <code>null</code> if the current source
* folder value is not a valid package fragment root
*
*/
public IPackageFragmentRoot getPackageFragmentRoot() {
return fCurrRoot;
}
/**
* Returns the current text of source folder text field.
*
* @return the text of the source folder text field
*/
public String getPackageFragmentRootText() {
return fContainerDialogField.getText();
}
/**
* Sets the current source folder (model and text field) to the given package
* fragment root.
*
* @param canBeModified if <code>false</code> the source folder field can
* not be changed by the user. If <code>true</code> the field is editable
*/
public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) {
fCurrRoot= root;
String str= (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$
fContainerDialogField.setText(str);
fContainerDialogField.setEnabled(canBeModified);
}
// ------------- choose source container dialog
private IPackageFragmentRoot chooseSourceContainer(IJavaElement initElement) {
Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) {
public boolean isSelectedValid(Object element) {
try {
if (element instanceof IJavaProject) {
IJavaProject jproject= (IJavaProject)element;
IPath path= jproject.getProject().getFullPath();
return (jproject.findPackageFragmentRoot(path) != null);
} else if (element instanceof IPackageFragmentRoot) {
return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
}
return true;
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus()); // just log, no ui in validation
}
return false;
}
};
acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class };
ViewerFilter filter= new TypedViewerFilter(acceptedClasses) {
public boolean select(Viewer viewer, Object parent, Object element) {
if (element instanceof IPackageFragmentRoot) {
try {
return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE);
} catch (JavaModelException e) {
JavaPlugin.log(e.getStatus()); // just log, no ui in validation
return false;
}
}
return super.select(viewer, parent, element);
}
};
StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider);
dialog.setValidator(validator);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(JavaCore.create(fWorkspaceRoot));
dialog.setInitialSelection(initElement);
if (dialog.open() == Window.OK) {
Object element= dialog.getFirstResult();
if (element instanceof IJavaProject) {
IJavaProject jproject= (IJavaProject)element;
return jproject.getPackageFragmentRoot(jproject.getProject());
} else if (element instanceof IPackageFragmentRoot) {
return (IPackageFragmentRoot)element;
}
return null;
}
return null;
}
}
|
38,705 |
Bug 38705 wizards should default with current editor selection [code manipulation]
|
Build 20030605 When using open-type wizard, or create class wizard, the initial type name should be using the current user editor selection if any, so as to ease the typing.
|
resolved fixed
|
76015ef
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T12:49:44Z | 2003-06-10T13:00: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.List;
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.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
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.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.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.Template;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
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.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
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 IImportsStructure fImportsStructure;
/* package */ ImportsManager(IImportsStructure structure) {
fImportsStructure= structure;
}
/* package */ IImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
return fImportsStructure.addImport(qualifiedTypeName);
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= 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;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <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$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <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
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName("", true); //$NON-NLS-1$
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <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);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null));
}
/**
* 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);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeightHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
}
/**
* Creates the controls for the type name field. Expects a <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/ceckbox 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);
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);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* 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 dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons || 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 fragement 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 fragement 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 seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <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) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <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(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <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);
}
// ----------- validation ----------
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <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
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <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$
if (cu.getResource().exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <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 superinterfaces 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;
ImportsStructure imports;
int indent= 0;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
// create a working copy with a new owner
createdWorkingCopy= parentCU.getWorkingCopy(null);
imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(pack.getElementName(), getTypeName());
String typeContent= constructTypeStub(new ImportsManager(imports), lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsStructure(parentCU, prefOrder, threshold, true);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
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(new ImportsManager(imports), lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
boolean needsSave= !imports.getCompilationUnit().isWorkingCopy();
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
ICompilationUnit cu= createdType.getCompilationUnit();
synchronized(cu) {
cu.reconcile();
}
createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1));
// add imports
imports.create(needsSave, new SubProgressMonitor(monitor, 1));
synchronized(cu) {
cu.reconcile();
}
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter);
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commit(false, new SubProgressMonitor(monitor, 1));
} else {
if (needsSave) {
buf.save(null, false);
}
monitor.worked(1);
}
if (createdWorkingCopy != null) {
fCreatedType= (IType) createdType.getPrimaryElement();
} else {
fCreatedType= createdType;
}
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.destroy();
}
monitor.done();
}
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
* @since 2.1
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
String typeComment= getTypeComment(cu, lineDelimiter);
IPackageFragment pack= (IPackageFragment) cu.getParent();
String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter);
if (content != null) {
CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray());
if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) {
return content;
}
}
StringBuffer buf= new StringBuffer();
if (!pack.isDefaultPackage()) {
buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$
}
buf.append(lineDelimiter).append(lineDelimiter);
if (typeComment != null) {
buf.append(typeComment).append(lineDelimiter);
}
buf.append(typeContent);
return buf.toString();
}
/**
* Returns the created type. The method only returns a valid type
* after <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();
}
/**
* @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
//deprecated
}
/**
* Hook method that gets called from <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 formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </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 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
*/
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 evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor)
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor);
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <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 neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= null;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
hierarchy= type.newSupertypeHierarchy(monitor);
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure());
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
if (hierarchy == null) {
hierarchy= type.newSupertypeHierarchy(monitor);
}
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
40,452 |
Bug 40452 refactor rename throws StringIndexOutOfBounds exception
|
------------------A.java--------------------- package a; public class A { public static void method2() //<--- refactor rename this method { } } ---------------------------------------------- -----------------------B.java----------------- package b; import a.A; public class B { I i = new I() { public void method() { A.method2(); } }; } interface I { void method(); } -------------------------------------------------- If you have the above two files and refactor rename "method2" to something you get the following: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(Unknown Source) at org.eclipse.jface.operation.ModalContext.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (Unknown Source) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Unknown Source) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Unknown Source) 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:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.jface.window.Window.runEventLoop(Unknown Source) at org.eclipse.jface.window.Window.open(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.reorg.RenameRefactoringAction.run (Unknown Source) at org.eclipse.jdt.ui.refactoring.RenameSupport.openDialog(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameJavaElementAction.run (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameJavaElementAction.run (Unknown Source) at org.eclipse.jdt.ui.actions.RenameAction.run(Unknown Source) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(Unknown Source) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(Unknown Source) at org.eclipse.jface.action.Action.runWithEvent(Unknown Source) at org.eclipse.ui.internal.commands.old.ActionHandler.execute(Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.pressed (Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.access$1 (Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager$7.widgetSelected (Unknown Source) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent(Unknown Source) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Unknown Source) at org.eclipse.ui.internal.Workbench.run(Unknown Source) at org.eclipse.core.internal.boot.InternalBootLoader.run(Unknown Source) at org.eclipse.core.boot.BootLoader.run(Unknown Source) 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(Unknown Source) at org.eclipse.core.launcher.Main.run(Unknown Source) at org.eclipse.core.launcher.Main.main(Unknown Source) Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -7 at java.lang.String.substring(String.java:1444) at java.lang.String.substring(String.java:1411) at org.eclipse.jdt.internal.corext.refactoring.rename.UpdateMethodReferenceEdit.con nect(Unknown Source) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.executeConnect (Unknown Source) at org.eclipse.jdt.internal.corext.textmanipulation.AutoOrganizingTextEdit.executeC onnect(Unknown Source) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor.add (Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.changes.TextChange.addTextEdits (Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.changes.TextChange.getPreviewTextBuf fer(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameAnalyzeUtil.getNewWorki ngCopies(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor.getNewO ccurrences(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor.analyze RenameChanges(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor.checkIn put(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameNonVirtualMethodProcess or.checkInput(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameRefactoring.checkInput (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(Unknown Source) ... 46 more
|
resolved fixed
|
d1b1705
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T13:24:39Z | 2003-07-18T09:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
40,452 |
Bug 40452 refactor rename throws StringIndexOutOfBounds exception
|
------------------A.java--------------------- package a; public class A { public static void method2() //<--- refactor rename this method { } } ---------------------------------------------- -----------------------B.java----------------- package b; import a.A; public class B { I i = new I() { public void method() { A.method2(); } }; } interface I { void method(); } -------------------------------------------------- If you have the above two files and refactor rename "method2" to something you get the following: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(Unknown Source) at org.eclipse.jface.operation.ModalContext.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactorin g(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (Unknown Source) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Unknown Source) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Unknown Source) 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:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.jface.window.Window.runEventLoop(Unknown Source) at org.eclipse.jface.window.Window.open(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.reorg.RenameRefactoringAction.run (Unknown Source) at org.eclipse.jdt.ui.refactoring.RenameSupport.openDialog(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameJavaElementAction.run (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameJavaElementAction.run (Unknown Source) at org.eclipse.jdt.ui.actions.RenameAction.run(Unknown Source) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(Unknown Source) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(Unknown Source) at org.eclipse.jface.action.Action.runWithEvent(Unknown Source) at org.eclipse.ui.internal.commands.old.ActionHandler.execute(Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.pressed (Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager.access$1 (Unknown Source) at org.eclipse.ui.internal.commands.old.ContextAndHandlerManager$7.widgetSelected (Unknown Source) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent(Unknown Source) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:848) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2188) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1878) at org.eclipse.ui.internal.Workbench.runEventLoop(Unknown Source) at org.eclipse.ui.internal.Workbench.run(Unknown Source) at org.eclipse.core.internal.boot.InternalBootLoader.run(Unknown Source) at org.eclipse.core.boot.BootLoader.run(Unknown Source) 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(Unknown Source) at org.eclipse.core.launcher.Main.run(Unknown Source) at org.eclipse.core.launcher.Main.main(Unknown Source) Caused by: java.lang.StringIndexOutOfBoundsException: String index out of range: -7 at java.lang.String.substring(String.java:1444) at java.lang.String.substring(String.java:1411) at org.eclipse.jdt.internal.corext.refactoring.rename.UpdateMethodReferenceEdit.con nect(Unknown Source) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.executeConnect (Unknown Source) at org.eclipse.jdt.internal.corext.textmanipulation.AutoOrganizingTextEdit.executeC onnect(Unknown Source) at org.eclipse.jdt.internal.corext.textmanipulation.TextBufferEditor.add (Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.changes.TextChange.addTextEdits (Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.changes.TextChange.getPreviewTextBuf fer(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameAnalyzeUtil.getNewWorki ngCopies(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor.getNewO ccurrences(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor.analyze RenameChanges(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameMethodProcessor.checkIn put(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameNonVirtualMethodProcess or.checkInput(Unknown Source) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameRefactoring.checkInput (Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run(Unknown Source) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run(Unknown Source) ... 46 more
|
resolved fixed
|
d1b1705
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T13:24:39Z | 2003-07-18T09:20:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/RenameStaticMethodTests.java
| |
40,706 |
Bug 40706 Error in the log & error dialog [refactoring] [ccp]
|
build I20030723 I selected two debug projects in the package explorer, and this error appeared - could not reproduce. !ENTRY org.eclipse.jface 4 2 Jul 24, 2003 07:46:55.415 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:121) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory$FilesFolder sAndCusReorgPolicy.verifyDestination(ReorgPolicyFactory.java:321) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory$ReorgPolicy .setDestination(ReorgPolicyFactory.java:232) at org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring.setDestination (CopyRefactoring.java:82) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.create (ReorgCopyStarter.java:49) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResource Paster.canPasteOn(PasteAction.java:349) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.canOperateOn (PasteAction.java:98) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.selectionChanged (PasteAction.java:83) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged (SelectionDispatchAction.java:184) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.selectionChanged (SelectionDispatchAction.java:179) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java) at org.eclipse.core.runtime.Platform.run(Platform.java) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:652) at org.eclipse.jface.viewers.StructuredViewer$4.widgetSelected (StructuredViewer.java:676) at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent (OpenStrategy.java:178) at org.eclipse.jface.util.OpenStrategy.access$3(OpenStrategy.java:173) at org.eclipse.jface.util.OpenStrategy$1.handleEvent (OpenStrategy.java:308) 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:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
1f16853
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T14:34:38Z | 2003-07-24T12:33:20Z |
org.eclipse.jdt.ui/core
| |
40,706 |
Bug 40706 Error in the log & error dialog [refactoring] [ccp]
|
build I20030723 I selected two debug projects in the package explorer, and this error appeared - could not reproduce. !ENTRY org.eclipse.jface 4 2 Jul 24, 2003 07:46:55.415 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at java.lang.Throwable.<init>(Throwable.java) at java.lang.Throwable.<init>(Throwable.java) at org.eclipse.jdt.internal.corext.Assert$AssertionFailedException.<init> (Assert.java:55) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:136) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:121) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory$FilesFolder sAndCusReorgPolicy.verifyDestination(ReorgPolicyFactory.java:321) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory$ReorgPolicy .setDestination(ReorgPolicyFactory.java:232) at org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring.setDestination (CopyRefactoring.java:82) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.create (ReorgCopyStarter.java:49) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResource Paster.canPasteOn(PasteAction.java:349) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.canOperateOn (PasteAction.java:98) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.selectionChanged (PasteAction.java:83) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchSelectionChanged (SelectionDispatchAction.java:184) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.selectionChanged (SelectionDispatchAction.java:179) at org.eclipse.jface.viewers.Viewer$2.run(Viewer.java:159) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java) at org.eclipse.core.runtime.Platform.run(Platform.java) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged (Viewer.java:157) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1282) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:652) at org.eclipse.jface.viewers.StructuredViewer$4.widgetSelected (StructuredViewer.java:676) at org.eclipse.jface.util.OpenStrategy.fireSelectionEvent (OpenStrategy.java:178) at org.eclipse.jface.util.OpenStrategy.access$3(OpenStrategy.java:173) at org.eclipse.jface.util.OpenStrategy$1.handleEvent (OpenStrategy.java:308) 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:1680) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1663) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.AccessibleObject.invokeL(AccessibleObject.java:207) at java.lang.reflect.Method.invoke(Method.java:271) at org.eclipse.core.launcher.Main.basicRun(Main.java:291) at org.eclipse.core.launcher.Main.run(Main.java:747) at org.eclipse.core.launcher.Main.main(Main.java:583)
|
resolved fixed
|
1f16853
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T14:34:38Z | 2003-07-24T12:33:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgPolicyFactory.java
| |
39,008 |
Bug 39008 [refactoring] change method signature annoying defaults
|
When adding a new parameter in Change Method signature refactoring you get the following defaults: int arg0 0 These default values do not make sense and are not helpful. We should not suggest them, but rather leave them empty.
|
resolved fixed
|
7f80a4b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T17:05:18Z | 2003-06-17T11:40:00Z |
org.eclipse.jdt.ui/core
| |
39,008 |
Bug 39008 [refactoring] change method signature annoying defaults
|
When adding a new parameter in Change Method signature refactoring you get the following defaults: int arg0 0 These default values do not make sense and are not helpful. We should not suggest them, but rather leave them empty.
|
resolved fixed
|
7f80a4b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T17:05:18Z | 2003-06-17T11:40:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
39,008 |
Bug 39008 [refactoring] change method signature annoying defaults
|
When adding a new parameter in Change Method signature refactoring you get the following defaults: int arg0 0 These default values do not make sense and are not helpful. We should not suggest them, but rather leave them empty.
|
resolved fixed
|
7f80a4b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T17:05:18Z | 2003-06-17T11:40:00Z |
org.eclipse.jdt.ui/ui
| |
39,008 |
Bug 39008 [refactoring] change method signature annoying defaults
|
When adding a new parameter in Change Method signature refactoring you get the following defaults: int arg0 0 These default values do not make sense and are not helpful. We should not suggest them, but rather leave them empty.
|
resolved fixed
|
7f80a4b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T17:05:18Z | 2003-06-17T11:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
39,008 |
Bug 39008 [refactoring] change method signature annoying defaults
|
When adding a new parameter in Change Method signature refactoring you get the following defaults: int arg0 0 These default values do not make sense and are not helpful. We should not suggest them, but rather leave them empty.
|
resolved fixed
|
7f80a4b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T17:05:18Z | 2003-06-17T11:40:00Z |
org.eclipse.jdt.ui/ui
| |
39,008 |
Bug 39008 [refactoring] change method signature annoying defaults
|
When adding a new parameter in Change Method signature refactoring you get the following defaults: int arg0 0 These default values do not make sense and are not helpful. We should not suggest them, but rather leave them empty.
|
resolved fixed
|
7f80a4b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T17:05:18Z | 2003-06-17T11:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeSignatureWizard.java
| |
40,788 |
Bug 40788 [plan item] Configurable Next/Previous actions
|
Toolbar drop down, or editor specific control. Needs to be coordinated with Platform UI.
|
resolved fixed
|
508186a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T18:05:20Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.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;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.core.DefaultWorkingCopyOwner;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CustomBufferFactory;
import org.eclipse.jdt.internal.ui.javaeditor.WorkingCopyManager;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
/** temporarily */
public static final boolean USE_WORKING_COPY_OWNERS= false;
private static JavaPlugin fgJavaPlugin;
private IWorkingCopyManager fWorkingCopyManager;
private CompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private JavaElementAdapterFactory fJavaElementAdapterFactory;
private MarkerAdapterFactory fMarkerAdapterFactory;
private EditorInputAdapterFactory fEditorInputAdapterFactory;
private ResourceAdapterFactory fResourceAdapterFactory;
private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IPropertyChangeListener fFontPropertyChangeListener;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
return getActiveWorkbenchWindow().getShell();
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getDirtyEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart ep= editors[z];
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
/**
* Returns an array of all instanciated editors.
*/
public static IEditorPart[] getInstanciatedEditors() {
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int windowIndex= 0; windowIndex < windows.length; windowIndex++) {
IWorkbenchPage[] pages= windows[windowIndex].getPages();
for (int pageIndex= 0; pageIndex < pages.length; pageIndex++) {
IEditorReference[] references= pages[pageIndex].getEditorReferences();
for (int refIndex= 0; refIndex < references.length; refIndex++) {
IEditorPart editor= references[refIndex].getEditor(false);
if (editor != null)
result.add(editor);
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().internalGetImageDescriptorRegistry();
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() throws CoreException {
super.startup();
registerAdapters();
if (USE_WORKING_COPY_OWNERS)
DefaultWorkingCopyOwner.PRIMARY.factory= new CustomBufferFactory();
/*
* Backward compatibility: propagate the Java editor font from a
* pre-2.1 plug-in to the Platform UI's preference store to preserve
* the Java editor font from a pre-2.1 workspace. This is done only
* once.
*/
String fontPropagatedKey= "fontPropagated"; //$NON-NLS-1$
if (getPreferenceStore().contains(JFaceResources.TEXT_FONT) && !getPreferenceStore().isDefault(JFaceResources.TEXT_FONT)) {
if (!getPreferenceStore().getBoolean(fontPropagatedKey))
PreferenceConverter.setValue(PlatformUI.getWorkbench().getPreferenceStore(), PreferenceConstants.EDITOR_TEXT_FONT, PreferenceConverter.getFontDataArray(getPreferenceStore(), JFaceResources.TEXT_FONT));
}
getPreferenceStore().setValue(fontPropagatedKey, true);
/*
* Backward compatibility: set the Java editor font in this plug-in's
* preference store to let older versions access it. Since 2.1 the
* Java editor font is managed by the workbench font preference page.
*/
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.putValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFontRegistry().getFontData(PreferenceConstants.EDITOR_TEXT_FONT));
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fWorkingCopyManager != null) {
fWorkingCopyManager.shutdown();
fWorkingCopyManager= null;
}
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
if (fWorkingCopyManager == null) {
CompilationUnitDocumentProvider provider= getCompilationUnitDocumentProvider();
fWorkingCopyManager= new WorkingCopyManager(provider);
}
return fWorkingCopyManager;
}
public synchronized ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore(), JavaCore.getPlugin().getPluginPreferences());
return fJavaTextTools;
}
public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
if (fMembersOrderPreferenceCache == null)
fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
return fMembersOrderPreferenceCache;
}
/**
* Returns all Java editor text hovers contributed to the workbench.
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
if (fJavaEditorTextHoverDescriptors == null)
fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
return fJavaEditorTextHoverDescriptors;
}
/**
* Resets the Java editor text hovers contributed to the workbench.
* <p>
* This will force a rebuild of the descriptors the next time
* a client asks for them.
* </p>
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public void resetJavaEditorTextHoverDescriptors() {
fJavaEditorTextHoverDescriptors= null;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
PreferenceConstants.initializeDefaultValues(store);
}
private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
if (fImageDescriptorRegistry == null)
fImageDescriptorRegistry= new ImageDescriptorRegistry();
return fImageDescriptorRegistry;
}
private void registerAdapters() {
fJavaElementAdapterFactory= new JavaElementAdapterFactory();
fMarkerAdapterFactory= new MarkerAdapterFactory();
fEditorInputAdapterFactory= new EditorInputAdapterFactory();
fResourceAdapterFactory= new ResourceAdapterFactory();
fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
manager.registerAdapters(fLogicalPackageAdapterFactory, LogicalPackage.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
manager.unregisterAdapters(fLogicalPackageAdapterFactory);
}
}
|
40,788 |
Bug 40788 [plan item] Configurable Next/Previous actions
|
Toolbar drop down, or editor specific control. Needs to be coordinated with Platform UI.
|
resolved fixed
|
508186a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T18:05:20Z | 2003-07-25T16:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/GotoAnnotationAction.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 org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
public class GotoAnnotationAction extends TextEditorAction {
private boolean fForward;
public GotoAnnotationAction(String prefix, boolean forward) {
super(JavaEditorMessages.getResourceBundle(), prefix, null);
fForward= forward;
if (forward)
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GOTO_NEXT_ERROR_ACTION);
else
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GOTO_PREVIOUS_ERROR_ACTION);
}
public void run() {
JavaEditor e= (JavaEditor) getTextEditor();
e.gotoError(fForward);
}
public void setEditor(ITextEditor editor) {
if (editor instanceof JavaEditor)
super.setEditor(editor);
update();
}
public void update() {
setEnabled(getTextEditor() instanceof JavaEditor);
}
}
|
40,788 |
Bug 40788 [plan item] Configurable Next/Previous actions
|
Toolbar drop down, or editor specific control. Needs to be coordinated with Platform UI.
|
resolved fixed
|
508186a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-08-11T18:05:20Z | 2003-07-25T16: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.util.ArrayList;
import java.util.Iterator;
import java.util.List;
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.IStatus;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
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.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.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITextViewerExtension4;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.IInformationProviderExtension2;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.ChangeRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IAnnotationModelExtension;
import org.eclipse.jface.text.source.IChangeRulerColumn;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberChangeRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
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.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IPartService;
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.editors.quickdiff.IQuickDiffProviderImplementation;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
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.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.ContentOutline;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.ui.internal.editors.quickdiff.DocumentLineDiffer;
import org.eclipse.ui.internal.editors.quickdiff.ReferenceProviderDescriptor;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
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.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.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.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaChangeHover;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.IJavaPartitions;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor 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
*/
public void uninstall(ISelectionProvider selectionProvider) {
if (selectionProvider == null)
return;
if (selectionProvider instanceof IPostSelectionProvider) {
IPostSelectionProvider provider= (IPostSelectionProvider) selectionProvider;
provider.removePostSelectionChangedListener(this);
} else {
selectionProvider.removeSelectionChangedListener(this);
}
}
}
/**
* Updates the Java outline page selection and this editor's range indicator.
*
* @since 3.0
*/
private class EditorSelectionChangedListener extends AbstractSelectionChangedListener {
/*
* @see org.eclipse.jface.viewers.ISelectionChangedListener#selectionChanged(org.eclipse.jface.viewers.SelectionChangedEvent)
*/
public void selectionChanged(SelectionChangedEvent event) {
selectionChanged();
}
public void selectionChanged() {
ISourceReference element= computeHighlightRangeSourceReference();
synchronizeOutlinePage(element);
setSelection(element, false);
}
}
/**
* Updates the selection in the editor's widget with the selection of the outline page.
*/
class OutlineSelectionChangedListener extends AbstractSelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
}
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** 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);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
if (fKeyModifierMask == -1) {
// Fallback to stored state mask
fKeyModifierMask= getPreferenceStore().getInt(BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK);
}
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= EditorUtility.findLocalizedModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
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 && !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();
}
});
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
}
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
/**
* Information provider used to present the information.
*
* @since 3.0
*/
class InformationProvider implements IInformationProvider, IInformationProviderExtension2 {
private IRegion fHoverRegion;
private String fHoverInfo;
private IInformationControlCreator fControlCreator;
InformationProvider(IRegion hoverRegion, String hoverInfo, IInformationControlCreator controlCreator) {
fHoverRegion= hoverRegion;
fHoverInfo= hoverInfo;
fControlCreator= controlCreator;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int invocationOffset) {
return fHoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return fHoverInfo;
}
/*
* @see org.eclipse.jface.text.information.IInformationProviderExtension2#getInformationPresenterControlCreator()
* @since 3.0
*/
public IInformationControlCreator getInformationPresenterControlCreator() {
return fControlCreator;
}
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (sourceViewer instanceof ITextViewerExtension4) {
ITextViewerExtension4 extension4= (ITextViewerExtension4) sourceViewer;
extension4.moveFocusToWidgetToken();
}
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
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
IInformationControlCreator controlCreator= null;
if (textHover instanceof IInformationProviderExtension2)
controlCreator= ((IInformationProviderExtension2)textHover).getInformationPresenterControlCreator();
IInformationProvider informationProvider= new InformationProvider(hoverRegion, hoverInfo, controlCreator);
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
}
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
}
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
}
/** Preference key for showing the line number ruler */
protected final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
protected final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** 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 highlighting current line */
protected final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
protected final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
protected final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
protected final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
protected final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for error indication */
protected final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
protected final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
protected final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
protected final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
protected final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
protected final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
protected final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
protected final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
protected final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
protected final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
protected final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
protected final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for shwoing the overview ruler */
protected final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
protected final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
/**
* Preference key for key modifier mask of browser like links.
* The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code>
* cannot be resolved to valid SWT modifier bits.
*
* @since 2.1.1
*/
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/**
* The editor selection changed listener.
*
* @since 3.0
*/
private EditorSelectionChangedListener fEditorSelectionChangedListener;
/** The selection changed listener */
protected AbstractSelectionChangedListener fOutlineSelectionChangedListener= new OutlineSelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/**
* The change ruler column.
* @since 3.0
*/
private IChangeRulerColumn fChangeRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** The annotation access */
protected IAnnotationAccess fAnnotationAccess= new AnnotationAccess();
/** The source viewer decoration support */
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/** The overview ruler */
protected OverviewRuler fOverviewRuler;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Whether quick diff information is displayed, either on a change ruler or the line number ruler.
* @since 3.0
*/
private boolean fIsChangeInformationShown;
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @return the most narrow java element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setKeyBindingScopes(new String[] { "org.eclipse.jdt.ui.javaEditorScope" }); //$NON-NLS-1$
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISharedTextColors sharedColors= JavaPlugin.getDefault().getJavaTextTools().getColorManager();
fOverviewRuler= new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.WARNING);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.ERROR);
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
configureSourceViewerDecorationSupport();
return viewer;
}
public final ISourceViewer getViewer() {
return getSourceViewer();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
fOutlineSelectionChangedListener.install(page);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the given element
* position in the editor.
*
* @param element the java element to select
*/
protected void synchronizeOutlinePage(ISourceReference element) {
if (fOutlinePage != null && element != null && !isJavaOutlinePageActive()) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
synchronizeOutlinePage(computeHighlightRangeSourceReference());
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
if (required == IShowInTargetList.class) {
return new IShowInTargetList() {
public String[] getShowInTargetIds() {
return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_OUTLINE, IPageLayout.ID_RES_NAV };
}
};
}
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (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= 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 IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
if (content != null) {
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
}
if (offset > -1 && length > 0) {
try {
textWidget.setRedraw(false);
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
} finally {
textWidget.setRedraw(true);
}
markInNavigationHistory();
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
}
} else if (moveCursor) {
resetHighlightRange();
markInNavigationHistory();
}
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select(reference);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
}
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
setSelection(reference, !isActivePart());
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlineSelectionChangedListener.uninstall(fOutlinePage);
fOutlinePage.select((ISourceReference) element);
fOutlineSelectionChangedListener.install(fOutlinePage);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchPart part= getActivePart();
return part != null && part.equals(this);
}
private boolean isJavaOutlinePageActive() {
IWorkbenchPart part= getActivePart();
return part instanceof ContentOutline && ((ContentOutline)part).getCurrentPage() == fOutlinePage;
}
private IWorkbenchPart getActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part;
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= 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();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
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});
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);
}
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 (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null
&& (LINE_NUMBER_COLOR.equals(property)
|| PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property)
|| PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (PreferenceConstants.QUICK_DIFF_CHANGED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_ADDED_COLOR.equals(property)
|| PreferenceConstants.QUICK_DIFF_DELETED_COLOR.equals(property)) {
if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
initializeChangeRulerColumn((IChangeRulerColumn) fLineNumberRulerColumn);
else if (fChangeRulerColumn != null)
initializeChangeRulerColumn(fChangeRulerColumn);
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
if (PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE.equals(property)) {
if ((event.getNewValue() instanceof Boolean) && ((Boolean)event.getNewValue()).booleanValue()) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
fEditorSelectionChangedListener.selectionChanged();
} else {
fEditorSelectionChangedListener.uninstall(getSelectionProvider());
fEditorSelectionChangedListener= null;
}
return;
}
if (PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE.equals(property)) {
if (event.getNewValue() instanceof Boolean) {
Boolean disable= (Boolean) event.getNewValue();
configureInsertMode(OVERWRITE, !disable.booleanValue());
}
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#showChangeInformation(boolean)
*/
public void showChangeInformation(boolean show) {
if (show == fIsChangeInformationShown)
return;
if (fIsChangeInformationShown) {
uninstallChangeRulerModel();
showChangeRuler(false); // hide change ruler if its displayed - if the line number ruler is showing, only the colors get removed by deinstalling the model
} else {
ensureChangeInfoCanBeDisplayed(); // can be replaced w/ showChangeRuler(false) once the old line number ruler is gone
installChangeRulerModel();
}
fIsChangeInformationShown= show;
}
/**
* Installs the differ annotation model with the current quick diff display.
* @since R3.0
*/
private void installChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(getOrCreateDiffer());
}
/**
* Uninstalls the differ annotation model from the current quick diff display.
*
* @since R3.0
*/
private void uninstallChangeRulerModel() {
IChangeRulerColumn column= getChangeColumn();
if (column != null)
column.setModel(null);
}
/**
* Ensures that either the line number display is a <code>LineNumberChangeRuler</code> or
* a separate change ruler gets displayed.
*
* @since R3.0
*/
private void ensureChangeInfoCanBeDisplayed() {
if (isLineNumberRulerVisible()) {
if (!(fLineNumberRulerColumn instanceof IChangeRulerColumn)) {
hideLineNumberRuler();
// HACK: set state already so a change ruler is created. Not needed once always a change line number bar gets installed
fIsChangeInformationShown= true;
showLineNumberRuler();
}
} else
showChangeRuler(true);
}
/*
* @see org.eclipse.ui.texteditor.ITextEditorExtension3#isChangeInformationShowing()
*/
public boolean isChangeInformationShowing() {
return fIsChangeInformationShown;
}
/**
* Creates a new <code>DocumentLineDiffer</code> and installs it with <code>model</code>.
* The default reference provider is installed with the newly created differ.
*
* @param model the annotation model of the current document.
* @return a new <code>DocumentLineDiffer</code> instance.
* @since R3.0
*/
private DocumentLineDiffer createDiffer(IAnnotationModelExtension model) {
DocumentLineDiffer differ;
differ= new DocumentLineDiffer();
IQuickDiffProviderImplementation provider= getDefaultReferenceProvider();
if (provider != null)
differ.setReferenceProvider(provider);
model.addAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID, differ);
return differ;
}
/**
* Returns the default quick diff reference provider. It is determined by first trying to
* enable the preferred provider as specified by the preferences; if this is unsuccessful, the
* default provider as specified by the extension point mechanism is installed. If that fails
* as well, <code>null</code> is returned.
*
* @return the default reference provider
* @since R3.0
*/
private IQuickDiffProviderImplementation getDefaultReferenceProvider() {
String defaultID= getPreferenceStore().getString(PreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER);
EditorsPlugin editorPlugin= EditorsPlugin.getDefault();
ReferenceProviderDescriptor[] descs= editorPlugin.getExtensions();
IQuickDiffProviderImplementation provider= null;
// try to fetch preferred provider; load if needed
for (int i= 0; i < descs.length; i++) {
if (descs[i].getId().equals(defaultID)) {
provider= descs[i].createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (provider.isEnabled())
break;
provider.dispose();
provider= null;
}
}
}
// if not found, get default provider as specified by the extension point
if (provider == null) {
ReferenceProviderDescriptor defaultDescriptor= editorPlugin.getDefaultProvider();
if (defaultDescriptor != null) {
provider= defaultDescriptor.createProvider();
if (provider != null) {
provider.setActiveEditor(this);
if (!provider.isEnabled()) {
provider.dispose();
provider= null;
}
}
}
}
return provider;
}
/**
* Returns the annotation model associated with the document displayed in the
* viewer if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>.
*
* @return the displayed document's annotation model if it is an <code>IAnnotationModelExtension</code>, or <code>null</code>
* @since R3.0
*/
private IAnnotationModelExtension getModel() {
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return null;
IAnnotationModel m= viewer.getAnnotationModel();
if (m instanceof IAnnotationModelExtension)
return (IAnnotationModelExtension) m;
else
return null;
}
/**
* Extracts the line differ from the displayed document's annotation model. If none can be found,
* a new differ is created and attached to the annotation model.
*
* @return the linediffer, or <code>null</code> if none could be found or created.
* @since R3.0
*/
private DocumentLineDiffer getOrCreateDiffer() {
IAnnotationModelExtension model= getModel();
if (model == null)
return null;
DocumentLineDiffer differ= (DocumentLineDiffer)model.getAnnotationModel(IChangeRulerColumn.QUICK_DIFF_MODEL_ID);
if (differ == null)
differ= createDiffer(model);
return differ;
}
/**
* Returns the <code>IChangeRulerColumn</code> of this editor, or <code>null</code> if there is none. Either
* the line number bar or a separate change ruler column can be returned.
*
* @return an instance of <code>IChangeRulerColumn</code> or <code>null</code>.
* @since R3.0
*/
private IChangeRulerColumn getChangeColumn() {
if (fChangeRulerColumn != null)
return fChangeRulerColumn;
else if (fLineNumberRulerColumn instanceof IChangeRulerColumn)
return (IChangeRulerColumn) fLineNumberRulerColumn;
else
return null;
}
/**
* Sets the display state of the separate change ruler column (not the quick diff display on
* the line number ruler column) to <code>show</code>.
*
* @param show <code>true</code> if the change ruler column should be shown, <code>false</code> if it should be hidden
* @since R3.0
*/
private void showChangeRuler(boolean show) {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
if (show && fChangeRulerColumn == null)
c.addDecorator(1, createChangeRulerColumn());
else if (!show && fChangeRulerColumn != null) {
c.removeDecorator(fChangeRulerColumn);
fChangeRulerColumn= null;
}
}
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
showChangeRuler(false);
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (fLineNumberRulerColumn != null && v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(fLineNumberRulerColumn);
fLineNumberRulerColumn= null;
}
if (fIsChangeInformationShown)
showChangeRuler(true);
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns whether quick diff info should be visible upon opening an editor
* according to the preference store settings.
*
* @return <code>true</code> if the line numbers should be visible
* @since R3.0
*/
private boolean isQuickDiffAlwaysOn() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(PreferenceConstants.QUICK_DIFF_ALWAYS_ON);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @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(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (IJavaPartitions.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
int lineOffset;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/**
* Initializes the given line number ruler column from the preference store.
*
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
rulerColumn.redraw();
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*
* @return a new line number ruler column
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
if (isQuickDiffAlwaysOn() || isChangeInformationShowing()) {
LineNumberChangeRulerColumn column= new LineNumberChangeRulerColumn();
column.setHover(new JavaChangeHover());
initializeChangeRulerColumn(column);
fLineNumberRulerColumn= column;
} else {
fLineNumberRulerColumn= new LineNumberRulerColumn();
}
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/**
* Initializes the given change ruler column from the preference store.
*
* @param changeColumn the ruler column to be initialized
* @since R3.0
*/
private void initializeChangeRulerColumn(IChangeRulerColumn changeColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
ISourceViewer v= getSourceViewer();
if (v != null && v.getAnnotationModel() != null) {
changeColumn.setModel(v.getAnnotationModel());
}
rgb= null;
// change color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_CHANGED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_CHANGED_COLOR);
}
}
changeColumn.setChangedColor(manager.getColor(rgb));
rgb= null;
// addition color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_ADDED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_ADDED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_ADDED_COLOR);
}
}
changeColumn.setAddedColor(manager.getColor(rgb));
rgb= null;
// deletion indicator color
if (!store.getBoolean(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.contains(PreferenceConstants.QUICK_DIFF_DELETED_COLOR)) {
if (store.isDefault(PreferenceConstants.QUICK_DIFF_DELETED_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
else
rgb= PreferenceConverter.getColor(store, PreferenceConstants.QUICK_DIFF_DELETED_COLOR);
}
}
changeColumn.setDeletedColor(manager.getColor(rgb));
}
changeColumn.redraw();
}
/**
* Creates a new change ruler column for quick diff display independent of the
* line number ruler column
*
* @return a new change ruler column
* @since R3.0
*/
protected IChangeRulerColumn createChangeRulerColumn() {
IChangeRulerColumn column= new ChangeRulerColumn();
column.setHover(new JavaChangeHover());
fChangeRulerColumn= column;
initializeChangeRulerColumn(fChangeRulerColumn);
return fChangeRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
else if (isQuickDiffAlwaysOn())
ruler.addDecorator(1, createChangeRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fSourceViewerDecorationSupport.install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell shell) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(shell, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) {
fEditorSelectionChangedListener= new EditorSelectionChangedListener();
fEditorSelectionChangedListener.install(getSelectionProvider());
}
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE))
configureInsertMode(OVERWRITE, false);
if (isQuickDiffAlwaysOn())
showChangeInformation(true);
}
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
protected void configureSourceViewerDecorationSupport() {
fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.UNKNOWN, UNKNOWN_INDICATION_COLOR, UNKNOWN_INDICATION, UNKNOWN_INDICATION_IN_OVERVIEW_RULER, 0);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.BOOKMARK, BOOKMARK_INDICATION_COLOR, BOOKMARK_INDICATION, BOOKMARK_INDICATION_IN_OVERVIEW_RULER, 1);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.TASK, TASK_INDICATION_COLOR, TASK_INDICATION, TASK_INDICATION_IN_OVERVIEW_RULER, 2);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.SEARCH, SEARCH_RESULT_INDICATION_COLOR, SEARCH_RESULT_INDICATION, SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, 3);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.WARNING, WARNING_INDICATION_COLOR, WARNING_INDICATION, WARNING_INDICATION_IN_OVERVIEW_RULER, 4);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.ERROR, ERROR_INDICATION_COLOR, ERROR_INDICATION, ERROR_INDICATION_IN_OVERVIEW_RULER, 5);
fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
fSourceViewerDecorationSupport.setSymbolicFontName(getFontPropertyPreferenceKey());
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset + 1: offset + length;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
// http://dev.eclipse.org/bugs/show_bug.cgi?id=34195
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset <= visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses 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);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
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;
}
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position errorPosition= new Position(0, 0);
IJavaAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition);
if (nextError != null) {
IMarker marker= null;
if (nextError instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextError).getMarker();
else {
Iterator e= nextError.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
setStatusLineErrorMessage(nextError.getMessage());
} else {
setStatusLineErrorMessage(null);
}
}
private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
IJavaAnnotation nextError= null;
Position nextErrorPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, true);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
if (a.hasOverlay() || !a.isProblem())
continue;
Position p= model.getPosition((Annotation) a);
if (!(p.includes(offset) || (p.getLength() == 0 && offset == p.offset))) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= a;
nextErrorPosition= p;
}
}
}
if (nextErrorPosition != null) {
errorPosition.setOffset(nextErrorPosition.getOffset());
errorPosition.setLength(nextErrorPosition.getLength());
}
return nextError;
}
/**
* Computes and returns the source reference that includes the caret and
* serves as provider for the outline page selection and the editor range
* indication.
*
* @return the computed source reference
* @since 3.0
*/
protected ISourceReference computeHighlightRangeSourceReference() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return null;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return null;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3)sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret, false);
if ( !(element instanceof ISourceReference))
return null;
if (element.getElementType() == IJavaElement.IMPORT_DECLARATION) {
IImportDeclaration declaration= (IImportDeclaration) element;
IImportContainer container= (IImportContainer) declaration.getParent();
ISourceRange srcRange= null;
try {
srcRange= container.getSourceRange();
} catch (JavaModelException e) {
}
if (srcRange != null && srcRange.getOffset() == caret)
return container;
}
return (ISourceReference) element;
}
/**
* Returns the most narrow java element including the given offset.
*
* @param offset the offset inside of the requested element
* @param reconcile <code>true</code> if editor input should be reconciled in advance
* @return the most narrow java element
* @since 3.0
*/
protected IJavaElement getElementAt(int offset, boolean reconcile) {
return getElementAt(offset);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.