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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
10,832 |
Bug 10832 NullPointerException when running JUnit Tests from Eclipse.
|
When running Junit Test from Eclipse using the JUnit plugin I get an internal error as soon as the Tests run through without failures or errors. Processing of TestCases stops at that point. I have always used the latest stable build (currently 20020214) but always got the same error. org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.NullPointerException) at org.eclipse.swt.SWT.error(SWT.java:1887) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:96) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1390) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) 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:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362) *** Stack trace of contained exception *** java.lang.NullPointerException at org.eclipse.jdt.internal.junit.ui.FailureRunView.endTest (FailureRunView.java:148) at org.eclipse.jdt.internal.junit.ui.TestRunnerViewPart$5.run (TestRunnerViewPart.java:367) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:29) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages (Synchronizer.java:93) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:1390) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) 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:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
1046e58
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T10:51:12Z | 2002-03-06T07:33:20Z |
JUnit/org/eclipse/jdt/internal/junit/ui/FailureRunView.java
| |
10,597 |
Bug 10597 JavaModelException after renaming method
|
20020228 I renamed a method and the parent type was showing in the type hierarchy. 4 org.eclipse.jdt.ui 1 Internal Error Java Model Exception: Java Model Status [createRetryQueryWithNoWorkingDirectory does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:452) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy (JavaElement.java:481) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:269) at org.eclipse.jdt.internal.core.SourceMethod.isConstructor (SourceMethod.java:133) at org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels.getMethodLabel (JavaElementLabels.java:339) at org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels.getElementLabel (JavaElementLabels.java:292) at org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels.getElementLabel (JavaElementLabels.java:272) at org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater.formatJavaElementMessag e(StatusBarUpdater.java:76) at org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater.formatMessage (StatusBarUpdater.java:66) at org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater.selectionChanged (StatusBarUpdater.java:51) at org.eclipse.jdt.internal.ui.typehierarchy.SelectionProviderMediator.fireSelectio nChanged(SelectionProviderMediator.java:105) at org.eclipse.jdt.internal.ui.typehierarchy.SelectionProviderMediator.propagateFoc usChanged(SelectionProviderMediator.java:94) at org.eclipse.jdt.internal.ui.typehierarchy.SelectionProviderMediator.doFocusChang ed(SelectionProviderMediator.java:78) at org.eclipse.jdt.internal.ui.typehierarchy.SelectionProviderMediator.access$1 (SelectionProviderMediator.java:75) at org.eclipse.jdt.internal.ui.typehierarchy.SelectionProviderMediator$InternalList ener.focusGained(SelectionProviderMediator.java:39) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:100) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:841) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:827) at org.eclipse.swt.widgets.Control.WM_SETFOCUS(Control.java:3694) at org.eclipse.swt.widgets.Table.WM_SETFOCUS(Table.java:2252) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2710) at org.eclipse.swt.widgets.Display.windowProc(Display.java:1806) at org.eclipse.swt.internal.win32.OS.SetFocus(Native Method) at org.eclipse.swt.widgets.Control.forceFocus(Control.java:572) at org.eclipse.swt.widgets.Decorations.restoreFocus (Decorations.java:608) at org.eclipse.swt.widgets.Decorations.WM_ACTIVATE (Decorations.java:1255) at org.eclipse.swt.widgets.Shell.WM_ACTIVATE(Shell.java:962) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2652) at org.eclipse.swt.widgets.Decorations.windowProc(Decorations.java:1225) at org.eclipse.swt.widgets.Display.windowProc(Display.java:1806) at org.eclipse.swt.internal.win32.OS.DestroyWindow(Native Method) at org.eclipse.swt.widgets.Control.destroyWidget(Control.java:485) at org.eclipse.swt.widgets.Widget.dispose(Widget.java:356) at org.eclipse.swt.widgets.Shell.dispose(Shell.java:402) at org.eclipse.jface.window.Window.close(Window.java:220) at org.eclipse.jface.wizard.WizardDialog.hardClose (WizardDialog.java:625) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:579) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:85) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.jface.window.Window.runEventLoop(Window.java:538) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.RefactoringSupportFactory$RenameSupport. rename(RefactoringSupportFactory.java:73) at org.eclipse.jdt.internal.ui.reorg.RenameAction.run (RenameAction.java:37) at org.eclipse.jface.action.Action.runWithEvent(Action.java:452) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
ec28e09
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T17:22:41Z | 2002-03-01T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IAdaptable;
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.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage;
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;
/**
* 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;
private final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - ";
private final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", ";
private final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type
/*
* Package name compression
*/
private static String fgPkgNamePattern= ""; //$NON-NLS-1$
private static String fgPkgNamePrefix;
private static String fgPkgNamePostfix;
private static int fgPkgNameChars;
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 "";
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static String getElementLabel(IJavaElement element, int flags) {
StringBuffer buf= new StringBuffer();
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 {
boolean isConstructor= method.isConstructor();
// return type
if (getFlag(flags, M_PRE_RETURNTYPE) && !isConstructor) {
buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType())));
buf.append(' ');
}
// qualification
if (getFlag(flags, M_FULLY_QUALIFIED)) {
getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED, 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.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)) {
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); //$NON-NLS-1$
}
buf.append(Signature.getSimpleName(Signature.toString(types[i])));
}
}
}
if (getFlag(flags, M_APP_RETURNTYPE) && !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, buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
/**
* 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)) {
buf.append(Signature.toString(field.getTypeSignature()));
buf.append(' '); //$NON-NLS-1$
}
// qualification
if (getFlag(flags, F_FULLY_QUALIFIED)) {
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED, buf);
buf.append('.');
}
buf.append(field.getElementName());
if (getFlag(flags, F_APP_TYPE_SIGNATURE)) {
buf.append(DECL_STRING); //$NON-NLS-1$
buf.append(Signature.toString(field.getTypeSignature()));
}
// post qualification
if (getFlag(flags, F_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED, buf);
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
/**
* 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, 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, 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)) {
buf.append(JavaModelUtil.getFullyQualifiedName(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) {
buf.append(JavaModelUtil.getFullyQualifiedName(declaringType));
} else {
getPackageFragmentLabel(type.getPackageFragment(), 0, 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) JavaModelUtil.getOpenable(declaration);
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) JavaModelUtil.getOpenable(declaration);
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('/');
}
if (pack.isDefaultPackage()) {
buf.append(JavaUIMessages.getString("JavaElementLabels.default_package")); //$NON-NLS-1$
} else if (getFlag(flags, P_COMPRESSED)) {
String name= pack.getElementName();
refreshPackageNamePattern();
int start= 0;
int dot= name.indexOf('.', start);
while (dot > 0) {
buf.append(fgPkgNamePrefix);
if (fgPkgNameChars > 0)
buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
buf.append(fgPkgNamePostfix);
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() && getFlag(flags, ROOT_VARIABLE)) {
try {
IClasspathEntry rawEntry= JavaModelUtil.getRawClasspathEntry(root);
if (rawEntry != null) {
if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
buf.append(rawEntry.getPath().makeRelative());
buf.append(CONCAT_STRING);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
if (root.isExternal()) {
// external jars have path == name
// no qualification for external roots
buf.append(root.getPath().toOSString());
} else {
if (getFlag(flags, ROOT_QUALIFIED)) {
buf.append(root.getPath().makeRelative().toString());
} else {
buf.append(root.getElementName());
}
if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getElementName());
}
}
}
private static void refreshPackageNamePattern() {
String pattern= WorkInProgressPreferencePage.getPkgNamePatternForPackagesView();
if (pattern.equals(fgPkgNamePattern))
return;
fgPkgNamePattern= pattern;
int i= 0;
fgPkgNameChars= 0;
fgPkgNamePrefix= "";
fgPkgNamePostfix= "";
while (i < pattern.length()) {
char ch= pattern.charAt(i);
if (Character.isDigit(ch)) {
fgPkgNameChars= ch-48;
if (i > 0 && i < pattern.length() - 1)
fgPkgNamePrefix= pattern.substring(0, i);
if (i >= 0 && i < pattern.length())
fgPkgNamePostfix= pattern.substring(i+1);
return;
}
i++;
}
fgPkgNamePrefix= pattern;
}
}
|
10,957 |
Bug 10957 IllegalArgumentException from drawing Highlight Line
|
20020305 Dont know if reproducible: 1. create new project with 2 classes pack.A & pack.B 2. add a long comment to B 3. Open Browser perspective, no editors open 4. Select B (opens editor), select comment, now switch to A ->IAE (Editor is reused) java.lang.IllegalArgumentException: Index out of bounds Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V org/eclipse/swt/SWT.error(ILjava/lang/Throwable;)V org/eclipse/swt/SWT.error(I)V org/eclipse/swt/custom/StyledText.redrawRange(IIZ)V org/eclipse/jdt/internal/ui/javaeditor/LinePainter.drawHighlightLine()V org/eclipse/jdt/internal/ui/javaeditor/LinePainter.paint()V org/eclipse/jdt/internal/ui/javaeditor/PaintManager.paint()V org/eclipse/jdt/internal/ui/javaeditor/PaintManager.access$2 (Lorg/eclipse/jdt/internal/ui/javaeditor/PaintManager;)V org/eclipse/jdt/internal/ui/javaeditor/PaintManager$1.run()V org/eclipse/swt/widgets/RunnableLock.run()V org/eclipse/swt/widgets/Synchronizer.runAsyncMessages()Z org/eclipse/swt/widgets/Display.runAsyncMessages()Z org/eclipse/swt/widgets/Display.readAndDispatch()Z org/eclipse/ui/internal/Workbench.runEventLoop()V org/eclipse/ui/internal/Workbench.run(Ljava/lang/Object;)Ljava/lang/Object; org/eclipse/core/internal/boot/InternalBootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;) Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;) Ljava/lang/Object; SlimLauncher.main([Ljava/lang/String;)V
|
resolved fixed
|
2188ec3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T17:34:50Z | 2002-03-07T16:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/LinePainter.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.swt.custom.LineBackgroundEvent;
import org.eclipse.swt.custom.LineBackgroundListener;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextContent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
public class LinePainter implements IPainter, LineBackgroundListener {
private StyledText fTextWidget;
private Color fHighlightColor;
private int fLineNumber;
private int[] fLine= { -1, -1 };
private boolean fIsActive= false;
public LinePainter(ISourceViewer sourceViewer) {
fTextWidget= sourceViewer.getTextWidget();
}
public void setHighlightColor(Color highlightColor) {
fHighlightColor= highlightColor;
}
/*
* @see LineBackgroundListener#lineGetBackground(LineBackgroundEvent)
*/
public void lineGetBackground(LineBackgroundEvent event) {
/* Don't use cached line information because of patched redrawing events. */
if (fTextWidget != null) {
int caret= fTextWidget.getCaretOffset();
int length= event.lineText.length();
if (event.lineOffset <= caret && caret <= event.lineOffset + length && fIsActive)
event.lineBackground= fHighlightColor;
else
event.lineBackground= fTextWidget.getBackground();
}
}
private void updateHighlightLine() {
StyledTextContent content= fTextWidget.getContent();
fLineNumber= content.getLineAtOffset(fTextWidget.getCaretOffset());
fLine[0]= content.getOffsetAtLine(fLineNumber);
try {
fLine[1]= content.getOffsetAtLine(fLineNumber + 1) - fLine[0];
} catch (IllegalArgumentException x) {
fLine[1]= -1;
}
}
private void drawHighlightLine() {
if (fLine[1] == -1 || (fLineNumber + 1) == fTextWidget.getLineCount()) {
Point upperLeft= fTextWidget.getLocationAtOffset(fLine[0]);
int width= fTextWidget.getClientArea().width;
int height= fTextWidget.getLineHeight();
fTextWidget.redraw(upperLeft.x, upperLeft.y, width, height, false);
} else {
fTextWidget.redrawRange(fLine[0], fLine[1], true);
}
}
/*
* @see IPainter#deactivate(boolean)
*/
public void deactivate(boolean redraw) {
if (fIsActive) {
fIsActive= false;
fTextWidget.removeLineBackgroundListener(this);
if (redraw)
drawHighlightLine();
}
}
/*
* @see IPainter#dispose()
*/
public void dispose() {
fTextWidget= null;
}
/*
* @see IPainter#paint()
*/
public void paint() {
if (!fIsActive) {
fIsActive= true;
fTextWidget.addLineBackgroundListener(this);
}
if (fLine[0] != -1 || fLine[1] != -1)
drawHighlightLine();
updateHighlightLine();
drawHighlightLine();
}
/*
* @see IPainter#setPositionManager(IPositionManager)
*/
public void setPositionManager(IPositionManager manager) {
}
}
|
10,387 |
Bug 10387 Code Assist crashes on constructor parameters
|
Using Nightly 0227 (but it's been present for since before the previous stable build) I get an exception thrown whenever I do code-assist on constructor parameters. example: throw new FlowHandlerException(<code-assist> "fillin argument names on completion" doesn't appear to change this. FlowHandlerException is a standard 1.1-type exception ( ie/ 2 constructors, () and (String) ) Eclipse nightly 20020227, PIII-800, 512 Megs ram, Win2k Stack trace: org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:110) at org.eclipse.jdt.internal.ui.text.java.AnonymousTypeCompletionProposal.<init>(AnonymousTypeCompletionProposal.java:39) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.createAnonymousTypeCompletion(ResultCollector.java:346) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.acceptAnonymousType(ResultCollector.java:142) at org.eclipse.jdt.internal.core.CompletionRequestorWrapper.acceptAnonymousType(CompletionRequestorWrapper.java:42) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findConstructors(CompletionEngine.java:810) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findAnonymousType(CompletionEngine.java:736) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:521) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:673) at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:113) at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:64) at org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor.computeCompletionProposals(JavaCompletionProcessor.java:312) at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1197) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:103) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$3(CompletionProposalPopup.java:102) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:71) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:56) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.showProposals(CompletionProposalPopup.java:66) at org.eclipse.jface.text.contentassist.ContentAssistant.showPossibleCompletions(ContentAssistant.java:1132) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:368) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:61) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:452) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
9a77a01
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:07:35Z | 2002-02-27T14:26:40Z |
org.eclipse.jdt.ui/core
| |
10,387 |
Bug 10387 Code Assist crashes on constructor parameters
|
Using Nightly 0227 (but it's been present for since before the previous stable build) I get an exception thrown whenever I do code-assist on constructor parameters. example: throw new FlowHandlerException(<code-assist> "fillin argument names on completion" doesn't appear to change this. FlowHandlerException is a standard 1.1-type exception ( ie/ 2 constructors, () and (String) ) Eclipse nightly 20020227, PIII-800, 512 Megs ram, Win2k Stack trace: org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:110) at org.eclipse.jdt.internal.ui.text.java.AnonymousTypeCompletionProposal.<init>(AnonymousTypeCompletionProposal.java:39) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.createAnonymousTypeCompletion(ResultCollector.java:346) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.acceptAnonymousType(ResultCollector.java:142) at org.eclipse.jdt.internal.core.CompletionRequestorWrapper.acceptAnonymousType(CompletionRequestorWrapper.java:42) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findConstructors(CompletionEngine.java:810) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findAnonymousType(CompletionEngine.java:736) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:521) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:673) at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:113) at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:64) at org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor.computeCompletionProposals(JavaCompletionProcessor.java:312) at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1197) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:103) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$3(CompletionProposalPopup.java:102) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:71) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:56) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.showProposals(CompletionProposalPopup.java:66) at org.eclipse.jface.text.contentassist.ContentAssistant.showPossibleCompletions(ContentAssistant.java:1132) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:368) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:61) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:452) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
9a77a01
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:07:35Z | 2002-02-27T14:26:40Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
10,387 |
Bug 10387 Code Assist crashes on constructor parameters
|
Using Nightly 0227 (but it's been present for since before the previous stable build) I get an exception thrown whenever I do code-assist on constructor parameters. example: throw new FlowHandlerException(<code-assist> "fillin argument names on completion" doesn't appear to change this. FlowHandlerException is a standard 1.1-type exception ( ie/ 2 constructors, () and (String) ) Eclipse nightly 20020227, PIII-800, 512 Megs ram, Win2k Stack trace: org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:110) at org.eclipse.jdt.internal.ui.text.java.AnonymousTypeCompletionProposal.<init>(AnonymousTypeCompletionProposal.java:39) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.createAnonymousTypeCompletion(ResultCollector.java:346) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.acceptAnonymousType(ResultCollector.java:142) at org.eclipse.jdt.internal.core.CompletionRequestorWrapper.acceptAnonymousType(CompletionRequestorWrapper.java:42) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findConstructors(CompletionEngine.java:810) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findAnonymousType(CompletionEngine.java:736) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:521) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:673) at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:113) at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:64) at org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor.computeCompletionProposals(JavaCompletionProcessor.java:312) at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1197) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:103) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$3(CompletionProposalPopup.java:102) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:71) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:56) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.showProposals(CompletionProposalPopup.java:66) at org.eclipse.jface.text.contentassist.ContentAssistant.showPossibleCompletions(ContentAssistant.java:1132) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:368) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:61) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:452) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
9a77a01
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:07:35Z | 2002-02-27T14:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/AnonymousTypeCompletionProposal.java
|
package org.eclipse.jdt.internal.ui.text.java;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.textmanipulation.TextUtil;
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.actions.OverrideMethodQuery;
import org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class AnonymousTypeCompletionProposal extends JavaCompletionProposal {
private IType fDeclaringType;
private ICompilationUnit fCompilationUnit;
private ImportsStructure fImportStructure;
public AnonymousTypeCompletionProposal(ICompilationUnit cu, int start, int length, String constructorCompletion, String displayName, String declaringTypeName) {
super(constructorCompletion, start, length, null, displayName);
Assert.isNotNull(cu);
Assert.isNotNull(declaringTypeName);
fCompilationUnit= cu;
fDeclaringType= getDeclaringType(cu.getJavaProject(), declaringTypeName);
setImage(getImageForType(fDeclaringType));
setCursorPosition(constructorCompletion.indexOf('(') + 1);
}
private Image getImageForType(IType type) {
String imageName= JavaPluginImages.IMG_OBJS_CLASS; // default
if (type != null) {
try {
if (type.isInterface()) {
imageName= JavaPluginImages.IMG_OBJS_INTERFACE;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return JavaPluginImages.get(imageName);
}
private IType getDeclaringType(IJavaProject project, String typeName) {
try {
return JavaModelUtil.findType(project, typeName);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return null;
}
/*
* @see JavaCompletionProposal#applyImports(IDocument)
*/
protected void applyImports(IDocument document) {
if (fImportStructure != null) {
try {
fImportStructure.create(false, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
/*
* @see ICompletionProposalExtension#apply(IDocument, char)
*/
public void apply(IDocument document, char trigger, int offset) {
try {
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
fImportStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true);
String replacementString= getReplacementString();
// construct replacement text
StringBuffer buf= new StringBuffer();
buf.append(replacementString);
if (!replacementString.endsWith(")")) {
buf.append(')');
}
buf.append(" {\n");
if (!createStubs(buf, fImportStructure)) {
return;
}
buf.append("}");
// use the code formatter
String lineDelim= StubUtility.getLineDelimiterFor(document);
int tabWidth= CodeFormatterPreferencePage.getTabSize();
IRegion region= document.getLineInformationOfOffset(getReplacementOffset());
int indent= TextUtil.getIndent(document.get(region.getOffset(), region.getLength()), tabWidth);
String replacement= StubUtility.codeFormat(buf.toString(), indent, lineDelim);
replacement= TextUtil.removeLeadingWhiteSpaces(replacement);
setReplacementString(replacement);
} catch (BadLocationException e) {
JavaPlugin.log(e);
} catch (CoreException e) {
JavaPlugin.log(e);
}
super.apply(document, trigger, offset);
}
private boolean createStubs(StringBuffer buf, ImportsStructure imports) throws JavaModelException {
if (fDeclaringType == null) {
return true;
}
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ITypeHierarchy hierarchy= fDeclaringType.newSupertypeHierarchy(null);
OverrideMethodQuery selectionQuery= fDeclaringType.isClass() ? new OverrideMethodQuery(JavaPlugin.getActiveWorkbenchShell(), true) : null;
String[] unimplemented= StubUtility.evalUnimplementedMethods(fDeclaringType, hierarchy, true, settings, selectionQuery, imports);
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
buf.append(unimplemented[i]);
buf.append('\n');
}
return true;
}
return false;
}
}
|
10,387 |
Bug 10387 Code Assist crashes on constructor parameters
|
Using Nightly 0227 (but it's been present for since before the previous stable build) I get an exception thrown whenever I do code-assist on constructor parameters. example: throw new FlowHandlerException(<code-assist> "fillin argument names on completion" doesn't appear to change this. FlowHandlerException is a standard 1.1-type exception ( ie/ 2 constructors, () and (String) ) Eclipse nightly 20020227, PIII-800, 512 Megs ram, Win2k Stack trace: org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java:110) at org.eclipse.jdt.internal.ui.text.java.AnonymousTypeCompletionProposal.<init>(AnonymousTypeCompletionProposal.java:39) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.createAnonymousTypeCompletion(ResultCollector.java:346) at org.eclipse.jdt.internal.ui.text.java.ResultCollector.acceptAnonymousType(ResultCollector.java:142) at org.eclipse.jdt.internal.core.CompletionRequestorWrapper.acceptAnonymousType(CompletionRequestorWrapper.java:42) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findConstructors(CompletionEngine.java:810) at org.eclipse.jdt.internal.codeassist.CompletionEngine.findAnonymousType(CompletionEngine.java:736) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:521) at org.eclipse.jdt.internal.codeassist.CompletionEngine.complete(CompletionEngine.java:673) at org.eclipse.jdt.internal.core.Openable.codeComplete(Openable.java:113) at org.eclipse.jdt.internal.core.CompilationUnit.codeComplete(CompilationUnit.java:64) at org.eclipse.jdt.internal.ui.text.java.JavaCompletionProcessor.computeCompletionProposals(JavaCompletionProcessor.java:312) at org.eclipse.jface.text.contentassist.ContentAssistant.computeCompletionProposals(ContentAssistant.java:1197) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.computeProposals(CompletionProposalPopup.java:103) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$3(CompletionProposalPopup.java:102) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$1.run(CompletionProposalPopup.java:71) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:56) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.showProposals(CompletionProposalPopup.java:66) at org.eclipse.jface.text.contentassist.ContentAssistant.showPossibleCompletions(ContentAssistant.java:1132) at org.eclipse.jface.text.source.SourceViewer.doOperation(SourceViewer.java:368) at org.eclipse.ui.texteditor.TextOperationAction.run(TextOperationAction.java:61) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:452) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:788) at org.eclipse.ui.internal.Workbench.run(Workbench.java:771) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
9a77a01
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:07:35Z | 2002-02-27T14:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.core.resources.IMarker;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.ICompletionRequestor;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaProject;
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.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
/**
* Bin to collect the proposal of the infrastructure on code assist in a java text.
*/
public class ResultCollector implements ICompletionRequestor {
private class ProposalComparator implements Comparator {
public int compare(Object o1, Object o2) {
ICompletionProposal c1= (ICompletionProposal) o1;
ICompletionProposal c2= (ICompletionProposal) o2;
return c1.getDisplayString().compareToIgnoreCase(c2.getDisplayString());
}
};
private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' };
private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' };
private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' };
private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';' };
private ArrayList fFields= new ArrayList(), fKeywords= new ArrayList(),
fLabels= new ArrayList(), fMethods= new ArrayList(),
fModifiers= new ArrayList(), fPackages= new ArrayList(),
fTypes= new ArrayList(), fVariables= new ArrayList();
private IMarker fLastProblem;
private IJavaProject fJavaProject;
private ICompilationUnit fCompilationUnit;
private int fCodeAssistOffset;
private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry();
private ArrayList[] fResults = new ArrayList[] {
fVariables, fFields, fMethods, fTypes, fKeywords, fModifiers, fLabels, fPackages
};
private int fUserReplacementLength;
/*
* Is eating code assist enabled or disabled? PR #3666
* When eating is enabled, JavaCompletionProposal must be revisited: PR #5533
*/
private boolean fPreventEating= true;
/*
* @see ICompletionRequestor#acceptClass
*/
public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end) {
ImageDescriptor descriptor= JavaPluginImages.DESC_OBJS_CLASS;
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info));
}
/*
* @see ICompletionRequestor#acceptError
*/
public void acceptError(IMarker problemMarker) {
fLastProblem= problemMarker;
}
/*
* @see ICompletionRequestor#acceptField
*/
public void acceptField(
char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[] typePackageName, char[] typeName, char[] completionName,
int modifiers, int start, int end) {
ImageDescriptor descriptor= getMemberDescriptor(modifiers);
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
if (typeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(typeName);
}
if (declaringTypeName != null && declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString());
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name));
proposal.setTriggerCharacters(VAR_TRIGGER);
fFields.add(proposal);
}
/*
* @see ICompletionRequestor#acceptInterface
*/
public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end) {
ImageDescriptor descriptor= JavaPluginImages.DESC_OBJS_INTERFACE;
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info));
}
/*
* @see ICompletionRequestor#acceptAnonymousType(char[], char[], char[][], char[][], char[][], char[], int, int, int)
*/
public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] completionName, int modifiers, int completionStart, int completionEnd) {
JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName));
fTypes.add(proposal);
}
/*
* @see ICompletionRequestor#acceptKeyword
*/
public void acceptKeyword(char[] keyword, int start, int end) {
String kw= new String(keyword);
fKeywords.add(createCompletion(start, end, kw, null, kw));
}
/*
* @see ICompletionRequestor#acceptLabel
*/
public void acceptLabel(char[] labelName, int start, int end) {
String ln= new String(labelName);
fLabels.add(createCompletion(start, end, ln, null, ln));
}
/*
* @see ICompletionRequestor#acceptLocalVariable
*/
public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end) {
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null) {
buf.append(" "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(name), null, buf.toString());
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
private String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) {
StringBuffer buf = new StringBuffer();
if (parameterTypeNames != null) {
for (int i = 0; i < parameterTypeNames.length; i++) {
if (i > 0) {
buf.append(',');
buf.append(' ');
}
buf.append(parameterTypeNames[i]);
if (parameterNames[i] != null) {
buf.append(' ');
buf.append(parameterNames[i]);
}
}
}
return buf.toString();
}
/*
* @see ICompletionRequestor#acceptMethod(char[], char[], char[], char[][], char[][], char[][], char[], char[], char[], int, int, int)
*/
public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name,
char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames,
char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers,
int start, int end) {
JavaCompletionProposal proposal= createMethodCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end);
proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0));
boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')');
ProposalContextInformation contextInformation= null;
if (hasOpeningBracket && parameterTypeNames.length > 0) {
contextInformation= new ProposalContextInformation();
contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames));
contextInformation.setContextDisplayString(proposal.getDisplayString());
contextInformation.setImage(proposal.getImage());
proposal.setContextInformation(contextInformation);
}
boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0);
char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS;
proposal.setTriggerCharacters(triggers);
if (userMustCompleteParameters) {
// set the cursor before the closing bracket
proposal.setCursorPosition(completionName.length - 1);
}
fMethods.add(proposal);
}
/*
* @see ICompletionRequestor#acceptModifier
*/
public void acceptModifier(char[] modifier, int start, int end) {
String mod= new String(modifier);
fModifiers.add(createCompletion(start, end, mod, null, mod));
}
/*
* @see ICompletionRequestor#acceptPackage
*/
public void acceptPackage(char[] packageName, char[] completionName, int start, int end) {
fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName)));
}
/*
* @see ICompletionRequestor#acceptType
*/
public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end) {
ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName);
fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info));
}
/*
* @see ICodeCompletionRequestor#acceptMethodDeclaration(char[], char[], char[], char[][], char[][], char[][], char[], char[], char[], int, int, int)
*/
public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) {
// XXX: To be revised
JavaCompletionProposal proposal= createMethodCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end);
fMethods.add(proposal);
}
/*
* @see ICodeCompletionRequestor#acceptVariableName(char[], char[], char[], char[], int, int)
*/
public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end) {
// XXX: To be revised
StringBuffer buf= new StringBuffer();
buf.append(name);
if (typeName != null && typeName.length > 0) {
buf.append(" - "); //$NON-NLS-1$
buf.append(typeName);
}
JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString());
proposal.setTriggerCharacters(VAR_TRIGGER);
fVariables.add(proposal);
}
public String getErrorMessage() {
if (fLastProblem != null)
return fLastProblem.getAttribute(IMarker.MESSAGE, JavaTextMessages.getString("ResultCollector.compile_error.message")); //$NON-NLS-1$
return ""; //$NON-NLS-1$
}
public JavaCompletionProposal[] getResults() {
ArrayList result= new ArrayList();
ProposalComparator comperator= new ProposalComparator();
for (int i= 0; i < fResults.length; i++) {
ArrayList bucket = fResults[i];
int size= bucket.size();
if (size == 1) {
result.add(bucket.get(0));
} else if (size > 1) {
Object[] sortedBucket = new Object[size];
bucket.toArray(sortedBucket);
Arrays.sort(sortedBucket, comperator);
for (int j= 0; j < sortedBucket.length; j++)
result.add(sortedBucket[j]);
}
}
return (JavaCompletionProposal[]) result.toArray(new JavaCompletionProposal[result.size()]);
}
protected JavaCompletionProposal createMethodCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) {
ImageDescriptor descriptor= getMemberDescriptor(modifiers);
if (Flags.isDeprecated(modifiers))
descriptor= getDeprecatedDescriptor(descriptor);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(name);
nameBuffer.append('(');
if (parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
if (returnTypeName.length > 0) {
nameBuffer.append(" "); //$NON-NLS-1$
nameBuffer.append(returnTypeName);
}
if (declaringTypeName.length > 0) {
nameBuffer.append(" - "); //$NON-NLS-1$
nameBuffer.append(declaringTypeName);
}
return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString());
}
protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end) {
StringBuffer declTypeBuf= new StringBuffer();
if (declaringTypePackageName.length > 0) {
declTypeBuf.append(declaringTypePackageName);
declTypeBuf.append('.');
}
declTypeBuf.append(declaringTypeName);
StringBuffer nameBuffer= new StringBuffer();
nameBuffer.append(declaringTypeName);
nameBuffer.append('(');
if (parameterTypeNames.length > 0) {
nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames));
}
nameBuffer.append(')');
nameBuffer.append(" ");
nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$
int length= end - start;
return new AnonymousTypeCompletionProposal(fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString());
}
protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo) {
IImportDeclaration importDeclaration= null;
if (containerName != null && fCompilationUnit != null) {
if (completion.equals(JavaModelUtil.concatenateName(containerName, typeName))) {
importDeclaration= fCompilationUnit.getImport(completion);
completion= typeName;
}
}
StringBuffer buf= new StringBuffer(typeName);
if (containerName != null) {
buf.append(" - "); //$NON-NLS-1$
if (containerName.length() > 0) {
buf.append(containerName);
} else {
buf.append(JavaTextMessages.getString("ResultCollector.default_package"));
}
}
String name= buf.toString();
JavaCompletionProposal proposal= createCompletion(start, end, completion, descriptor, name);
proposal.setImportDeclaration(importDeclaration);
proposal.setProposalInfo(proposalInfo);
proposal.setTriggerCharacters(TYPE_TRIGGERS);
return proposal;
}
protected ImageDescriptor getMemberDescriptor(int modifiers) {
if (Flags.isPublic(modifiers)) {
return JavaPluginImages.DESC_MISC_PUBLIC;
} else if (Flags.isProtected(modifiers)) {
return JavaPluginImages.DESC_MISC_PROTECTED;
} else if (Flags.isPrivate(modifiers)) {
return JavaPluginImages.DESC_MISC_PRIVATE;
} else {
return JavaPluginImages.DESC_MISC_DEFAULT;
}
}
protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) {
Point size= new Point(16, 16);
return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.WARNING, size);
}
protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name) {
int length;
if (fUserReplacementLength == -1) {
length= fPreventEating ? fCodeAssistOffset - start : end - start;
} else {
length= fUserReplacementLength;
// extend length to begin at start
if (start < fCodeAssistOffset) {
length+= fCodeAssistOffset - start;
}
}
Image icon= (descriptor == null) ? null : fRegistry.get(descriptor);
return new JavaCompletionProposal(completion, start, length, icon, name);
}
/**
* Specifies the context of the code assist operation.
* @param codeAssistOffset The Offset on which the code assist will be called.
* Used to modify the offsets of the created proposals. ('Non Eating')
* @param jproject The Java project to which the underlying source belongs.
* Needed to find types referred.
* @param cu The compilation unit that is edited. Used to add import statements.
* Can be <code>null</code> if no import statements should be added.
*/
public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) {
fJavaProject= jproject;
fCompilationUnit= cu;
fCodeAssistOffset= codeAssistOffset;
fUserReplacementLength= -1;
fLastProblem= null;
for (int i= 0; i < fResults.length; i++)
fResults[i].clear();
}
/**
* If the replacement length is set, it overrides the length returned from
* the content assist infrastructure.
* Use this setting if code assist is called with a none empty selection.
*/
public void setReplacementLength(int length) {
fUserReplacementLength= length;
}
/**
* If set, proposals created will not remove characters after the code assist position
* @param preventEating The preventEating to set
*/
public void setPreventEating(boolean preventEating) {
fPreventEating= preventEating;
}
}
|
10,762 |
Bug 10762 Generate getter and setter of a field starting with the 'F' letter
| null |
resolved fixed
|
73fae0b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:10:05Z | 2002-03-05T14:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeGenerationPreferencePage.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
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.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
public class CodeGenerationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String PREF_USE_GETTERSETTER_PREFIX= JavaUI.ID_PLUGIN + ".gettersetter.prefix.enable"; //$NON-NLS-1$
private static final String PREF_GETTERSETTER_PREFIX= JavaUI.ID_PLUGIN + ".gettersetter.prefix.list"; //$NON-NLS-1$
private static final String PREF_USE_GETTERSETTER_SUFFIX= JavaUI.ID_PLUGIN + ".gettersetter.suffix.enable"; //$NON-NLS-1$
private static final String PREF_GETTERSETTER_SUFFIX= JavaUI.ID_PLUGIN + ".gettersetter.suffix.list"; //$NON-NLS-1$
private static final String PREF_JAVADOC_STUBS= JavaUI.ID_PLUGIN + ".javadoc"; //$NON-NLS-1$
private static final String PREF_SEE_COMMENTS= JavaUI.ID_PLUGIN + ".seecomments"; //$NON-NLS-1$
private static final String PREF_FILE_COMMENTS= JavaUI.ID_PLUGIN + ".filecomments"; //$NON-NLS-1$
public static String[] getGetterStetterPrefixes() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PREF_USE_GETTERSETTER_PREFIX)) {
String str= prefs.getString(PREF_GETTERSETTER_PREFIX);
if (str != null) {
return unpackOrderList(str);
}
}
return new String[0];
}
public static String[] getGetterStetterSuffixes() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PREF_USE_GETTERSETTER_SUFFIX)) {
String str= prefs.getString(PREF_GETTERSETTER_SUFFIX);
if (str != null) {
return unpackOrderList(str);
}
}
return new String[0];
}
public static boolean doCreateComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_JAVADOC_STUBS);
}
public static boolean doNonJavaDocSeeComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_SEE_COMMENTS);
}
public static boolean doFileComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_FILE_COMMENTS);
}
private static String[] unpackOrderList(String str) {
StringTokenizer tok= new StringTokenizer(str, ","); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < nTokens; i++) {
res[i]= tok.nextToken().trim();
}
return res;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_USE_GETTERSETTER_PREFIX, true);
prefs.setDefault(PREF_USE_GETTERSETTER_SUFFIX, false);
prefs.setDefault(PREF_GETTERSETTER_PREFIX, "f, fg, _, m_"); //$NON-NLS-1$
prefs.setDefault(PREF_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$
prefs.setDefault(PREF_JAVADOC_STUBS, true);
prefs.setDefault(PREF_SEE_COMMENTS, true);
prefs.setDefault(PREF_FILE_COMMENTS, true);
}
private SelectionButtonDialogField fUseGetterSetterPrefix;
private SelectionButtonDialogField fUseGetterSetterSuffix;
private StringDialogField fGetterSetterPrefix;
private StringDialogField fGetterSetterSuffix;
private SelectionButtonDialogField fCreateJavaDocComments;
private SelectionButtonDialogField fCreateSeeComments;
private SelectionButtonDialogField fCreateFileComments;
private IStatus fGetterSetterPrefixStatus;
private IStatus fGetterSetterSuffixStatus;
public CodeGenerationPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CodeGenerationPreferencePage.description")); //$NON-NLS-1$
IDialogFieldListener listener= new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doDialogFieldChanged(field);
}
};
fGetterSetterPrefixStatus= new StatusInfo();
fGetterSetterSuffixStatus= new StatusInfo();
fUseGetterSetterPrefix= new SelectionButtonDialogField(SWT.CHECK);
fUseGetterSetterPrefix.setDialogFieldListener(listener);
fUseGetterSetterPrefix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.prefix.checkbox")); //$NON-NLS-1$
fGetterSetterPrefix= new StringDialogField();
fGetterSetterPrefix.setDialogFieldListener(listener);
fGetterSetterPrefix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.prefix.list")); //$NON-NLS-1$
fUseGetterSetterSuffix= new SelectionButtonDialogField(SWT.CHECK);
fUseGetterSetterSuffix.setDialogFieldListener(listener);
fUseGetterSetterSuffix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.suffix.checkbox")); //$NON-NLS-1$
fGetterSetterSuffix= new StringDialogField();
fGetterSetterSuffix.setDialogFieldListener(listener);
fGetterSetterSuffix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.suffix.list")); //$NON-NLS-1$
fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateJavaDocComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.javadoc_comment.label")); //$NON-NLS-1$
fCreateSeeComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateSeeComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.see_comment.label")); //$NON-NLS-1$
fCreateFileComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateFileComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.file_comment.label")); //$NON-NLS-1$
}
private void initFields() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fUseGetterSetterSuffix.setSelection(prefs.getBoolean(PREF_USE_GETTERSETTER_SUFFIX));
String str= prefs.getString(PREF_GETTERSETTER_SUFFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterSuffix.setText(str);
fUseGetterSetterPrefix.setSelection(prefs.getBoolean(PREF_USE_GETTERSETTER_PREFIX));
str= prefs.getString(PREF_GETTERSETTER_PREFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterPrefix.setText(str);
fCreateJavaDocComments.setSelection(prefs.getBoolean(PREF_JAVADOC_STUBS));
fCreateSeeComments.setSelection(prefs.getBoolean(PREF_SEE_COMMENTS));
fCreateFileComments.setSelection(prefs.getBoolean(PREF_FILE_COMMENTS));
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
int horizontalIndent= convertWidthInCharsToPixels(4);
(new Separator()).doFillIntoGrid(composite, 2, 4);
DialogField javaDocLabel= new DialogField();
javaDocLabel.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.comments.label")); //$NON-NLS-1$
javaDocLabel.doFillIntoGrid(composite, 2);
fCreateJavaDocComments.doFillIntoGrid(composite, 2);
fCreateSeeComments.doFillIntoGrid(composite, 2);
fCreateFileComments.doFillIntoGrid(composite, 2);
(new Separator()).doFillIntoGrid(composite, 2, 4);
DialogField getterSetterLabel= new DialogField();
getterSetterLabel.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.label")); //$NON-NLS-1$
getterSetterLabel.doFillIntoGrid(composite, 2);
fUseGetterSetterPrefix.doFillIntoGrid(composite, 2);
fGetterSetterPrefix.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalIndent(fGetterSetterPrefix.getLabelControl(null), horizontalIndent);
LayoutUtil.setHorizontalGrabbing(fGetterSetterPrefix.getTextControl(null));
fUseGetterSetterSuffix.doFillIntoGrid(composite, 2);
fGetterSetterSuffix.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalIndent(fGetterSetterSuffix.getLabelControl(null), horizontalIndent);
initFields();
return composite;
}
private void doDialogFieldChanged(DialogField field) {
if (field == fGetterSetterPrefix || field == fUseGetterSetterPrefix) {
fGetterSetterPrefix.setEnabled(fUseGetterSetterPrefix.isSelected());
if (fUseGetterSetterPrefix.isSelected()) {
String[] prefixes= unpackOrderList(fGetterSetterPrefix.getText());
fGetterSetterPrefixStatus= validateIdentifiers(prefixes, true);
} else {
fGetterSetterPrefixStatus= new StatusInfo();
}
}
if (field == fGetterSetterSuffix || field == fUseGetterSetterSuffix) {
fGetterSetterSuffix.setEnabled(fUseGetterSetterSuffix.isSelected());
if (fUseGetterSetterSuffix.isSelected()) {
String[] prefixes= unpackOrderList(fGetterSetterSuffix.getText());
fGetterSetterSuffixStatus= validateIdentifiers(prefixes, false);
} else {
fGetterSetterSuffixStatus= new StatusInfo();
}
}
updateStatus(StatusUtil.getMoreSevere(fGetterSetterPrefixStatus, fGetterSetterSuffixStatus));
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private IStatus validateIdentifiers(String[] values, boolean prefix) {
for (int i= 0; i < values.length; i++) {
String val= values[i];
if (val.length() == 0) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.error.emptyprefix")); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.error.emptysuffix")); //$NON-NLS-1$
}
}
String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$
IStatus status= JavaConventions.validateFieldName(name);
if (status.matches(IStatus.ERROR)) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getFormattedString("CodeGenerationPreferencePage.gettersetter.error.invalidprefix", val)); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getFormattedString("CodeGenerationPreferencePage.gettersetter.error.invalidsuffix", val)); //$NON-NLS-1$
}
}
}
return new StatusInfo();
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_USE_GETTERSETTER_SUFFIX, fUseGetterSetterSuffix.isSelected());
prefs.setValue(PREF_GETTERSETTER_SUFFIX, fGetterSetterSuffix.getText());
prefs.setValue(PREF_USE_GETTERSETTER_PREFIX, fUseGetterSetterPrefix.isSelected());
prefs.setValue(PREF_GETTERSETTER_PREFIX, fGetterSetterPrefix.getText());
prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected());
prefs.setValue(PREF_SEE_COMMENTS, fCreateSeeComments.isSelected());
prefs.setValue(PREF_FILE_COMMENTS, fCreateFileComments.isSelected());
return super.performOk();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fUseGetterSetterSuffix.setSelection(prefs.getDefaultBoolean(PREF_USE_GETTERSETTER_SUFFIX));
String str= prefs.getDefaultString(PREF_GETTERSETTER_SUFFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterSuffix.setText(str);
fUseGetterSetterPrefix.setSelection(prefs.getDefaultBoolean(PREF_USE_GETTERSETTER_PREFIX));
str= prefs.getDefaultString(PREF_GETTERSETTER_PREFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterPrefix.setText(str);
fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS));
fCreateSeeComments.setSelection(prefs.getDefaultBoolean(PREF_SEE_COMMENTS));
fCreateFileComments.setSelection(prefs.getDefaultBoolean(PREF_FILE_COMMENTS));
super.performDefaults();
}
}
|
10,795 |
Bug 10795 no progress or busy cursor opening refactor dialog
|
Build 20020214 Select a method in content outline, and choose refactor->pull up. Depending on the case, it can take a couple of seconds until the refactoring wizard appears. During this time there is no progress or busy cursor, and it is working in the UI thread so there are no repaints.
|
resolved fixed
|
172807b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:45:28Z | 2002-03-05T17:40:00Z |
org.eclipse.jdt.ui/ui
| |
10,795 |
Bug 10795 no progress or busy cursor opening refactor dialog
|
Build 20020214 Select a method in content outline, and choose refactor->pull up. Depending on the case, it can take a couple of seconds until the refactoring wizard appears. During this time there is no progress or busy cursor, and it is working in the UI thread so there are no repaints.
|
resolved fixed
|
172807b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:45:28Z | 2002-03-05T17:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/PullUpInputPage.java
| |
9,587 |
Bug 9587 Self encapsulate field: chosen argument names must be valid identifiers
|
1. In the code gen pref page set field name suffix to _ 2. Encapsulate field private IPackageFragment package_; -> private void setPackage(IPackageFragment package) { package_= package; } 'package' is a reserved keyword
|
resolved fixed
|
8b4e3bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:59:32Z | 2002-02-13T14:20:00Z |
org.eclipse.jdt.ui/core
| |
9,587 |
Bug 9587 Self encapsulate field: chosen argument names must be valid identifiers
|
1. In the code gen pref page set field name suffix to _ 2. Encapsulate field private IPackageFragment package_; -> private void setPackage(IPackageFragment package) { package_= package; } 'package' is a reserved keyword
|
resolved fixed
|
8b4e3bc
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T18:59:32Z | 2002-02-13T14:20:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/NameProposer.java
| |
10,970 |
Bug 10970 Index out of bounds exception when deleting code
|
Build 20020305 with latest stuff from 20020307 (catchup) - created a new file using the create CU wizard - selected the copyright using the shift down key combination - deleted it - selected the class comment using the shift down combination - deleted it Got the following exception: java.lang.IllegalArgumentException: Index out of bounds Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V org/eclipse/swt/SWT.error(ILjava/lang/Throwable;)V org/eclipse/swt/SWT.error(I)V org/eclipse/swt/custom/StyledText.redrawRange(IIZ)V org/eclipse/jdt/internal/ui/javaeditor/LinePainter.drawHighlightLine()V org/eclipse/jdt/internal/ui/javaeditor/LinePainter.paint()V org/eclipse/jdt/internal/ui/javaeditor/PaintManager.paint()V org/eclipse/jdt/internal/ui/javaeditor/PaintManager.selectionChanged (Lorg/eclipse/jface/viewers/SelectionChangedEvent;)V org/eclipse/jface/viewers/Viewer.fireSelectionChanged (Lorg/eclipse/jface/viewers/SelectionChangedEvent;)V org/eclipse/jface/text/TextViewer.selectionChanged(II)V org/eclipse/jface/text/TextViewer$4.widgetSelected (Lorg/eclipse/swt/events/SelectionEvent;)V org/eclipse/swt/widgets/TypedListener.handleEvent (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/EventTable.sendEvent(Lorg/eclipse/swt/widgets/Event;) V org/eclipse/swt/widgets/Widget.notifyListeners (ILorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/custom/StyledText.sendSelectionEvent()V org/eclipse/swt/custom/StyledText.clearSelection(Z)V org/eclipse/swt/custom/StyledText.internalSetSelection(IIZ)V org/eclipse/swt/custom/StyledText.updateSelection(III)V org/eclipse/swt/custom/StyledText.handleTextChanged (Lorg/eclipse/swt/custom/TextChangedEvent;)V org/eclipse/swt/custom/StyledText$6.textChanged (Lorg/eclipse/swt/custom/TextChangedEvent;)V org/eclipse/jface/text/DocumentAdapter.fireTextChanged()V org/eclipse/jface/text/DocumentAdapter.documentChanged (Lorg/eclipse/jface/text/DocumentEvent;)V org/eclipse/jface/text/AbstractDocument.fireDocumentChanged (Lorg/eclipse/jface/text/DocumentEvent;)V org/eclipse/jface/text/AbstractDocument.replace(IILjava/lang/String;)V org/eclipse/jface/text/DocumentAdapter.replaceTextRange(IILjava/lang/String;) V org/eclipse/swt/custom/StyledText.modifyContent (Lorg/eclipse/swt/widgets/Event;Z)V org/eclipse/swt/custom/StyledText.sendKeyEvent (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/custom/StyledText.doDelete()V org/eclipse/swt/custom/StyledText.invokeAction(I)V org/eclipse/swt/custom/StyledText.handleKey(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/custom/StyledText.handleKeyDown (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/custom/StyledText$8.handleEvent (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/EventTable.sendEvent(Lorg/eclipse/swt/widgets/Event;) V org/eclipse/swt/widgets/Widget.notifyListeners (ILorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Display.runDeferredEvents()Z org/eclipse/swt/widgets/Display.readAndDispatch()Z org/eclipse/ui/internal/Workbench.runEventLoop()V org/eclipse/ui/internal/Workbench.run(Ljava/lang/Object;)Ljava/lang/Object; org/eclipse/core/internal/boot/InternalBootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;) Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;) Ljava/lang/Object; SlimLauncher.main([Ljava/lang/String;)V
|
resolved fixed
|
320a2e7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T19:30:54Z | 2002-03-07T16:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/LinePainter.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.swt.custom.LineBackgroundEvent;
import org.eclipse.swt.custom.LineBackgroundListener;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.StyledTextContent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jdt.core.dom.CatchClause;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.ui.JavaPlugin;
public class LinePainter implements IPainter, LineBackgroundListener {
private StyledText fTextWidget;
private Color fHighlightColor;
private int fLineNumber;
private int[] fLine= { -1, -1 };
private boolean fIsActive= false;
public LinePainter(ISourceViewer sourceViewer) {
fTextWidget= sourceViewer.getTextWidget();
}
public void setHighlightColor(Color highlightColor) {
fHighlightColor= highlightColor;
}
/*
* @see LineBackgroundListener#lineGetBackground(LineBackgroundEvent)
*/
public void lineGetBackground(LineBackgroundEvent event) {
/* Don't use cached line information because of patched redrawing events. */
if (fTextWidget != null) {
int caret= fTextWidget.getCaretOffset();
int length= event.lineText.length();
if (event.lineOffset <= caret && caret <= event.lineOffset + length && fIsActive)
event.lineBackground= fHighlightColor;
else
event.lineBackground= fTextWidget.getBackground();
}
}
private void updateHighlightLine() {
StyledTextContent content= fTextWidget.getContent();
fLineNumber= content.getLineAtOffset(fTextWidget.getCaretOffset());
fLine[0]= content.getOffsetAtLine(fLineNumber);
try {
fLine[1]= content.getOffsetAtLine(fLineNumber + 1) - fLine[0];
} catch (IllegalArgumentException x) {
fLine[1]= -1;
}
}
private void drawHighlightLine() {
if (fLine[1] == -1 || (fLineNumber + 1) == fTextWidget.getLineCount()) {
Point upperLeft= fTextWidget.getLocationAtOffset(fLine[0]);
int width= fTextWidget.getClientArea().width;
int height= fTextWidget.getLineHeight();
fTextWidget.redraw(upperLeft.x, upperLeft.y, width, height, false);
} else {
fTextWidget.redrawRange(fLine[0], fLine[1], true);
}
}
/*
* @see IPainter#deactivate(boolean)
*/
public void deactivate(boolean redraw) {
if (fIsActive) {
fIsActive= false;
fTextWidget.removeLineBackgroundListener(this);
if (redraw)
drawHighlightLine();
}
}
/*
* @see IPainter#dispose()
*/
public void dispose() {
fTextWidget= null;
}
/*
* @see IPainter#paint()
*/
public void paint() {
if (!fIsActive) {
fIsActive= true;
fTextWidget.addLineBackgroundListener(this);
} else if (fLine[0] != -1) {
drawHighlightLine();
}
updateHighlightLine();
drawHighlightLine();
}
/*
* @see IPainter#setPositionManager(IPositionManager)
*/
public void setPositionManager(IPositionManager manager) {
}
}
|
9,510 |
Bug 9510 Improve option settings for JDK 1.4
|
What we currently offer isn't sufficient. We should discuss with Philippe, this is important for the next milestone
|
resolved fixed
|
66a7cef
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-07T22:03:08Z | 2002-02-13T06:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Hashtable;
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.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.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
/*
* The page for setting the compiler options.
*/
public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= "org.eclipse.jdt.core.compiler.debug.localVariable";
private static final String PREF_LINE_NUMBER_ATTR= "org.eclipse.jdt.core.compiler.debug.lineNumber";
private static final String PREF_SOURCE_FILE_ATTR= "org.eclipse.jdt.core.compiler.debug.sourceFile";
private static final String PREF_CODEGEN_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.codegen.unusedLocal";
private static final String PREF_CODEGEN_TARGET_PLATFORM= "org.eclipse.jdt.core.compiler.codegen.targetPlatform";
private static final String PREF_PB_UNREACHABLE_CODE= "org.eclipse.jdt.core.compiler.problem.unreachableCode";
private static final String PREF_PB_INVALID_IMPORT= "org.eclipse.jdt.core.compiler.problem.invalidImport";
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= "org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod";
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= "org.eclipse.jdt.core.compiler.problem.methodWithConstructorName";
private static final String PREF_PB_DEPRECATION= "org.eclipse.jdt.core.compiler.problem.deprecation";
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock";
private static final String PREF_PB_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.problem.unusedLocal";
private static final String PREF_PB_UNUSED_PARAMETER= "org.eclipse.jdt.core.compiler.problem.unusedParameter";
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= "org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation";
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= "org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral";
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= "org.eclipse.jdt.core.compiler.problem.assertIdentifier";
private static final String PREF_SOURCE_COMPATIBILITY= "org.eclipse.jdt.core.compiler.source";
// values
private static final String GENERATE= "generate";
private static final String DO_NOT_GENERATE= "do not generate";
private static final String PRESERVE= "preserve";
private static final String OPTIMIZE_OUT= "optimize out";
private static final String VERSION_1_1= "1.1";
private static final String VERSION_1_2= "1.2";
private static final String VERSION_1_3= "1.3";
private static final String VERSION_1_4= "1.4";
private static final String ERROR= "error";
private static final String WARNING= "warning";
private static final String IGNORE= "ignore";
private static String[] getAllKeys() {
return new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, 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_SOURCE_COMPATIBILITY
};
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("CompilerPreferencePage: value is null: " + key);
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
private 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();
}
}
private Hashtable fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fComboBoxes;
private SelectionListener fSelectionListener;
public CompilerPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
}
/**
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/**
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
// added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE);
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.error"),
JavaUIMessages.getString("CompilerPreferencePage.warning"),
JavaUIMessages.getString("CompilerPreferencePage.ignore")
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite warningsComposite= new Composite(folder, SWT.NULL);
warningsComposite.setLayout(layout);
Label description= new Label(warningsComposite, SWT.WRAP);
description.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
String label= JavaUIMessages.getString("CompilerPreferencePage.pb_unreachable_code.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_invalid_import.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels);
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
layout= new GridLayout();
layout.numColumns= 2;
Composite codeGenComposite= new Composite(folder, SWT.NULL);
codeGenComposite.setLayout(layout);
label= JavaUIMessages.getString("CompilerPreferencePage.variable_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues);
label= JavaUIMessages.getString("CompilerPreferencePage.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues);
label= JavaUIMessages.getString("CompilerPreferencePage.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues);
label= JavaUIMessages.getString("CompilerPreferencePage.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT });
String[] values= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] valuesLabels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.jvm11"),
JavaUIMessages.getString("CompilerPreferencePage.jvm12"),
JavaUIMessages.getString("CompilerPreferencePage.jvm13"),
JavaUIMessages.getString("CompilerPreferencePage.jvm14")
};
label= JavaUIMessages.getString("CompilerPreferencePage.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(codeGenComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values, valuesLabels);
values= new String[] { VERSION_1_3, VERSION_1_4 };
valuesLabels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.version13"),
JavaUIMessages.getString("CompilerPreferencePage.version14")
};
label= JavaUIMessages.getString("CompilerPreferencePage.source_compatibility.label"); //$NON-NLS-1$
addComboBox(codeGenComposite, label, PREF_SOURCE_COMPATIBILITY, values, valuesLabels);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_WARNING));
item.setControl(warningsComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.generation.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(codeGenComposite);
return folder;
}
private void addCheckBox(Composite parent, String label, String key, String[] values) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
fCheckBoxes.add(checkBox);
}
private void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels) {
ControlData data= new ControlData(key, values);
Label labelControl= new Label(parent, SWT.NONE);
labelControl.setText(label);
labelControl.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd= new GridData();
gd.horizontalAlignment= GridData.FILL;
Combo comboBox= new Combo(parent, SWT.READ_ONLY);
comboBox.setItems(valueLabels);
comboBox.setData(data);
comboBox.setLayoutData(gd);
comboBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
private 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);
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
String oldVal= (String) actualOptions.get(key);
hasChanges= hasChanges | !val.equals(oldVal);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
if (hasChanges) {
String title= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.title");
String message= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.message");
if (MessageDialog.openQuestion(getShell(), title, message)) {
doFullBuild();
}
}
return super.performOk();
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("CompilerPreferencePage.builderror.title");
String message= JavaUIMessages.getString("CompilerPreferencePage.builderror.message");
ExceptionHandler.handle(e, getShell(), title, message);
}
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
updateControls();
super.performDefaults();
}
private void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= 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));
}
}
}
|
11,026 |
Bug 11026 extract local variable: incorrect on some boolean expressions
|
public class A{ boolean m(){ return /*[*/a().length != 3/*]*/; } int[] a(){ return null; } }
|
verified fixed
|
2f7e475
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-08T16:11:23Z | 2002-03-08T15:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test28_in.java
| |
11,026 |
Bug 11026 extract local variable: incorrect on some boolean expressions
|
public class A{ boolean m(){ return /*[*/a().length != 3/*]*/; } int[] a(){ return null; } }
|
verified fixed
|
2f7e475
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-08T16:11:23Z | 2002-03-08T15:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractTemp/canExtract/A_test28_out.java
| |
11,026 |
Bug 11026 extract local variable: incorrect on some boolean expressions
|
public class A{ boolean m(){ return /*[*/a().length != 3/*]*/; } int[] a(){ return null; } }
|
verified fixed
|
2f7e475
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-08T16:11:23Z | 2002-03-08T15:06:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,026 |
Bug 11026 extract local variable: incorrect on some boolean expressions
|
public class A{ boolean m(){ return /*[*/a().length != 3/*]*/; } int[] a(){ return null; } }
|
verified fixed
|
2f7e475
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-08T16:11:23Z | 2002-03-08T15:06:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractTempTests.java
| |
9,909 |
Bug 9909 template: toarray - using ${type} is wrong
|
using ${type} in toarray is wrong it puts the name of the enclosing type - which is very much not what is needed. only the user knows to what type the casting should be done suggest creating ${enclosing_type} for enclosing types
|
resolved fixed
|
a0ea2a1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-11T14:38:22Z | 2002-02-15T16:20:00Z |
org.eclipse.jdt.ui/core
| |
9,909 |
Bug 9909 template: toarray - using ${type} is wrong
|
using ${type} in toarray is wrong it puts the name of the enclosing type - which is very much not what is needed. only the user knows to what type the casting should be done suggest creating ${enclosing_type} for enclosing types
|
resolved fixed
|
a0ea2a1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-11T14:38:22Z | 2002-02-15T16:20:00Z |
extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitContextType.java
| |
9,646 |
Bug 9646 open type: no progress should be shown if no searching is done
|
there used to be no progress monitor dialog in the 'fast access' mode (when stuff was actually in the cache and no searching was done) now, i see the progress monitor everytime which makes no sense (takes more time to open the PM dialog then the type dialog) and it looks extremally flashy
|
resolved fixed
|
cf40a94
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-11T17:02:30Z | 2002-02-13T17:06:40Z |
org.eclipse.jdt.ui/core
| |
9,646 |
Bug 9646 open type: no progress should be shown if no searching is done
|
there used to be no progress monitor dialog in the 'fast access' mode (when stuff was actually in the cache and no searching was done) now, i see the progress monitor everytime which makes no sense (takes more time to open the PM dialog then the type dialog) and it looks extremally flashy
|
resolved fixed
|
cf40a94
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-11T17:02:30Z | 2002-02-13T17:06:40Z |
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
| |
9,646 |
Bug 9646 open type: no progress should be shown if no searching is done
|
there used to be no progress monitor dialog in the 'fast access' mode (when stuff was actually in the cache and no searching was done) now, i see the progress monitor everytime which makes no sense (takes more time to open the PM dialog then the type dialog) and it looks extremally flashy
|
resolved fixed
|
cf40a94
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-11T17:02:30Z | 2002-02-13T17:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/TypeSelectionDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.dialogs;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.internal.corext.util.AllTypesCache;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.StringMatcher;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
/**
* A dialog to select a type from a list of types.
*/
public class TypeSelectionDialog extends TwoPaneElementSelector {
private static class TypeFilterMatcher implements FilteredList.FilterMatcher {
private StringMatcher fMatcher;
private StringMatcher fQualifierMatcher;
/*
* @see FilteredList.FilterMatcher#setFilter(String, boolean)
*/
public void setFilter(String pattern, boolean ignoreCase, boolean igoreWildCards) {
int qualifierIndex= pattern.lastIndexOf("."); //$NON-NLS-1$
// type
if (qualifierIndex == -1) {
fQualifierMatcher= null;
fMatcher= new StringMatcher(pattern + '*', ignoreCase, igoreWildCards);
// qualified type
} else {
fQualifierMatcher= new StringMatcher(pattern.substring(0, qualifierIndex), ignoreCase, igoreWildCards);
fMatcher= new StringMatcher(pattern.substring(qualifierIndex + 1), ignoreCase, igoreWildCards);
}
}
/*
* @see FilteredList.FilterMatcher#match(Object)
*/
public boolean match(Object element) {
if (!(element instanceof TypeInfo))
return false;
TypeInfo type= (TypeInfo) element;
if (!fMatcher.match(type.getTypeName()))
return false;
if (fQualifierMatcher == null)
return true;
return fQualifierMatcher.match(type.getTypeContainerName());
}
}
/*
* A string comparator which is aware of obfuscated code
* (type names starting with lower case characters).
*/
private static class StringComparator implements Comparator {
public int compare(Object left, Object right) {
String leftString= (String) left;
String rightString= (String) right;
if (Character.isLowerCase(leftString.charAt(0)) &&
!Character.isLowerCase(rightString.charAt(0)))
return +1;
if (Character.isLowerCase(rightString.charAt(0)) &&
!Character.isLowerCase(leftString.charAt(0)))
return -1;
return leftString.compareToIgnoreCase(rightString);
}
}
private IRunnableContext fRunnableContext;
private IJavaSearchScope fScope;
private int fElementKinds;
/**
* Constructs a type selection dialog.
* @param parent the parent shell.
* @param context the runnable context.
* @param elementKinds <code>IJavaSearchConstants.CLASS</code>, <code>IJavaSearchConstants.INTERFACE</code>
* or <code>IJavaSearchConstants.TYPE</code>
* @param scope the java search scope.
*/
public TypeSelectionDialog(Shell parent, IRunnableContext context, int elementKinds, IJavaSearchScope scope) {
super(parent, new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_ONLY),
new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_TYPE_CONTAINER_ONLY + TypeInfoLabelProvider.SHOW_ROOT_POSTFIX));
Assert.isNotNull(context);
Assert.isNotNull(scope);
fRunnableContext= context;
fScope= scope;
fElementKinds= elementKinds;
setUpperListLabel(JavaUIMessages.getString("TypeSelectionDialog.upperLabel")); //$NON-NLS-1$
setLowerListLabel(JavaUIMessages.getString("TypeSelectionDialog.lowerLabel")); //$NON-NLS-1$
}
public void create() {
if (getFilter() == null)
setFilter("A"); //$NON-NLS-1$
super.create();
}
/*
* @see AbstractElementListSelectionDialog#createFilteredList(Composite)
*/
protected FilteredList createFilteredList(Composite parent) {
FilteredList list= super.createFilteredList(parent);
fFilteredList.setFilterMatcher(new TypeFilterMatcher());
fFilteredList.setComparator(new StringComparator());
return list;
}
/**
* @see Window#open()
*/
public int open() {
final ArrayList typeList= new ArrayList();
IRunnableWithProgress runnable= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
AllTypesCache.getTypes(fScope, fElementKinds, monitor, typeList);
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
}
if (monitor.isCanceled()) {
throw new InterruptedException();
}
}
};
try {
fRunnableContext.run(true, true, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, "Exception", "Unexpected exception. See log for details.");
} catch (InterruptedException e) {
// cancelled by user
return CANCEL;
}
if (typeList.isEmpty()) {
String title= JavaUIMessages.getString("TypeSelectionDialog.notypes.title"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.notypes.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
return CANCEL;
}
TypeInfo[] typeRefs= (TypeInfo[])typeList.toArray(new TypeInfo[typeList.size()]);
setElements(typeRefs);
return super.open();
}
/**
* @see SelectionStatusDialog#computeResult()
*/
protected void computeResult() {
TypeInfo ref= (TypeInfo) getLowerSelectedElement();
if (ref == null)
return;
try {
IType type= ref.resolveType(fScope);
if (type == null) {
// not a class file or compilation unit
String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
setResult(null);
} else {
List result= new ArrayList(1);
result.add(type);
setResult(result);
}
} catch (JavaModelException e) {
String title= JavaUIMessages.getString("TypeSelectionDialog.errorTitle"); //$NON-NLS-1$
String message= JavaUIMessages.getString("TypeSelectionDialog.errorMessage"); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
setResult(null);
}
}
}
|
11,109 |
Bug 11109 F1 no longer works in Packages view
|
new context ID?
|
resolved fixed
|
902f54b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T10:32:04Z | 2002-03-11T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/IJavaHelpContextIds.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.jdt.ui.JavaUI;
/**
* Help context ids for the Java UI.
* <p>
* This interface contains constants only; it is not intended to be implemented
* or extended.
* </p>
*
*/
public interface IJavaHelpContextIds {
public static final String PREFIX= JavaUI.ID_PLUGIN + '.';
// Actions
public static final String GETTERSETTER_ACTION= PREFIX + "getter_setter_action_context"; //$NON-NLS-1$
public static final String ADD_METHODBREAKPOINT_ACTION= PREFIX + "add_methodbreakpoint_action_context"; //$NON-NLS-1$
public static final String ADD_WATCHPOINT_ACTION= PREFIX + "add_watchpoint_action_context"; //$NON-NLS-1$
public static final String ADD_METHODSTUB_ACTION= PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$
public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$
public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$
public static final String SHOW_IN_PACKAGEVIEW_ACTION= PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$
public static final String SHOW_IN_HIERARCHYVIEW_ACTION= PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$
public static final String FOCUS_ON_SELECTION_ACTION= PREFIX + "focus_on_selection_action"; //$NON-NLS-1$
public static final String FOCUS_ON_TYPE_ACTION= PREFIX + "focus_on_type_action"; //$NON-NLS-1$
public static final String TYPEHIERARCHY_HISTORY_ACTION= PREFIX + "typehierarchy_history_action"; //$NON-NLS-1$
public static final String FILTER_PUBLIC_ACTION= PREFIX + "filter_public_action"; //$NON-NLS-1$
public static final String FILTER_FIELDS_ACTION= PREFIX + "filter_fields_action"; //$NON-NLS-1$
public static final String FILTER_STATIC_ACTION= PREFIX + "filter_static_action"; //$NON-NLS-1$
public static final String SHOW_INHERITED_ACTION= PREFIX + "show_inherited_action"; //$NON-NLS-1$
public static final String SHOW_SUPERTYPES= PREFIX + "show_supertypes_action"; //$NON-NLS-1$
public static final String SHOW_SUBTYPES= PREFIX + "show_subtypes_action"; //$NON-NLS-1$
public static final String SHOW_HIERARCHY= PREFIX + "show_hierarchy_action"; //$NON-NLS-1$
public static final String ENABLE_METHODFILTER_ACTION= PREFIX + "enable_methodfilter_action"; //$NON-NLS-1$
public static final String ADD_IMPORT_ON_SELECTION_ACTION= PREFIX + "add_imports_on_selection_action_context"; //$NON-NLS-1$
public static final String ORGANIZE_IMPORTS_ACTION= PREFIX + "organize_imports_action_context"; //$NON-NLS-1$
public static final String RUN_TO_LINE_ACTION= PREFIX + "run_to_line_action_context"; //$NON-NLS-1$
public static final String TOGGLE_PRESENTATION_ACTION= PREFIX + "toggle_presentation_action_context"; //$NON-NLS-1$
public static final String TOGGLE_TEXTHOVER_ACTION= PREFIX + "toggle_texthover_action_context"; //$NON-NLS-1$
// Dialogs
public static final String MAINTYPE_SELECTION_DIALOG= PREFIX + "maintype_selection_dialog_context"; //$NON-NLS-1$
public static final String OPEN_TYPE_DIALOG= PREFIX + "open_type_dialog_context"; //$NON-NLS-1$
public static final String EDIT_JRE_DIALOG= PREFIX + "edit_jre_dialog_context"; //$NON-NLS-1$
public static final String SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$
public static final String VARIABLE_SELECTION_DIALOG= PREFIX + "variable_selection_dialog_context"; //$NON-NLS-1$
public static final String VARIABLE_CREATION_DIALOG= PREFIX + "variable_creation_dialog_context"; //$NON-NLS-1$
public static final String JAVA_SEARCH_PAGE= PREFIX + "java_search_page_context"; //$NON-NLS-1$
public static final String COMPILATION_UNIT_EDITOR= PREFIX + "compilation_unit_editor_context"; //$NON-NLS-1$
public static final String CLASS_FILE_EDITOR= PREFIX + "class_file_editor_context"; //$NON-NLS-1$
// view parts
public static final String PACKAGE_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$
public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$
public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$
public static final String PACKAGES_VIEW= PREFIX + "packages_view_context"; //$NON-NLS-1$
public static final String TYPES_VIEW= PREFIX + "types_view_context"; //$NON-NLS-1$
public static final String MEMBERS_VIEW= PREFIX + "members_view_context"; //$NON-NLS-1$
// Preference/Property pages
public static final String APPEARANCE_PREFERENCE_PAGE= PREFIX + "appearance_preference_page_context"; //$NON-NLS-1$
public static final String BUILD_PATH_PROPERTY_PAGE= PREFIX + "build_path_property_page_context"; //$NON-NLS-1$
public static final String CP_VARIABLES_PREFERENCE_PAGE= PREFIX + "cp_variables_preference_page_context"; //$NON-NLS-1$
public static final String CODEFORMATTER_PREFERENCE_PAGE= PREFIX + "codeformatter_preference_page_context"; //$NON-NLS-1$
public static final String SOURCE_ATTACHMENT_PROPERTY_PAGE= PREFIX + "source_attachment_property_page_context"; //$NON-NLS-1$
public static final String SOURCE_LOOKUP_PROPERTY_PAGE= PREFIX + "source_lookup_property_page_context"; //$NON-NLS-1$
public static final String CODE_MANIPULATION_PREFERENCE_PAGE= PREFIX + "code_manipulation_preference_context"; //$NON-NLS-1$
public static final String ORGANIZE_IMPORTS_PREFERENCE_PAGE= PREFIX + "organizeimports_preference_page_context"; //$NON-NLS-1$
public static final String JAVA_BASE_PREFERENCE_PAGE= PREFIX + "java_base_preference_page_context"; //$NON-NLS-1$
public static final String REFACTORING_PREFERENCE_PAGE= PREFIX + "refactoring_preference_page_context"; //$NON-NLS-1$
public static final String JAVA_EDITOR_PREFERENCE_PAGE= PREFIX + "java_editor_preference_page_context"; //$NON-NLS-1$
public static final String COMPILER_PREFERENCE_PAGE= PREFIX + "compiler_preference_page_context"; //$NON-NLS-1$
public static final String TEMPLATE_PREFERENCE_PAGE= PREFIX + "template_preference_page_context"; //$NON-NLS-1$
public static final String WORK_IN_PROGRESS_PREFERENCE_PAGE= PREFIX + "work_in_progress_preference_page_context"; //$NON-NLS-1$
public static final String JAVA_BROWSING_PREFERENCE_PAGE= PREFIX + "java_browsing_preference_page_context"; //$NON-NLS-1$
// Wizard pages
public static final String NEW_JAVAPROJECT_WIZARD_PAGE= PREFIX + "new_javaproject_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_SNIPPET_WIZARD_PAGE= PREFIX + "new_snippet_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_PACKAGE_WIZARD_PAGE= PREFIX + "new_package_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_CLASS_WIZARD_PAGE= PREFIX + "new_class_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_INTERFACE_WIZARD_PAGE= PREFIX + "new_interface_wizard_page_context"; //$NON-NLS-1$
public static final String NEW_PACKAGEROOT_WIZARD_PAGE= PREFIX + "new_packageroot_wizard_page_context"; //$NON-NLS-1$
public static final String JARPACKAGER_WIZARD_PAGE= PREFIX + "jar_packager_wizard_page_context"; //$NON-NLS-1$
public static final String JARMANIFEST_WIZARD_PAGE= PREFIX + "jar_manifest_wizard_page_context"; //$NON-NLS-1$
public static final String JAROPTIONS_WIZARD_PAGE= PREFIX + "jar_options_wizard_page_context"; //$NON-NLS-1$
// same help for all refactoring preview pages
public static final String REFACTORING_PREVIEW_WIZARD_PAGE= PREFIX + "refactoring_preview_wizard_page_context"; //$NON-NLS-1$
public static final String MOVE_CU_WIZARD_PAGE= PREFIX + "move_cu_wizard_page_context"; //$NON-NLS-1$
public static final String MOVE_CU_ERROR_WIZARD_PAGE= PREFIX + "move_cu_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_PARAMS_WIZARD_PAGE= PREFIX + "rename_params_wizard_page"; //$NON-NLS-1$
public static final String RENAME_PARAMS_ERROR_WIZARD_PAGE= PREFIX + "rename_params_error_wizard_page"; //$NON-NLS-1$
public static final String EXTRACT_METHOD_WIZARD_PAGE= PREFIX + "extract_method_wizard_page_context"; //$NON-NLS-1$
public static final String EXTRACT_METHOD_ERROR_WIZARD_PAGE= PREFIX + "extract_method_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_PACKAGE_WIZARD_PAGE= PREFIX + "rename_package_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_PACKAGE_ERROR_WIZARD_PAGE= PREFIX + "rename_package_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_SRCFLDR_WIZARD_PAGE= PREFIX + "rename_source_folder_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_SRCFLDR_ERROR_WIZARD_PAGE= PREFIX + "rename_source_folder_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_JPRJ_WIZARD_PAGE= PREFIX + "rename_java_project_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_JPRJ_ERROR_WIZARD_PAGE= PREFIX + "rename_java_project_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_RESOURCE_WIZARD_PAGE= PREFIX + "rename_resource_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_RESOURCE_ERROR_WIZARD_PAGE= PREFIX + "rename_resource_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_TEMP_WIZARD_PAGE= PREFIX + "rename_local_variable_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_TEMP_ERROR_WIZARD_PAGE= PREFIX + "rename_local_variable_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_CU_WIZARD_PAGE= PREFIX + "rename_cu_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_CU_ERROR_WIZARD_PAGE= PREFIX + "rename_cu_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_METHOD_WIZARD_PAGE= PREFIX + "rename_method_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_METHOD_ERROR_WIZARD_PAGE= PREFIX + "rename_method_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_TYPE_WIZARD_PAGE= PREFIX + "rename_type_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_TYPE_ERROR_WIZARD_PAGE= PREFIX + "rename_type_error_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_FIELD_WIZARD_PAGE= PREFIX + "rename_field_wizard_page_context"; //$NON-NLS-1$
public static final String RENAME_FIELD_ERROR_WIZARD_PAGE= PREFIX + "rename_field_error_wizard_page_context"; //$NON-NLS-1$
public static final String SEF_WIZARD_PAGE= PREFIX + "self_encapsulate_field_wizard_page_context"; //$NON-NLS-1$
// reused ui-blocks
public static final String BUILD_PATH_BLOCK= PREFIX + "build_paths_context"; //$NON-NLS-1$
public static final String SOURCE_ATTACHMENT_BLOCK= PREFIX + "source_attachment_context"; //$NON-NLS-1$
}
|
11,109 |
Bug 11109 F1 no longer works in Packages view
|
new context ID?
|
resolved fixed
|
902f54b
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T10:32:04Z | 2002-03-11T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.FileTransfer;
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.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.Action;
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.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
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.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenPerspectiveMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.internal.framelist.BackAction;
import org.eclipse.ui.views.internal.framelist.ForwardAction;
import org.eclipse.ui.views.internal.framelist.FrameList;
import org.eclipse.ui.views.internal.framelist.GoIntoAction;
import org.eclipse.ui.views.internal.framelist.UpAction;
import org.eclipse.search.ui.IWorkingSet;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
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.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
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.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.DeleteAction;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener {
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_SHOWLIBRARIES = "showLibraries"; //$NON-NLS-1$
static final String TAG_SHOWBINARIES = "showBinaries"; //$NON-NLS-1$
static final String TAG_WORKINGSET = "workingset"; //$NON-NLS-1$
private JavaElementPatternFilter fPatternFilter= new JavaElementPatternFilter();
private LibraryFilter fLibraryFilter= new LibraryFilter();
private BinaryProjectFilter fBinaryFilter= new BinaryProjectFilter();
private WorkingSetFilter fWorkingSetFilter= new WorkingSetFilter();
private MemberFilterActionGroup fMemberFilterActionGroup;
private ProblemTreeViewer fViewer;
private StandardJavaUILabelProvider fJavaElementLabelProvider;
private PackagesFrameSource fFrameSource;
private FrameList fFrameList;
private ContextMenuGroup[] fStandardGroups;
private Menu fContextMenu;
private OpenResourceAction fOpenCUAction;
private Action fOpenToAction;
private Action fShowTypeHierarchyAction;
private Action fShowNavigatorAction;
private PropertyDialogAction fPropertyDialogAction;
private RefactoringAction fDeleteAction;
private RefreshAction fRefreshAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private GoIntoAction fZoomInAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private AddBookmarkAction fAddBookmarkAction;
private FilterSelectionAction fFilterAction;
private ShowLibrariesAction fShowLibrariesAction;
private ShowBinariesAction fShowBinariesAction;
private FilterWorkingSetAction fFilterWorkingSetAction;
private RemoveWorkingSetFilterAction fRemoveWorkingSetAction;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
public PackageExplorerPart() {
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/**
* Initializes the default preferences
*/
public static void initDefaults(IPreferenceStore store) {
store.setDefault(TAG_SHOWLIBRARIES, true);
store.setDefault(TAG_SHOWBINARIES, true);
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fViewer != null)
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fViewer);
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
fViewer.setContentProvider(new JavaElementContentProvider(showCUChildren, false));
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fViewer);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fJavaElementLabelProvider=
new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
fViewer.setLabelProvider(new DecoratingLabelProvider(
fJavaElementLabelProvider, getViewSite().getDecoratorManager())
);
fViewer.setSorter(new JavaElementSorter());
fViewer.addFilter(new EmptyInnerPackageFilter());
fViewer.setUseHashlookup(true);
fViewer.addFilter(fPatternFilter);
fViewer.addFilter(fLibraryFilter);
fMemberFilterActionGroup= new MemberFilterActionGroup(fViewer, "PackageView"); // adds filter
fViewer.addFilter(fWorkingSetFilter);
if(fMemento != null)
restoreFilters();
else
initFilterFromPreferences();
// Set input after filter and sorter has been set. This avoids resorting
// and refiltering.
fViewer.setInput(findInputElement());
initDragAndDrop();
initFrameList();
initKeyListener();
updateTitle();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
getSite().registerContextMenu(menuMgr, fViewer);
makeActions(); // call before registering for selection changes
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick(event);
}
});
getSite().setSelectionProvider(fViewer);
getSite().getPage().addPartListener(fPartListener);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
// Set help for the view
WorkbenchHelp.setHelp(fViewer.getControl(), IJavaHelpContextIds.MEMBERS_VIEW);
fillActionBars();
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
actionBars.updateActionBars();
IMenuManager menu= actionBars.getMenuManager();
menu.add(fFilterAction);
menu.add(fShowLibrariesAction);
//menu.add(fShowBinariesAction);
menu.add(fFilterWorkingSetAction);
menu.add(fRemoveWorkingSetAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
private void fillToolBar(IToolBarManager toolBar) {
toolBar.removeAll();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
if (JavaBasePreferencePage.showCompilationUnitChildren()) {
toolBar.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(toolBar);
}
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
IWorkingSet ws= fWorkingSetFilter.getWorkingSet();
if (ws == null)
return result;
String wsstr= "Working Set: "+ws.getName();
if (result.length() == 0)
return wsstr;
return result + " - " + wsstr;
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Sets the working set to be used for filtering this part
*/
public void setWorkingSet(IWorkingSet ws) {
fWorkingSetFilter.setWorkingSet(ws);
firePropertyChange(IWorkbenchPart.PROP_TITLE);
fFilterWorkingSetAction.setChecked(ws != null);
fRemoveWorkingSetAction.setEnabled(ws != null);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
Object element= selection.getFirstElement();
fPropertyDialogAction.selectionChanged(selection);
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// updateActions(selection);
if (selection.size() == 1 && fViewer.isExpandable(element))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
addGotoMenu(menu);
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction);
addOpenWithMenu(menu, selection);
addOpenToMenu(menu, selection);
addRefactoring(menu);
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
if (fAddBookmarkAction.canOperateOnSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddBookmarkAction);
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
fRefreshAction.selectionChanged(selection);
menu.add(new Separator());
if (fPropertyDialogAction.isApplicableForSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
void addGotoMenu(IMenuManager menu) {
MenuManager gotoMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.gotoTitle")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, gotoMenu);
gotoMenu.add(fBackAction);
gotoMenu.add(fForwardAction);
gotoMenu.add(fUpAction);
gotoMenu.add(fGotoTypeAction);
gotoMenu.add(fGotoPackageAction);
}
private void makeActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenCUAction= new OpenResourceAction(provider);
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
// fShowTypeHierarchyAction= new ShowTypeHierarchyAction(provider);
fShowNavigatorAction= new ShowInNavigatorAction(provider);
fAddBookmarkAction= new AddBookmarkAction(provider);
fStandardGroups= new ContextMenuGroup[] {
new BuildGroup(),
new ReorgGroup(),
new GenerateGroup(),
new JavaSearchGroup()
};
fDeleteAction= new DeleteAction(provider);
fRefreshAction= new RefreshAction(getShell());
fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$
fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$
fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$
fBackAction= new BackAction(fFrameList);
fForwardAction= new ForwardAction(fFrameList);
fZoomInAction= new GoIntoAction(fFrameList);
fUpAction= new UpAction(fFrameList);
fGotoTypeAction= new GotoTypeAction(this);
fGotoPackageAction= new GotoPackageAction(this);
IActionBars actionService= getViewSite().getActionBars();
actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction);
ReorgGroup.addGlobalReorgActions(actionService, getSelectionProvider());
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) {
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable) selection.getFirstElement();
IResource resource= (IResource)element.getAdapter(IResource.class);
if ((resource instanceof IContainer)) {
// Create a menu flyout.
MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$
submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource));
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE;
final LocalSelectionTransfer lt= LocalSelectionTransfer.getInstance();
Transfer[] transfers= new Transfer[] {
lt,
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
/**
* Handles double clicks in viewer.
* Opens editor if file double-clicked.
*/
private void handleDoubleClick(DoubleClickEvent event) {
IStructuredSelection s= (IStructuredSelection) event.getSelection();
Object element= s.getFirstElement();
if (fOpenCUAction.isEnabled()) {
fOpenCUAction.run();
return;
}
if (fViewer.isExpandable(element)) {
if (JavaBasePreferencePage.doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
fViewer.setExpandedState(element, !fViewer.getExpandedState(element));
//expandMainType(element);
}
}
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel= (IStructuredSelection) event.getSelection();
//updateGlobalActions(sel);
fZoomInAction.update();
linkToEditor(sel);
}
public void selectReveal(ISelection selection) {
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
}
private ISelection convertSelection(ISelection s) {
List converted= new ArrayList();
if (s instanceof StructuredSelection) {
Object[] elements= ((StructuredSelection)s).toArray();
for (int i= 0; i < elements.length; i++) {
Object e= elements[i];
if (e instanceof IJavaElement)
converted.add(e);
else if (e instanceof IResource) {
IJavaElement element= JavaCore.create((IResource)e);
if (element != null)
converted.add(element);
else
converted.add(e);
}
}
}
return new StructuredSelection(converted.toArray());
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return JavaBasePreferencePage.linkPackageSelectionToEditor();
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
//if (!isLinkingEnabled())
// return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveScrollState(memento, fViewer.getTree());
savePatternFilterState(memento);
saveFilterState(memento);
saveWorkingSetState(memento);
saveMemberFilterState(memento);
}
protected void saveFilterState(IMemento memento) {
boolean showLibraries= getLibraryFilter().getShowLibraries();
String show= "true"; //$NON-NLS-1$
if (!showLibraries)
show= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWLIBRARIES, show);
//save binary filter
boolean showBinaries= getBinaryFilter().getShowBinaries();
String showBinString= "true"; //$NON-NLS-1$
if (!showBinaries)
showBinString= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWBINARIES, showBinString);
}
protected void savePatternFilterState(IMemento memento) {
String filters[] = getPatternFilter().getPatterns();
if(filters.length > 0) {
IMemento filtersMem = memento.createChild(TAG_FILTERS);
for (int i = 0; i < filters.length; i++){
IMemento child = filtersMem.createChild(TAG_FILTER);
child.putString(TAG_ELEMENT,filters[i]);
}
}
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
protected void saveWorkingSetState(IMemento memento) {
IWorkingSet ws= getWorkingSetFilter().getWorkingSet();
if (ws != null) {
memento.putString(TAG_WORKINGSET, ws.getName());
}
}
/**
* Saves the state of the filter actions
*/
public void saveMemberFilterState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
}
void restoreState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
restoreScrollState(memento, fViewer.getTree());
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
doKeyPressed(event);
}
});
}
private void doKeyPressed(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} else if (key == SWT.F4) {
OpenTypeHierarchyUtil.open(getSelection(), getSite().getWorkbenchWindow());
} else if (key == SWT.F3) {
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
fOpenCUAction.run();
} else if (event.character == SWT.DEL){
fDeleteAction.update();
if (fDeleteAction.isEnabled())
fDeleteAction.run();
}
}
void initFrameList() {
fFrameSource= new PackagesFrameSource(this);
fFrameList= new FrameList(fFrameSource);
fFrameSource.connectTo(fFrameList);
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IMember) {
IMember m= (IMember)o;
if (element.equals(m.getCompilationUnit()))
return;
if (element.equals(m.getClassFile()))
return;
}
}
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
}
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the pattern filter for this view.
* @return the pattern filter
*/
JavaElementPatternFilter getPatternFilter() {
return fPatternFilter;
}
/**
* Returns the library filter for this view.
* @return the library filter
*/
LibraryFilter getLibraryFilter() {
return fLibraryFilter;
}
/**
* Returns the working set filter for this view.
* @return the working set filter
*/
WorkingSetFilter getWorkingSetFilter() {
return fWorkingSetFilter;
}
/**
* Returns the Binary filter for this view.
* @return the binary filter
*/
BinaryProjectFilter getBinaryFilter() {
return fBinaryFilter;
}
void restoreFilters() {
IMemento filtersMem= fMemento.getChild(TAG_FILTERS);
if(filtersMem != null) {
IMemento children[]= filtersMem.getChildren(TAG_FILTER);
String filters[]= new String[children.length];
for (int i = 0; i < children.length; i++) {
filters[i]= children[i].getString(TAG_ELEMENT);
}
getPatternFilter().setPatterns(filters);
} else {
getPatternFilter().setPatterns(new String[0]);
}
//restore library
String show= fMemento.getString(TAG_SHOWLIBRARIES);
if (show != null)
getLibraryFilter().setShowLibraries(show.equals("true")); //$NON-NLS-1$
else
initLibraryFilterFromPreferences();
//restore binary fileter
String showbin= fMemento.getString(TAG_SHOWBINARIES);
if (showbin != null)
getBinaryFilter().setShowBinaries(showbin.equals("true")); //$NON-NLS-1$
else
initBinaryFilterFromPreferences();
//restore working set
String workingSetName= fMemento.getString(TAG_WORKINGSET);
if (workingSetName != null) {
IWorkingSet ws= SearchUI.findWorkingSet(workingSetName);
if (ws != null) {
getWorkingSetFilter().setWorkingSet(ws);
}
}
fMemberFilterActionGroup.restoreState(fMemento);
}
void initFilterFromPreferences() {
initBinaryFilterFromPreferences();
initLibraryFilterFromPreferences();
}
void initLibraryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean show= plugin.getPreferenceStore().getBoolean(TAG_SHOWLIBRARIES);
getLibraryFilter().setShowLibraries(show);
}
void initBinaryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean showbin= plugin.getPreferenceStore().getBoolean(TAG_SHOWBINARIES);
getBinaryFilter().setShowBinaries(showbin);
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= getViewer().getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
if (decorator == null)
fViewer.setLabelProvider(fJavaElementLabelProvider);
else
fViewer.setLabelProvider(new DecoratingLabelProvider(fJavaElementLabelProvider, decorator));
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (event.getProperty() == JavaBasePreferencePage.SHOW_CU_CHILDREN) {
IActionBars actionBars= getViewSite().getActionBars();
fillToolBar(actionBars.getToolBarManager());
actionBars.updateActionBars();
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
((JavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
}
|
10,593 |
Bug 10593 Jar export should add ".jar" suffix if not specified
|
Build 20020228 - select some files - export them using the jar export - enter "test" as the jar name - it creates a jar file called "test" It should use "test.jar".
|
verified fixed
|
b9806a6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T15:33:51Z | 2002-03-01T16:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
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.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
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.custom.BusyIndicator;
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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.WizardExportResourcesPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
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.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.packageview.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
/**
* Page 1 of the JAR Package wizard
*/
public class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
private JarPackage fJarPackage;
private IStructuredSelection fInitialSelection;
private CheckboxTreeAndListGroup fInputGroup;
private boolean fFirstTime= true;
// widgets
private Text fSourceNameField;
private Button fSourceBrowseButton;
private Button fExportClassFilesCheckbox;
private Button fExportJavaFilesCheckbox;
private Combo fDestinationNamesCombo;
private Button fDestinationBrowseButton;
private Button fCompressCheckbox;
private Button fOverwriteCheckbox;
private Composite fDescriptionFileGroup;
private Button fSaveDescriptionCheckbox;
private Label fDescriptionFileLabel;
private Text fDescriptionFileText;
private Button fDescriptionFileBrowseButton;
// dialog store id constants
private final static String PAGE_NAME= "JarPackageWizardPage"; //$NON-NLS-1$
private final static String STORE_EXPORT_CLASS_FILES= PAGE_NAME + ".EXPORT_CLASS_FILES"; //$NON-NLS-1$
private final static String STORE_EXPORT_JAVA_FILES= PAGE_NAME + ".EXPORT_JAVA_FILES"; //$NON-NLS-1$
private final static String STORE_DESTINATION_NAMES= PAGE_NAME + ".DESTINATION_NAMES_ID"; //$NON-NLS-1$
private final static String STORE_COMPRESS= PAGE_NAME + ".COMPRESS"; //$NON-NLS-1$
private final static String STORE_OVERWRITE= PAGE_NAME + ".OVERWRITE"; //$NON-NLS-1$
// other constants
private final static int SIZING_SELECTION_WIDGET_WIDTH= 400;
private final static int SIZING_SELECTION_WIDGET_HEIGHT= 150;
/**
* Create an instance of this class
*/
public JarPackageWizardPage(JarPackage jarPackage, IStructuredSelection selection) {
super(PAGE_NAME, selection);
setTitle(JarPackagerMessages.getString("JarPackageWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarPackageWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
fInitialSelection= selection;
}
/*
* Method declared on IDialogPage.
*/
public void createControl(final 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));
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whatToExport.label")); //$NON-NLS-1$
createInputGroup(composite);
createExportTypeGroup(composite);
new Label(composite, SWT.NONE); // vertical spacer
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whereToExport.label")); //$NON-NLS-1$
createDestinationGroup(composite);
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.options.label")); //$NON-NLS-1$
createOptionsGroup(composite);
restoreResourceSpecificationWidgetValues(); // superclass API defines this hook
restoreWidgetValues();
if (fInitialSelection != null)
BusyIndicator.showWhile(parent.getDisplay(), new Runnable() {
public void run() {
setupBasedOnInitialSelections();
}
});
setControl(composite);
update();
giveFocusToDestination();
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JARPACKAGER_WIZARD_PAGE);
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createOptionsGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
optionsGroup.setLayout(layout);
fCompressCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fCompressCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.compress.text")); //$NON-NLS-1$
fCompressCheckbox.addListener(SWT.Selection, this);
fOverwriteCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fOverwriteCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.overwrite.text")); //$NON-NLS-1$
fOverwriteCheckbox.addListener(SWT.Selection, this);
}
/**
* Answer the contents of the destination specification widget. If this
* value does not have the required suffix then add it first.
*
* @return java.lang.String
*/
protected String getDestinationValue() {
String requiredSuffix= getOutputSuffix();
String destinationText= fDestinationNamesCombo.getText().trim();
if (!destinationText.toLowerCase().endsWith(requiredSuffix.toLowerCase()))
destinationText += requiredSuffix;
return destinationText;
}
/**
* Answer the string to display in self as the destination type
*
* @return java.lang.String
*/
protected String getDestinationLabel() {
return JarPackagerMessages.getString("JarPackageWizardPage.destination.label"); //$NON-NLS-1$
}
/**
* Answer the suffix that files exported from this wizard must have.
* If this suffix is a file extension (which is typically the case)
* then it must include the leading period character.
*
* @return java.lang.String
*/
protected String getOutputSuffix() {
return "." + JarPackage.EXTENSION; //$NON-NLS-1$
}
/**
* Returns an iterator over this page's collection of currently-specified
* elements to be exported. This is the primary element selection facility
* accessor for subclasses.
*
* @return an iterator over the collection of elements currently selected for export
*/
protected Iterator getSelectedResourcesIterator() {
return fInputGroup.getAllCheckedListItems();
}
/**
* 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() {
// update directory names history
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
directoryNames= new String[0];
directoryNames= addToHistory(directoryNames, getDestinationValue());
settings.put(STORE_DESTINATION_NAMES, directoryNames);
settings.put(STORE_EXPORT_CLASS_FILES, fJarPackage.areClassFilesExported());
settings.put(STORE_EXPORT_JAVA_FILES, fJarPackage.areJavaFilesExported());
// options
settings.put(STORE_COMPRESS, fJarPackage.isCompressed());
settings.put(STORE_OVERWRITE, fJarPackage.allowOverwrite());
}
// 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 (!fJarPackage.isUsedToInitialize())
initializeJarPackage();
fExportClassFilesCheckbox.setSelection(fJarPackage.areClassFilesExported());
fExportJavaFilesCheckbox.setSelection(fJarPackage.areJavaFilesExported());
// destination
if (fJarPackage.getJarLocation().isEmpty())
fDestinationNamesCombo.setText(""); //$NON-NLS-1$
else
fDestinationNamesCombo.setText(fJarPackage.getJarLocation().toOSString());
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
if (! fDestinationNamesCombo.getText().equals(directoryNames[0]))
fDestinationNamesCombo.add(fDestinationNamesCombo.getText());
for (int i= 0; i < directoryNames.length; i++)
fDestinationNamesCombo.add(directoryNames[i]);
}
// options
fCompressCheckbox.setSelection(fJarPackage.isCompressed());
fOverwriteCheckbox.setSelection(fJarPackage.allowOverwrite());
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(settings.getBoolean(STORE_EXPORT_CLASS_FILES));
fJarPackage.setExportJavaFiles(settings.getBoolean(STORE_EXPORT_JAVA_FILES));
// options
fJarPackage.setCompress(settings.getBoolean(STORE_COMPRESS));
fJarPackage.setOverwrite(settings.getBoolean(STORE_OVERWRITE));
// destination
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
fJarPackage.setJarLocation(getPathFromString(directoryNames[0]));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
// destination
fJarPackage.setJarLocation(getPathFromString(fDestinationNamesCombo.getText()));
// options
fJarPackage.setCompress(fCompressCheckbox.getSelection());
fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
}
protected IPath getPathFromString(String text) {
return new Path(text).makeAbsolute();
}
/**
* Returns a boolean indicating whether the passed File handle is
* is valid and available for use.
*
* @return boolean
*/
protected boolean ensureTargetFileIsValid(File targetFile) {
if (targetFile.exists() && targetFile.isDirectory()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (targetFile.exists()) {
if (!targetFile.canWrite()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.jarFileExistsAndNotWritable")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
}
return true;
}
/*
* Overrides method from WizardExportPage
*/
protected void createDestinationGroup(Composite parent) {
initializeDialogUnits(parent);
// destination specification group
Composite destinationSelectionGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
destinationSelectionGroup.setLayout(layout);
destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
new Label(destinationSelectionGroup, SWT.NONE).setText(getDestinationLabel());
// destination name entry field
fDestinationNamesCombo= new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
fDestinationNamesCombo.addListener(SWT.Modify, this);
fDestinationNamesCombo.addListener(SWT.Selection, this);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= SIZING_TEXT_FIELD_WIDTH;
fDestinationNamesCombo.setLayoutData(data);
// destination browse button
fDestinationBrowseButton= new Button(destinationSelectionGroup, SWT.PUSH);
fDestinationBrowseButton.setText(JarPackagerMessages.getString("JarPackageWizardPage.browseButton.text")); //$NON-NLS-1$
fDestinationBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
SWTUtil.setButtonDimensionHint(fDestinationBrowseButton);
fDestinationBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleDestinationBrowseButtonPressed();
}
});
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDescriptionFileBrowseButtonPressed() {
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getDescriptionLocation()));
if (dialog.open() == dialog.OK) {
IPath path= dialog.getResult();
path= path.removeFileExtension().addFileExtension(JarPackage.DESCRIPTION_EXTENSION);
fDescriptionFileText.setText(path.toString());
}
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog= new FileDialog(getContainer().getShell(), SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.jar"}); //$NON-NLS-1$
String currentSourceString= getDestinationValue();
int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
dialog.setFileName(currentSourceString.substring(lastSeparatorIndex + 1, currentSourceString.length()));
}
else
dialog.setFileName(currentSourceString);
String selectedFileName= dialog.open();
if (selectedFileName != null) {
IPath path= getPathFromString(selectedFileName);
if (path.lastSegment().equals(getOutputSuffix()))
selectedFileName= ""; //$NON-NLS-1$
fDestinationNamesCombo.setText(selectedFileName);
}
}
/**
* 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;
}
/**
* Creates the checkbox tree and list for selecting resources.
*
* @param parent the parent control
*/
protected void createInputGroup(Composite parent) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider treeContentProvider=
new JavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
fInputGroup= new CheckboxTreeAndListGroup(
parent,
JavaCore.create(JavaPlugin.getDefault().getWorkspace().getRoot()),
treeContentProvider,
new JavaElementLabelProvider(labelFlags),
new BaseJavaElementContentProvider(),
new JavaElementLabelProvider(labelFlags),
SWT.NONE,
SIZING_SELECTION_WIDGET_WIDTH,
SIZING_SELECTION_WIDGET_HEIGHT);
fInputGroup.addTreeFilter(new EmptyInnerPackageFilter());
fInputGroup.setTreeSorter(new JavaElementSorter());
fInputGroup.setListSorter(new JavaElementSorter());
fInputGroup.addTreeFilter(new ContainerFilter(ContainerFilter.FILTER_NON_CONTAINERS));
fInputGroup.addTreeFilter(new LibraryFilter());
fInputGroup.addListFilter(new ContainerFilter(ContainerFilter.FILTER_CONTAINERS));
fInputGroup.getTree().addListener(SWT.MouseUp, this);
fInputGroup.getTable().addListener(SWT.MouseUp, this);
}
/**
* Creates the export type controls.
*
* @param parent the parent control
*/
protected void createExportTypeGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout optionsLayout= new GridLayout();
optionsLayout.marginHeight= 0;
optionsGroup.setLayout(optionsLayout);
fExportClassFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportClassFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportClassFiles.text")); //$NON-NLS-1$
fExportClassFilesCheckbox.addListener(SWT.Selection, this);
fExportJavaFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportJavaFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportJavaFiles.text")); //$NON-NLS-1$
fExportJavaFilesCheckbox.addListener(SWT.Selection, this);
}
/**
* Updates the enablements of this page's controls. Subclasses may extend.
*/
protected void updateWidgetEnablements() {
}
/*
* Overrides method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
setErrorMessage(null);
return super.determinePageCompletion();
}
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
protected void update() {
updateModel();
updateWidgetEnablements();
updatePageCompletion();
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateDestinationGroup() {
if (fDestinationNamesCombo.getText().length() == 0) {
return false;
}
if (fJarPackage.getJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
return ensureTargetFileIsValid(fJarPackage.getJarLocation().toFile());
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateOptionsGroup() {
return true;
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateSourceGroup() {
if (!fExportClassFilesCheckbox.getSelection()
&& !fExportJavaFilesCheckbox.getSelection()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.noExportTypeChecked")); //$NON-NLS-1$
return false;
}
if (getSelectedResources().size() == 0)
return false;
if (fExportClassFilesCheckbox.getSelection() || !fExportJavaFilesCheckbox.getSelection())
return true;
// No class file export - check if there are source files
Iterator iter= getSelectedResourcesIterator();
while (iter.hasNext()) {
if (!(iter.next() instanceof IClassFile))
return true;
}
return false;
}
/*
* Overwrides method from WizardExportPage
*/
protected IPath getResourcePath() {
return getPathFromText(fSourceNameField);
}
/**
* 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
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Set the current input focus to self's destination entry field
*/
protected void giveFocusToDestination() {
fDestinationNamesCombo.setFocus();
}
/*
* Overrides method from WizardExportResourcePage
*/
protected void setupBasedOnInitialSelections() {
Iterator enum= fInitialSelection.iterator();
while (enum.hasNext()) {
Object selectedElement= enum.next();
if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile || selectedElement instanceof IFile)
fInputGroup.initialCheckListItem(selectedElement);
else
fInputGroup.initialCheckTreeItem(selectedElement);
}
TreeItem[] items= fInputGroup.getTree().getItems();
int i= 0;
while (i < items.length && !items[i].getChecked())
i++;
if (i < items.length) {
fInputGroup.getTree().setSelection(new TreeItem[] {items[i]});
fInputGroup.getTree().showSelection();
fInputGroup.populateListViewer(items[i].getData());
}
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
/*
* Method declared on IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
if (getControl() != null)
updatePageCompletion();
}
void setSelectedElementsWithoutContainedChildren() {
Set closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
closure.addAll(getExportedNonContainers());
fJarPackage.setSelectedElementsClosure(closure);
}
private Set removeContainedChildren(Set elements) {
Set newList= new HashSet(elements.size());
Set javaElementResources= getCorrespondingContainers(elements);
Iterator iter= elements.iterator();
boolean removedOne= false;
while (iter.hasNext()) {
Object element= iter.next();
Object parent;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement) {
parent= ((IJavaElement)element).getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
try {
if (pkgRoot.getCorrespondingResource() instanceof IProject)
parent= pkgRoot.getJavaProject();
} catch (JavaModelException ex) {
// leave parent as is
}
}
}
else {
// unknown type
newList.add(element);
continue;
}
if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
removedOne= true;
else
newList.add(element);
}
if (removedOne)
return removeContainedChildren(newList);
else
return newList;
}
private Set getExportedNonContainers() {
Set whiteCheckedTreeItems= fInputGroup.getWhiteCheckedTreeItems();
Set exportedNonContainers= new HashSet(whiteCheckedTreeItems.size());
Set javaElementResources= getCorrespondingContainers(whiteCheckedTreeItems);
Iterator iter= fInputGroup.getAllCheckedListItems();
while (iter.hasNext()) {
Object element= iter.next();
Object parent= null;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement)
parent= ((IJavaElement)element).getParent();
if (!whiteCheckedTreeItems.contains(parent) && !javaElementResources.contains(parent))
exportedNonContainers.add(element);
}
return exportedNonContainers;
}
/*
* Create a list with the folders / projects that correspond
* to the Java elements (Java project, package, package root)
*/
private Set getCorrespondingContainers(Set elements) {
Set javaElementResources= new HashSet(elements.size());
Iterator iter= elements.iterator();
while (iter.hasNext()) {
Object element= iter.next();
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
// exclude default package since it is covered by the root
if (!(type == IJavaElement.PACKAGE_FRAGMENT && ((IPackageFragment)element).isDefaultPackage())) {
Object resource;
try {
resource= je.getCorrespondingResource();
} catch (JavaModelException ex) {
resource= null;
}
if (resource != null)
javaElementResources.add(resource);
}
}
}
}
return javaElementResources;
}
}
|
10,339 |
Bug 10339 Refactoring: Pull up should have "select/deselect all" options
|
When selecting multiple methods for pull up, it would be nice to have the option to select/deselect all.
|
resolved fixed
|
bc30327
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T15:57:10Z | 2002-02-27T03:20:00Z |
org.eclipse.jdt.ui/ui
| |
10,339 |
Bug 10339 Refactoring: Pull up should have "select/deselect all" options
|
When selecting multiple methods for pull up, it would be nice to have the option to select/deselect all.
|
resolved fixed
|
bc30327
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T15:57:10Z | 2002-02-27T03:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/PullUpInputPage.java
| |
11,172 |
Bug 11172 organize imports pref page - buttons have incorrect sizes
|
20020307 + latest as in the summary: buttons from the organize imports pref page have incorrect sizes
|
verified fixed
|
b312140
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T16:16:39Z | 2002-03-12T13:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizePreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.IStatus;
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.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
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.IListAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
/*
* The page for setting the organize import settings
*/
public class ImportOrganizePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// Preference store keys
private static final String PREF_IMPORTORDER= JavaUI.ID_PLUGIN + ".importorder"; //$NON-NLS-1$
private static final String PREF_ONDEMANDTHRESHOLD= JavaUI.ID_PLUGIN + ".ondemandthreshold"; //$NON-NLS-1$
private static final String PREF_IGNORELOWERCASE= JavaUI.ID_PLUGIN + ".ignorelowercasenames"; //$NON-NLS-1$
private static final String PREF_LASTLOADPATH= JavaUI.ID_PLUGIN + ".importorder.loadpath"; //$NON-NLS-1$
private static final String PREF_LASTSAVEPATH= JavaUI.ID_PLUGIN + ".importorder.savepath"; //$NON-NLS-1$
public static String[] getImportOrderPreference() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
String str= prefs.getString(PREF_IMPORTORDER);
if (str != null) {
return unpackOrderList(str);
}
return new String[0];
}
private static String[] unpackOrderList(String str) {
StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < nTokens; i++) {
res[i]= tok.nextToken();
}
return res;
}
private static String packOrderList(List orderList) {
StringBuffer buf= new StringBuffer();
for (int i= 0; i < orderList.size(); i++) {
buf.append((String) orderList.get(i));
buf.append(';');
}
return buf.toString();
}
public static int getImportNumberThreshold() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
int threshold= prefs.getInt(PREF_ONDEMANDTHRESHOLD);
if (threshold < 0) {
threshold= Integer.MAX_VALUE;
}
return threshold;
}
public static boolean doIgnoreLowerCaseNames() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_IGNORELOWERCASE);
}
/**
* Initializes the default values of this page in the preference bundle.
* Will be called on startup of the JavaPlugin
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_IMPORTORDER, "java;javax;com"); //$NON-NLS-1$
prefs.setDefault(PREF_ONDEMANDTHRESHOLD, 99);
}
private static class ImportOrganizeLabelProvider extends LabelProvider {
private static final Image PCK_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKAGE);
public Image getImage(Object element) {
return PCK_ICON;
}
}
private class ImportOrganizeAdapter implements IListAdapter, IDialogFieldListener {
public void customButtonPressed(DialogField field, int index) {
doButtonPressed(index);
}
public void selectionChanged(DialogField field) {
doSelectionChanged();
}
public void dialogFieldChanged(DialogField field) {
if (field == fThresholdField) {
doThresholdChanged();
}
}
}
private ListDialogField fOrderListField;
private StringDialogField fThresholdField;
private SelectionButtonDialogField fIgnoreLowerCaseTypesField;
public ImportOrganizePreferencePage() {
super();
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("ImportOrganizePreferencePage.description")); //$NON-NLS-1$
String[] buttonLabels= new String[] {
/* 0 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.add.button"), //$NON-NLS-1$
/* 1 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.edit.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.up.button"), //$NON-NLS-1$
/* 4 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.down.button"), //$NON-NLS-1$
/* 5 */ null,
/* 6 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.remove.button"), //$NON-NLS-1$
/* 7 */ null,
/* 8 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.load.button"), //$NON-NLS-1$
/* 9 */ JavaUIMessages.getString("ImportOrganizePreferencePage.order.save.button") //$NON-NLS-1$
};
ImportOrganizeAdapter adapter= new ImportOrganizeAdapter();
fOrderListField= new ListDialogField(adapter, buttonLabels, new ImportOrganizeLabelProvider());
fOrderListField.setDialogFieldListener(adapter);
fOrderListField.setLabelText(JavaUIMessages.getString("ImportOrganizePreferencePage.order.label")); //$NON-NLS-1$
fOrderListField.setUpButtonIndex(3);
fOrderListField.setDownButtonIndex(4);
fOrderListField.setRemoveButtonIndex(6);
fOrderListField.enableButton(1, false);
fThresholdField= new StringDialogField();
fThresholdField.setDialogFieldListener(adapter);
fThresholdField.setLabelText(JavaUIMessages.getString("ImportOrganizePreferencePage.threshold.label")); //$NON-NLS-1$
fIgnoreLowerCaseTypesField= new SelectionButtonDialogField(SWT.CHECK);
fIgnoreLowerCaseTypesField.setLabelText(JavaUIMessages.getString("ImportOrganizePreferencePage.ignoreLowerCase.label"));
}
/**
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
// added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.ORGANIZE_IMPORTS_PREFERENCE_PAGE);
}
protected Control createContents(Composite parent) {
initialize(getImportOrderPreference(), getImportNumberThreshold(), doIgnoreLowerCaseNames());
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 2;
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
fOrderListField.doFillIntoGrid(composite, 3);
LayoutUtil.setHorizontalSpan(fOrderListField.getLabelControl(null), 2);
LayoutUtil.setHorizontalGrabbing(fOrderListField.getLabelControl(null));
fThresholdField.doFillIntoGrid(composite, 2);
((GridData) fThresholdField.getTextControl(null).getLayoutData()).grabExcessHorizontalSpace= false;
fIgnoreLowerCaseTypesField.doFillIntoGrid(composite, 2);
return composite;
}
private void initialize(String[] importOrder, int threshold, boolean ignoreLowerCase) {
fOrderListField.removeAllElements();
for (int i= 0; i < importOrder.length; i++) {
fOrderListField.addElement(importOrder[i]);
}
fThresholdField.setText(String.valueOf(threshold));
fIgnoreLowerCaseTypesField.setSelection(ignoreLowerCase);
}
private void doThresholdChanged() {
StatusInfo status= new StatusInfo();
String thresholdString= fThresholdField.getText();
try {
int threshold= Integer.parseInt(thresholdString);
if (threshold < 0) {
status.setError(JavaUIMessages.getString("ImportOrganizePreferencePage.error.invalidthreshold")); //$NON-NLS-1$
}
} catch (NumberFormatException e) {
status.setError(JavaUIMessages.getString("ImportOrganizePreferencePage.error.invalidthreshold")); //$NON-NLS-1$
}
updateStatus(status);
}
private void doButtonPressed(int index) {
if (index == 0) { // add new
List existing= fOrderListField.getElements();
ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing);
if (dialog.open() == dialog.OK) {
fOrderListField.addElement(dialog.getResult());
}
} else if (index == 1) { // edit
List selected= fOrderListField.getSelectedElements();
if (selected.isEmpty()) {
return;
}
String editedEntry= (String) selected.get(0);
List existing= fOrderListField.getElements();
existing.remove(editedEntry);
ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing);
dialog.setInitialString(editedEntry);
if (dialog.open() == dialog.OK) {
fOrderListField.replaceElement(editedEntry, dialog.getResult());
}
} else if (index == 8) { // load
List order= loadImportOrder();
if (order != null) {
fOrderListField.setElements(order);
}
} else if (index == 9) { // save
saveImportOrder(fOrderListField.getElements());
}
}
private void doSelectionChanged() {
// update enable state of the edit button
List selected= fOrderListField.getSelectedElements();
fOrderListField.enableButton(1, selected.size() == 1);
}
/**
* The import order file is a property file with keys
* "0", "1" ... last entry.
* values must be valid package names
*/
private List loadFromProperties(Properties properties) {
ArrayList res= new ArrayList();
int nEntries= properties.size();
for (int i= 0 ; i < nEntries; i++) {
String curr= properties.getProperty(String.valueOf(i));
if (curr != null) {
if (JavaConventions.validatePackageName(curr).isOK()) {
res.add(curr);
} else {
return null;
}
} else {
return res;
}
}
return res;
}
private List loadImportOrder() {
FileDialog dialog= new FileDialog(getShell(), SWT.OPEN);
dialog.setText(JavaUIMessages.getString("ImportOrganizePreferencePage.loadDialog.title")); //$NON-NLS-1$)
dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$
String lastPath= getPreferenceStore().getString(PREF_LASTLOADPATH);
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
String fileName= dialog.open();
if (fileName != null) {
getPreferenceStore().putValue(PREF_LASTLOADPATH, dialog.getFilterPath());
Properties properties= new Properties();
FileInputStream fis= null;
try {
fis= new FileInputStream(fileName);
properties.load(fis);
List res= loadFromProperties(properties);
if (res != null) {
return res;
}
} catch (IOException e) {
JavaPlugin.log(e);
} finally {
if (fis != null) {
try { fis.close(); } catch (IOException e) {}
}
}
String title= JavaUIMessages.getString("ImportOrganizePreferencePage.loadDialog.error.title");
String message= JavaUIMessages.getString("ImportOrganizePreferencePage.loadDialog.error.message");
MessageDialog.openError(getShell(), title, message);
}
return null;
}
private void saveImportOrder(List elements) {
FileDialog dialog= new FileDialog(getShell(), SWT.SAVE);
dialog.setText(JavaUIMessages.getString("ImportOrganizePreferencePage.saveDialog.title")); //$NON-NLS-1$)
dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$
dialog.setFileName("example.importorder");
String lastPath= getPreferenceStore().getString(PREF_LASTSAVEPATH);
if (lastPath != null) {
dialog.setFilterPath(lastPath);
}
String fileName= dialog.open();
if (fileName != null) {
getPreferenceStore().putValue(PREF_LASTSAVEPATH, dialog.getFilterPath());
Properties properties= new Properties();
for (int i= 0; i < elements.size(); i++) {
properties.setProperty(String.valueOf(i), (String) elements.get(i));
}
FileOutputStream fos= null;
try {
fos= new FileOutputStream(fileName);
properties.store(fos, "Organize Import Order");
} catch (IOException e) {
JavaPlugin.log(e);
String title= JavaUIMessages.getString("ImportOrganizePreferencePage.saveDialog.error.title");
String message= JavaUIMessages.getString("ImportOrganizePreferencePage.saveDialog.error.message");
MessageDialog.openError(getShell(), title, message);
} finally {
if (fos != null) {
try { fos.close(); } catch (IOException e) {}
}
}
}
}
public void init(IWorkbench workbench) {
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
/**
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
String[] order;
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
String str= prefs.getDefaultString(PREF_IMPORTORDER);
if (str != null) {
order= unpackOrderList(str);
} else {
order= new String[0];
}
int threshold= prefs.getDefaultInt(PREF_ONDEMANDTHRESHOLD);
if (threshold < 0) {
threshold= Integer.MAX_VALUE;
}
boolean ignoreLowerCase= prefs.getDefaultBoolean(PREF_IGNORELOWERCASE);
initialize(order, threshold, ignoreLowerCase);
}
/**
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_IMPORTORDER, packOrderList(fOrderListField.getElements()));
prefs.setValue(PREF_ONDEMANDTHRESHOLD, fThresholdField.getText());
prefs.setValue(PREF_IGNORELOWERCASE, fIgnoreLowerCaseTypesField.isSelected());
return true;
}
}
|
10,170 |
Bug 10170 Externalize strings doesn't insert CR into properties file
|
If the properties file doesn't end with a CR, using externalize strings will result in two strings on the same line in the properties file. It should insert a CR before the new strings, if necesary.
|
resolved fixed
|
db4e625
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T16:28:16Z | 2002-02-25T15:13:20Z |
org.eclipse.jdt.ui/core
| |
10,170 |
Bug 10170 Externalize strings doesn't insert CR into properties file
|
If the properties file doesn't end with a CR, using externalize strings will result in two strings on the same line in the properties file. It should insert a CR before the new strings, if necesary.
|
resolved fixed
|
db4e625
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T16:28:16Z | 2002-02-25T15:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/nls/NLSRefactoring.java
| |
4,121 |
Bug 4121 JarExporter causes out of Sync (1GILQD5)
|
PA (8/17/01 2:03:29 PM) if you export a directory (project) and place the exported jar in the same directory (project) then you will get an out of sync message when you overwrite the exported jar-file the 2nd time. -> maybe the exported jar file should not include itself ? NOTES:
|
resolved fixed
|
5b22f41
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-12T19:47:43Z | 2001-10-11T03:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.File;
import java.util.HashSet;
import java.util.Iterator;
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.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
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.custom.BusyIndicator;
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.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.WizardExportResourcesPage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
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.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.packageview.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
/**
* Page 1 of the JAR Package wizard
*/
public class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
private JarPackage fJarPackage;
private IStructuredSelection fInitialSelection;
private CheckboxTreeAndListGroup fInputGroup;
private boolean fFirstTime= true;
// widgets
private Text fSourceNameField;
private Button fSourceBrowseButton;
private Button fExportClassFilesCheckbox;
private Button fExportJavaFilesCheckbox;
private Combo fDestinationNamesCombo;
private Button fDestinationBrowseButton;
private Button fCompressCheckbox;
private Button fOverwriteCheckbox;
private Composite fDescriptionFileGroup;
private Button fSaveDescriptionCheckbox;
private Label fDescriptionFileLabel;
private Text fDescriptionFileText;
private Button fDescriptionFileBrowseButton;
// dialog store id constants
private final static String PAGE_NAME= "JarPackageWizardPage"; //$NON-NLS-1$
private final static String STORE_EXPORT_CLASS_FILES= PAGE_NAME + ".EXPORT_CLASS_FILES"; //$NON-NLS-1$
private final static String STORE_EXPORT_JAVA_FILES= PAGE_NAME + ".EXPORT_JAVA_FILES"; //$NON-NLS-1$
private final static String STORE_DESTINATION_NAMES= PAGE_NAME + ".DESTINATION_NAMES_ID"; //$NON-NLS-1$
private final static String STORE_COMPRESS= PAGE_NAME + ".COMPRESS"; //$NON-NLS-1$
private final static String STORE_OVERWRITE= PAGE_NAME + ".OVERWRITE"; //$NON-NLS-1$
// other constants
private final static int SIZING_SELECTION_WIDGET_WIDTH= 400;
private final static int SIZING_SELECTION_WIDGET_HEIGHT= 150;
/**
* Create an instance of this class
*/
public JarPackageWizardPage(JarPackage jarPackage, IStructuredSelection selection) {
super(PAGE_NAME, selection);
setTitle(JarPackagerMessages.getString("JarPackageWizardPage.title")); //$NON-NLS-1$
setDescription(JarPackagerMessages.getString("JarPackageWizardPage.description")); //$NON-NLS-1$
fJarPackage= jarPackage;
fInitialSelection= selection;
}
/*
* Method declared on IDialogPage.
*/
public void createControl(final 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));
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whatToExport.label")); //$NON-NLS-1$
createInputGroup(composite);
createExportTypeGroup(composite);
new Label(composite, SWT.NONE); // vertical spacer
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.whereToExport.label")); //$NON-NLS-1$
createDestinationGroup(composite);
createPlainLabel(composite, JarPackagerMessages.getString("JarPackageWizardPage.options.label")); //$NON-NLS-1$
createOptionsGroup(composite);
restoreResourceSpecificationWidgetValues(); // superclass API defines this hook
restoreWidgetValues();
if (fInitialSelection != null)
BusyIndicator.showWhile(parent.getDisplay(), new Runnable() {
public void run() {
setupBasedOnInitialSelections();
}
});
setControl(composite);
update();
giveFocusToDestination();
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.JARPACKAGER_WIZARD_PAGE);
}
/**
* Create the export options specification widgets.
*
* @param parent org.eclipse.swt.widgets.Composite
*/
protected void createOptionsGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
optionsGroup.setLayout(layout);
fCompressCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fCompressCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.compress.text")); //$NON-NLS-1$
fCompressCheckbox.addListener(SWT.Selection, this);
fOverwriteCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fOverwriteCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.overwrite.text")); //$NON-NLS-1$
fOverwriteCheckbox.addListener(SWT.Selection, this);
}
/**
* Answer the contents of the destination specification widget. If this
* value does not have the required suffix then add it first.
*
* @return java.lang.String
*/
protected String getDestinationValue() {
String destinationText= fDestinationNamesCombo.getText().trim();
if (destinationText.indexOf('.') < 0)
destinationText += getOutputSuffix();
return destinationText;
}
/**
* Answer the string to display in self as the destination type
*
* @return java.lang.String
*/
protected String getDestinationLabel() {
return JarPackagerMessages.getString("JarPackageWizardPage.destination.label"); //$NON-NLS-1$
}
/**
* Answer the suffix that files exported from this wizard must have.
* If this suffix is a file extension (which is typically the case)
* then it must include the leading period character.
*
* @return java.lang.String
*/
protected String getOutputSuffix() {
return "." + JarPackage.EXTENSION; //$NON-NLS-1$
}
/**
* Returns an iterator over this page's collection of currently-specified
* elements to be exported. This is the primary element selection facility
* accessor for subclasses.
*
* @return an iterator over the collection of elements currently selected for export
*/
protected Iterator getSelectedResourcesIterator() {
return fInputGroup.getAllCheckedListItems();
}
/**
* 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() {
// update directory names history
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
directoryNames= new String[0];
directoryNames= addToHistory(directoryNames, getDestinationValue());
settings.put(STORE_DESTINATION_NAMES, directoryNames);
settings.put(STORE_EXPORT_CLASS_FILES, fJarPackage.areClassFilesExported());
settings.put(STORE_EXPORT_JAVA_FILES, fJarPackage.areJavaFilesExported());
// options
settings.put(STORE_COMPRESS, fJarPackage.isCompressed());
settings.put(STORE_OVERWRITE, fJarPackage.allowOverwrite());
}
// 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 (!fJarPackage.isUsedToInitialize())
initializeJarPackage();
fExportClassFilesCheckbox.setSelection(fJarPackage.areClassFilesExported());
fExportJavaFilesCheckbox.setSelection(fJarPackage.areJavaFilesExported());
// destination
if (fJarPackage.getJarLocation().isEmpty())
fDestinationNamesCombo.setText(""); //$NON-NLS-1$
else
fDestinationNamesCombo.setText(fJarPackage.getJarLocation().toOSString());
IDialogSettings settings= getDialogSettings();
if (settings != null) {
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
if (! fDestinationNamesCombo.getText().equals(directoryNames[0]))
fDestinationNamesCombo.add(fDestinationNamesCombo.getText());
for (int i= 0; i < directoryNames.length; i++)
fDestinationNamesCombo.add(directoryNames[i]);
}
// options
fCompressCheckbox.setSelection(fJarPackage.isCompressed());
fOverwriteCheckbox.setSelection(fJarPackage.allowOverwrite());
}
/**
* Initializes the JAR package from last used wizard page values.
*/
protected void initializeJarPackage() {
IDialogSettings settings= getDialogSettings();
if (settings != null) {
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(settings.getBoolean(STORE_EXPORT_CLASS_FILES));
fJarPackage.setExportJavaFiles(settings.getBoolean(STORE_EXPORT_JAVA_FILES));
// options
fJarPackage.setCompress(settings.getBoolean(STORE_COMPRESS));
fJarPackage.setOverwrite(settings.getBoolean(STORE_OVERWRITE));
// destination
String[] directoryNames= settings.getArray(STORE_DESTINATION_NAMES);
if (directoryNames == null)
return; // ie.- no settings stored
fJarPackage.setJarLocation(getPathFromString(directoryNames[0]));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// source
fJarPackage.setSelectedElements(getSelectedResources());
fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
// destination
IPath path= getPathFromString(fDestinationNamesCombo.getText());
if (path.segmentCount() > 0 && ensureTargetFileIsValid(path.toFile()) && path.getFileExtension() == null) //$NON-NLS-1$
path= path.addFileExtension(JarPackage.EXTENSION);
fJarPackage.setJarLocation(path);
// options
fJarPackage.setCompress(fCompressCheckbox.getSelection());
fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
}
protected IPath getPathFromString(String text) {
return new Path(text).makeAbsolute();
}
/**
* Returns a boolean indicating whether the passed File handle is
* is valid and available for use.
*
* @return boolean
*/
protected boolean ensureTargetFileIsValid(File targetFile) {
if (targetFile.exists() && targetFile.isDirectory()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (targetFile.exists()) {
if (!targetFile.canWrite()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.jarFileExistsAndNotWritable")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
}
return true;
}
/*
* Overrides method from WizardExportPage
*/
protected void createDestinationGroup(Composite parent) {
initializeDialogUnits(parent);
// destination specification group
Composite destinationSelectionGroup= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.numColumns= 3;
destinationSelectionGroup.setLayout(layout);
destinationSelectionGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL));
new Label(destinationSelectionGroup, SWT.NONE).setText(getDestinationLabel());
// destination name entry field
fDestinationNamesCombo= new Combo(destinationSelectionGroup, SWT.SINGLE | SWT.BORDER);
fDestinationNamesCombo.addListener(SWT.Modify, this);
fDestinationNamesCombo.addListener(SWT.Selection, this);
GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL);
data.widthHint= SIZING_TEXT_FIELD_WIDTH;
fDestinationNamesCombo.setLayoutData(data);
// destination browse button
fDestinationBrowseButton= new Button(destinationSelectionGroup, SWT.PUSH);
fDestinationBrowseButton.setText(JarPackagerMessages.getString("JarPackageWizardPage.browseButton.text")); //$NON-NLS-1$
fDestinationBrowseButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
SWTUtil.setButtonDimensionHint(fDestinationBrowseButton);
fDestinationBrowseButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
handleDestinationBrowseButtonPressed();
}
});
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDescriptionFileBrowseButtonPressed() {
SaveAsDialog dialog= new SaveAsDialog(getContainer().getShell());
dialog.create();
dialog.getShell().setText(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.title")); //$NON-NLS-1$
dialog.setMessage(JarPackagerMessages.getString("JarPackageWizardPage.saveAsDialog.message")); //$NON-NLS-1$
dialog.setOriginalFile(createFileHandle(fJarPackage.getDescriptionLocation()));
if (dialog.open() == dialog.OK) {
IPath path= dialog.getResult();
path= path.removeFileExtension().addFileExtension(JarPackage.DESCRIPTION_EXTENSION);
fDescriptionFileText.setText(path.toString());
}
}
/**
* Open an appropriate destination browser so that the user can specify a source
* to import from
*/
protected void handleDestinationBrowseButtonPressed() {
FileDialog dialog= new FileDialog(getContainer().getShell(), SWT.SAVE);
dialog.setFilterExtensions(new String[] {"*.jar", "*.zip"}); //$NON-NLS-1$ //$NON-NLS-2$
String currentSourceString= getDestinationValue();
int lastSeparatorIndex= currentSourceString.lastIndexOf(File.separator);
if (lastSeparatorIndex != -1) {
dialog.setFilterPath(currentSourceString.substring(0, lastSeparatorIndex));
dialog.setFileName(currentSourceString.substring(lastSeparatorIndex + 1, currentSourceString.length()));
}
else
dialog.setFileName(currentSourceString);
String selectedFileName= dialog.open();
if (selectedFileName != null)
fDestinationNamesCombo.setText(selectedFileName);
}
/**
* 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;
}
/**
* Creates the checkbox tree and list for selecting resources.
*
* @param parent the parent control
*/
protected void createInputGroup(Composite parent) {
int labelFlags= JavaElementLabelProvider.SHOW_BASICS
| JavaElementLabelProvider.SHOW_OVERLAY_ICONS
| JavaElementLabelProvider.SHOW_SMALL_ICONS;
ITreeContentProvider treeContentProvider=
new JavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
fInputGroup= new CheckboxTreeAndListGroup(
parent,
JavaCore.create(JavaPlugin.getDefault().getWorkspace().getRoot()),
treeContentProvider,
new JavaElementLabelProvider(labelFlags),
new BaseJavaElementContentProvider(),
new JavaElementLabelProvider(labelFlags),
SWT.NONE,
SIZING_SELECTION_WIDGET_WIDTH,
SIZING_SELECTION_WIDGET_HEIGHT);
fInputGroup.addTreeFilter(new EmptyInnerPackageFilter());
fInputGroup.setTreeSorter(new JavaElementSorter());
fInputGroup.setListSorter(new JavaElementSorter());
fInputGroup.addTreeFilter(new ContainerFilter(ContainerFilter.FILTER_NON_CONTAINERS));
fInputGroup.addTreeFilter(new LibraryFilter());
fInputGroup.addListFilter(new ContainerFilter(ContainerFilter.FILTER_CONTAINERS));
fInputGroup.getTree().addListener(SWT.MouseUp, this);
fInputGroup.getTable().addListener(SWT.MouseUp, this);
}
/**
* Creates the export type controls.
*
* @param parent the parent control
*/
protected void createExportTypeGroup(Composite parent) {
Composite optionsGroup= new Composite(parent, SWT.NONE);
GridLayout optionsLayout= new GridLayout();
optionsLayout.marginHeight= 0;
optionsGroup.setLayout(optionsLayout);
fExportClassFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportClassFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportClassFiles.text")); //$NON-NLS-1$
fExportClassFilesCheckbox.addListener(SWT.Selection, this);
fExportJavaFilesCheckbox= new Button(optionsGroup, SWT.CHECK | SWT.LEFT);
fExportJavaFilesCheckbox.setText(JarPackagerMessages.getString("JarPackageWizardPage.exportJavaFiles.text")); //$NON-NLS-1$
fExportJavaFilesCheckbox.addListener(SWT.Selection, this);
}
/**
* Updates the enablements of this page's controls. Subclasses may extend.
*/
protected void updateWidgetEnablements() {
}
/*
* Overrides method from IJarPackageWizardPage
*/
public boolean isPageComplete() {
setErrorMessage(null);
return super.determinePageCompletion();
}
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
protected void update() {
updateModel();
updateWidgetEnablements();
updatePageCompletion();
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateDestinationGroup() {
if (fDestinationNamesCombo.getText().length() == 0) {
return false;
}
if (fJarPackage.getJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
return ensureTargetFileIsValid(fJarPackage.getJarLocation().toFile());
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateOptionsGroup() {
return true;
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateSourceGroup() {
if (!fExportClassFilesCheckbox.getSelection()
&& !fExportJavaFilesCheckbox.getSelection()) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.noExportTypeChecked")); //$NON-NLS-1$
return false;
}
if (getSelectedResources().size() == 0)
return false;
if (fExportClassFilesCheckbox.getSelection() || !fExportJavaFilesCheckbox.getSelection())
return true;
// No class file export - check if there are source files
Iterator iter= getSelectedResourcesIterator();
while (iter.hasNext()) {
if (!(iter.next() instanceof IClassFile))
return true;
}
return false;
}
/*
* Overwrides method from WizardExportPage
*/
protected IPath getResourcePath() {
return getPathFromText(fSourceNameField);
}
/**
* 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
* @see #createFile
*/
protected IFile createFileHandle(IPath filePath) {
if (filePath.isValidPath(filePath.toString()) && filePath.segmentCount() >= 2)
return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath);
else
return null;
}
/**
* Set the current input focus to self's destination entry field
*/
protected void giveFocusToDestination() {
fDestinationNamesCombo.setFocus();
}
/*
* Overrides method from WizardExportResourcePage
*/
protected void setupBasedOnInitialSelections() {
Iterator enum= fInitialSelection.iterator();
while (enum.hasNext()) {
Object selectedElement= enum.next();
if (selectedElement instanceof ICompilationUnit || selectedElement instanceof IClassFile || selectedElement instanceof IFile)
fInputGroup.initialCheckListItem(selectedElement);
else
fInputGroup.initialCheckTreeItem(selectedElement);
}
TreeItem[] items= fInputGroup.getTree().getItems();
int i= 0;
while (i < items.length && !items[i].getChecked())
i++;
if (i < items.length) {
fInputGroup.getTree().setSelection(new TreeItem[] {items[i]});
fInputGroup.getTree().showSelection();
fInputGroup.populateListViewer(items[i].getData());
}
}
/*
* Implements method from IJarPackageWizardPage.
*/
public void finish() {
saveWidgetValues();
}
/*
* Method declared on IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
if (getControl() != null)
updatePageCompletion();
}
void setSelectedElementsWithoutContainedChildren() {
Set closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
closure.addAll(getExportedNonContainers());
fJarPackage.setSelectedElementsClosure(closure);
}
private Set removeContainedChildren(Set elements) {
Set newList= new HashSet(elements.size());
Set javaElementResources= getCorrespondingContainers(elements);
Iterator iter= elements.iterator();
boolean removedOne= false;
while (iter.hasNext()) {
Object element= iter.next();
Object parent;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement) {
parent= ((IJavaElement)element).getParent();
if (parent instanceof IPackageFragmentRoot) {
IPackageFragmentRoot pkgRoot= (IPackageFragmentRoot)parent;
try {
if (pkgRoot.getCorrespondingResource() instanceof IProject)
parent= pkgRoot.getJavaProject();
} catch (JavaModelException ex) {
// leave parent as is
}
}
}
else {
// unknown type
newList.add(element);
continue;
}
if (element instanceof IJavaModel || ((!(parent instanceof IJavaModel)) && (elements.contains(parent) || javaElementResources.contains(parent))))
removedOne= true;
else
newList.add(element);
}
if (removedOne)
return removeContainedChildren(newList);
else
return newList;
}
private Set getExportedNonContainers() {
Set whiteCheckedTreeItems= fInputGroup.getWhiteCheckedTreeItems();
Set exportedNonContainers= new HashSet(whiteCheckedTreeItems.size());
Set javaElementResources= getCorrespondingContainers(whiteCheckedTreeItems);
Iterator iter= fInputGroup.getAllCheckedListItems();
while (iter.hasNext()) {
Object element= iter.next();
Object parent= null;
if (element instanceof IResource)
parent= ((IResource)element).getParent();
else if (element instanceof IJavaElement)
parent= ((IJavaElement)element).getParent();
if (!whiteCheckedTreeItems.contains(parent) && !javaElementResources.contains(parent))
exportedNonContainers.add(element);
}
return exportedNonContainers;
}
/*
* Create a list with the folders / projects that correspond
* to the Java elements (Java project, package, package root)
*/
private Set getCorrespondingContainers(Set elements) {
Set javaElementResources= new HashSet(elements.size());
Iterator iter= elements.iterator();
while (iter.hasNext()) {
Object element= iter.next();
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
int type= je.getElementType();
if (type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT) {
// exclude default package since it is covered by the root
if (!(type == IJavaElement.PACKAGE_FRAGMENT && ((IPackageFragment)element).isDefaultPackage())) {
Object resource;
try {
resource= je.getCorrespondingResource();
} catch (JavaModelException ex) {
resource= null;
}
if (resource != null)
javaElementResources.add(resource);
}
}
}
}
return javaElementResources;
}
}
|
11,177 |
Bug 11177 externalize strings- incorrect second page size
| null |
resolved fixed
|
5360ffe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T11:38:13Z | 2002-03-12T16:20:00Z |
org.eclipse.jdt.ui/ui
| |
11,177 |
Bug 11177 externalize strings- incorrect second page size
| null |
resolved fixed
|
5360ffe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T11:38:13Z | 2002-03-12T16:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage2.java
| |
11,050 |
Bug 11050 Devide Sorting in two main parts: fields and methodes
|
would it be possible for one of the next releases, to adapt the sorting order of VAJ in the Outline view. I mean, first all attributes, which are sorted alphabeticly, and then all methods which are also sorted alphabeticly. At the moment, there will be make no difference between the attributes and methods, so that the sorting is done over them all together and not divided in two parts: attributes and methods. It would be nice, if that could be done. Thanks Daniel
|
resolved fixed
|
f83fa2a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T15:17:25Z | 2002-03-08T20:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementSorter.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.ui;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.viewers.ContentViewer;
import org.eclipse.jface.viewers.IBaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jdt.core.Flags;
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.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Sorter for Java elements. Ordered by element category, then by element name.
* Package fragment roots are sorted as ordered on the classpath.
* @since 2.0
*/
public class JavaElementSorter extends ViewerSorter {
private static final int JAVAPROJECTS= 1;
private static final int PACKAGEFRAGMENTROOTS= 2;
private static final int PACKAGEFRAGMENT= 3;
private static final int RESOURCEPACKAGES= 6;
private static final int COMPILATIONUNITS= 4;
private static final int CLASSFILES= 5;
private static final int RESOURCEFOLDERS= 7;
private static final int RESOURCES= 8;
private static final int STORAGE= 9;
private static final int PACKAGE_DECL= 10;
private static final int IMPORT_CONTAINER= 11;
private static final int IMPORT_DECLARATION= 12;
private static final int TYPES= 13;
private static final int CONSTRUCTORS= 14;
private static final int STATIC_INIT= 15;
private static final int STATIC_METHODS= 16;
private static final int INIT= 17;
private static final int METHODS= 18;
private static final int STATIC_FIELDS= 19;
private static final int FIELDS= 20;
private static final int JAVAELEMENTS= 21;
private static final int OTHERS= 22;
public JavaElementSorter() {
}
/*
* @see ViewerSorter#isSorterProperty
*/
public boolean isSorterProperty(Object element, Object property) {
return true;
}
/*
* @see ViewerSorter#category
*/
public int category(Object element) {
if (element instanceof IJavaElement) {
try {
IJavaElement je= (IJavaElement) element;
switch (je.getElementType()) {
case IJavaElement.METHOD: {
IMethod method= (IMethod) je;
if (method.isConstructor())
return CONSTRUCTORS;
int flags= method.getFlags();
return Flags.isStatic(flags) ? STATIC_METHODS : METHODS;
}
case IJavaElement.FIELD: {
int flags= ((IField) je).getFlags();
return Flags.isStatic(flags) ? STATIC_FIELDS : FIELDS;
}
case IJavaElement.INITIALIZER: {
int flags= ((IInitializer) je).getFlags();
return Flags.isStatic(flags) ? STATIC_INIT : INIT;
}
case IJavaElement.TYPE:
return TYPES;
case IJavaElement.PACKAGE_DECLARATION:
return PACKAGE_DECL;
case IJavaElement.IMPORT_CONTAINER:
return IMPORT_CONTAINER;
case IJavaElement.IMPORT_DECLARATION:
return IMPORT_DECLARATION;
case IJavaElement.PACKAGE_FRAGMENT:
IPackageFragment pack= (IPackageFragment) je;
if (pack.getParent().getUnderlyingResource() instanceof IProject) {
return PACKAGEFRAGMENTROOTS;
}
if (!pack.hasChildren() && pack.getNonJavaResources().length > 0) {
return RESOURCEPACKAGES;
}
return PACKAGEFRAGMENT;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
return PACKAGEFRAGMENTROOTS;
case IJavaElement.JAVA_PROJECT:
return JAVAPROJECTS;
case IJavaElement.CLASS_FILE:
return CLASSFILES;
case IJavaElement.COMPILATION_UNIT:
return COMPILATIONUNITS;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
return JAVAELEMENTS;
} else if (element instanceof IFile) {
return RESOURCES;
} else if (element instanceof IContainer) {
return RESOURCEFOLDERS;
} else if (element instanceof IStorage) {
return STORAGE;
}
return OTHERS;
}
/*
* @see ViewerSorter#compare
*/
public int compare(Viewer viewer, Object e1, Object e2) {
int cat1= category(e1);
int cat2= category(e2);
if (cat1 != cat2)
return cat1 - cat2;
if (cat1 == PACKAGEFRAGMENTROOTS) {
IPackageFragmentRoot root1= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e1);
IPackageFragmentRoot root2= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e2);
if (!root1.getPath().equals(root2.getPath())) {
int p1= getClassPathIndex(root1);
int p2= getClassPathIndex(root2);
if (p1 != p2) {
return p1 - p2;
}
}
}
// non - java resources are sorted using the label from the viewers label provider
if (cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) {
return compareWithLabelProvider(viewer, e1, e2);
}
// java element are sorted by name (and parameter types)
String name1= JavaElementLabels.getTextLabel(e1, JavaElementLabels.M_PARAMETER_TYPES);
String name2= JavaElementLabels.getTextLabel(e2, JavaElementLabels.M_PARAMETER_TYPES);
return getCollator().compare(name1, name2);
}
private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) {
if (viewer == null || !(viewer instanceof ContentViewer)) {
IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider();
if (prov instanceof ILabelProvider) {
ILabelProvider lprov= (ILabelProvider) prov;
String name1 = lprov.getText(e1);
String name2 = lprov.getText(e2);
if (name1 != null && name2 != null) {
return getCollator().compare(name1, name2);
}
}
}
return 0; // can't compare
}
private int getClassPathIndex(IPackageFragmentRoot root) {
try {
IPath rootPath= root.getPath();
IPackageFragmentRoot[] roots= root.getJavaProject().getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
if (roots[i].getPath().equals(rootPath)) {
return i;
}
}
} catch (JavaModelException e) {
}
return Integer.MAX_VALUE;
}
}
|
11,080 |
Bug 11080 Package statements for nested classes not updated properly
|
If a class that contains references to nested classes of another class in the same package is moved into a different package the automatically inserted package statements unnecessarily include the nested classes explicitely. Instead of: import p1.A The following (illegal) statements are inserted: import p1.A; import p1.A$B; import p1.A$B$C; -- Eric Jain
|
resolved fixed
|
896d24c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:25:55Z | 2002-03-10T14:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test13/out/B.java
|
package p;
class B{
public static void m(){
new A.Inner();
}
}
|
11,080 |
Bug 11080 Package statements for nested classes not updated properly
|
If a class that contains references to nested classes of another class in the same package is moved into a different package the automatically inserted package statements unnecessarily include the nested classes explicitely. Instead of: import p1.A The following (illegal) statements are inserted: import p1.A; import p1.A$B; import p1.A$B$C; -- Eric Jain
|
resolved fixed
|
896d24c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:25:55Z | 2002-03-10T14:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test14/out/B.java
|
package p;
class B{
public static void m(){
new A.Inner();
}
}
|
11,080 |
Bug 11080 Package statements for nested classes not updated properly
|
If a class that contains references to nested classes of another class in the same package is moved into a different package the automatically inserted package statements unnecessarily include the nested classes explicitely. Instead of: import p1.A The following (illegal) statements are inserted: import p1.A; import p1.A$B; import p1.A$B$C; -- Eric Jain
|
resolved fixed
|
896d24c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:25:55Z | 2002-03-10T14:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test17/out/B.java
|
package p;
class B{
public static void m(){
A.Inner[] i;
}
}
|
11,080 |
Bug 11080 Package statements for nested classes not updated properly
|
If a class that contains references to nested classes of another class in the same package is moved into a different package the automatically inserted package statements unnecessarily include the nested classes explicitely. Instead of: import p1.A The following (illegal) statements are inserted: import p1.A; import p1.A$B; import p1.A$B$C; -- Eric Jain
|
resolved fixed
|
896d24c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:25:55Z | 2002-03-10T14:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test18/out/B.java
|
package p;
class B{
public static void m(){
A.Inner[] i;
}
}
|
11,080 |
Bug 11080 Package statements for nested classes not updated properly
|
If a class that contains references to nested classes of another class in the same package is moved into a different package the automatically inserted package statements unnecessarily include the nested classes explicitely. Instead of: import p1.A The following (illegal) statements are inserted: import p1.A; import p1.A$B; import p1.A$B$C; -- Eric Jain
|
resolved fixed
|
896d24c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:25:55Z | 2002-03-10T14:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test19/out/B.java
|
package p;
class B{
public static void m(){
A.Inner[][] i;
}
}
|
11,080 |
Bug 11080 Package statements for nested classes not updated properly
|
If a class that contains references to nested classes of another class in the same package is moved into a different package the automatically inserted package statements unnecessarily include the nested classes explicitely. Instead of: import p1.A The following (illegal) statements are inserted: import p1.A; import p1.A$B; import p1.A$B$C; -- Eric Jain
|
resolved fixed
|
896d24c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:25:55Z | 2002-03-10T14:20:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/MoveMembers/test20/out/B.java
|
package p;
class B{
public static void m(){
A.F[] y;
A.F[] ff;
A.F[ ] ff1;
A.F[][] fff;
A.F[][] fff1;
p.A.F[ ][ ] fff2;
}
}
|
8,357 |
Bug 8357 Pull Up: should remove final from field
|
Pull up 'fName' in test case. -> Compilation Error in TestCase The final modifier has to be removed (or the refactoring should not allow to move final variables.
|
resolved fixed
|
9273021
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:49:22Z | 2002-01-24T11:00:00Z |
org.eclipse.jdt.ui/core
| |
8,357 |
Bug 8357 Pull Up: should remove final from field
|
Pull up 'fName' in test case. -> Compilation Error in TestCase The final modifier has to be removed (or the refactoring should not allow to move final variables.
|
resolved fixed
|
9273021
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-13T17:49:22Z | 2002-01-24T11:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoring.java
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/T11337.java
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/T11337_1.java
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_in/A_test565.java
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/ExtractMethodWorkSpace/ExtractMethodTests/locals_out/A_test565.java
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractMethodTests.java
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
org.eclipse.jdt.ui/core
| |
11,337 |
Bug 11337 Extract method parameter detection
|
When I extract selected ('*') lines of code from: void Disassemble(String aggregateName, String telegramName, byte bytes []) throws Exception { String fullTelegramName = aggregateName + "." + telegramName; TTelegramDef telegramDef = GetExistingTelegramDef(telegramName); System.out.println(telegramDef); // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // int bitValue = 0; int bitPos = -1; // for (int i = 0; i < telegramDef.GetFieldCount(); i++) { TFieldDef field = telegramDef.GetField(i); if (field.GetName().equals("skip")) { bitPos = -1; continue; } // String fullFieldName = fullTelegramName + "." + field.GetName(); switch (field.GetType()) { case TFieldDef.TYPE_INT : { * byte b1 = (byte) is.read(); * byte b2 = (byte) is.read(); * if ((b1 == -1) || (b2 == -1)) * throw new Exception ("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); * int value = (b1 << 8) + b2; m_DE.Set(fullFieldName, value); } break; case TFieldDef.TYPE_BIT : break; case TFieldDef.TYPE_STR : break; default : throw new Exception("Unknown field type: " + field.GetType()); } // switch field type } // for all fields // m_DE.Commit(); } It produces: private int GetIntFromBytes(String telegramName, ByteArrayInputStream is) throws Exception { byte b1 = (byte) is.read(); byte b2 = (byte) is.read(); if ((b1 == -1) || (b2 == -1)) throw new Exception("Not enough data in telegram, name: " + telegramName + " bytes: " + Debug.DumpBytes(bytes)); int value = (b1 << 8) + b2; return value; } But there is no parameter with name "bytes".
|
verified fixed
|
26ad983
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T10:17:33Z | 2002-03-14T10:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/flow/FlowAnalyzer.java
| |
11,314 |
Bug 11314 Replace package name fragments should always be smaller
|
Build 20020214 If you enter "2~." in the 'Replace package name fragments with:' field in the preferences (Java->Work in progress), com.ibm.foobar is replaced with co~.ib~.foobar. I believe that package name compression should only replace a fragment if the compressed name is actually smaller. Thus com. would not be replaced in this example, since co~. is the same length, and contains less info.
|
verified fixed
|
1d7fa44
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T13:47:52Z | 2002-03-13T22:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.java
|
package org.eclipse.jdt.internal.ui.viewsupport;
import org.eclipse.core.runtime.IAdaptable;
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.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage;
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;
/**
* 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;
private final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - ";
private final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", ";
private final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type
/*
* Package name compression
*/
private static String fgPkgNamePattern= ""; //$NON-NLS-1$
private static String fgPkgNamePrefix;
private static String fgPkgNamePostfix;
private static int fgPkgNameChars;
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 "";
}
/**
* Returns the label for a Java element. Flags as defined above.
*/
public static String getElementLabel(IJavaElement element, int flags) {
StringBuffer buf= new StringBuffer();
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, 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, 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, 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, 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, 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, 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)) {
buf.append(JavaModelUtil.getFullyQualifiedName(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) {
buf.append(JavaModelUtil.getFullyQualifiedName(declaringType));
} else {
getPackageFragmentLabel(type.getPackageFragment(), 0, 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) JavaModelUtil.getOpenable(declaration);
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) JavaModelUtil.getOpenable(declaration);
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('/');
}
if (pack.isDefaultPackage()) {
buf.append(JavaUIMessages.getString("JavaElementLabels.default_package")); //$NON-NLS-1$
} else if (getFlag(flags, P_COMPRESSED)) {
String name= pack.getElementName();
refreshPackageNamePattern();
int start= 0;
int dot= name.indexOf('.', start);
while (dot > 0) {
buf.append(fgPkgNamePrefix);
if (fgPkgNameChars > 0)
buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot)));
buf.append(fgPkgNamePostfix);
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() && getFlag(flags, ROOT_VARIABLE)) {
try {
IClasspathEntry rawEntry= JavaModelUtil.getRawClasspathEntry(root);
if (rawEntry != null) {
if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
buf.append(rawEntry.getPath().makeRelative());
buf.append(CONCAT_STRING);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e); // problems with class path
}
}
if (root.isExternal()) {
// external jars have path == name
// no qualification for external roots
buf.append(root.getPath().toOSString());
} else {
if (getFlag(flags, ROOT_QUALIFIED)) {
buf.append(root.getPath().makeRelative().toString());
} else {
buf.append(root.getElementName());
}
if (getFlag(flags, ROOT_POST_QUALIFIED)) {
buf.append(CONCAT_STRING);
buf.append(root.getParent().getElementName());
}
}
}
private static void refreshPackageNamePattern() {
String pattern= WorkInProgressPreferencePage.getPkgNamePatternForPackagesView();
if (pattern.equals(fgPkgNamePattern))
return;
fgPkgNamePattern= pattern;
int i= 0;
fgPkgNameChars= 0;
fgPkgNamePrefix= "";
fgPkgNamePostfix= "";
while (i < pattern.length()) {
char ch= pattern.charAt(i);
if (Character.isDigit(ch)) {
fgPkgNameChars= ch-48;
if (i > 0 && i < pattern.length() - 1)
fgPkgNamePrefix= pattern.substring(0, i);
if (i >= 0 && i < pattern.length())
fgPkgNamePostfix= pattern.substring(i+1);
return;
}
i++;
}
fgPkgNamePrefix= pattern;
}
}
|
11,437 |
Bug 11437 jar packager: no error message but buttons disabled
|
20020314 on the 'jar manifest' wizard page, if you select to use existing manifest file there's no error message but next and finish are disabled user should be informed what to do to make the wizard happy
|
resolved fixed
|
76a8215
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T13:50:11Z | 2002-03-15T11:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarManifestWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
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.IDialogSettings;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.ui.dialogs.SaveAsDialog;
import org.eclipse.ui.dialogs.SelectionDialog;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
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.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaUI;
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.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.packageview.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;
/**
* Page 3 of the JAR Package wizard
*/
public 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 JarPackage 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(JarPackage 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();
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.setMainClass(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() == dialog.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.doesManifestExist())
dialog.setInitialSelections(new IResource[] {fJarPackage.getManifestFile()});
if (dialog.open() == dialog.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= fJarPackage.getSelectedResources();
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= fJarPackage.getSelectedResources();
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.getMainClass() != null)
dialog.setInitialSelections(new Object[] {fJarPackage.getMainClass()});
if (dialog.open() == dialog.OK) {
fJarPackage.setMainClass((IType)dialog.getResult()[0]);
fMainClassText.setText(fJarPackage.getMainClassName());
} else if (!fJarPackage.isMainClassValid(getContainer())) {
// user did not cancel: no types were found
fJarPackage.setMainClass(null);
fMainClassText.setText(fJarPackage.getMainClassName());
}
}
protected void handleSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(fJarPackage.getPackagesForSelectedResources());
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() == dialog.OK)
fJarPackage.setPackagesToSeal(getPackagesFromDialog(dialog));
updateSealingInfo();
}
protected void handleUnSealPackagesDetailsButtonPressed() {
SelectionDialog dialog= createPackageDialog(fJarPackage.getPackagesForSelectedResources());
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() == dialog.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 incompleteButNotAnError= false;
if (fJarPackage.isManifestGenerated() && fJarPackage.isManifestSaved()) {
if (fJarPackage.getManifestLocation().toString().length() == 0)
incompleteButNotAnError= true;
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() && !fJarPackage.doesManifestExist()) {
if (fJarPackage.getManifestLocation().toString().length() == 0)
incompleteButNotAnError= true;
else {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.invalidManifestFile")); //$NON-NLS-1$
return false;
}
}
if (fJarPackage.isJarSealed()
&& !fJarPackage.getPackagesForSelectedResources().containsAll(Arrays.asList(fJarPackage.getPackagesToUnseal()))) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.unsealedPackagesNotInSelection")); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isJarSealed()
&& !fJarPackage.getPackagesForSelectedResources().containsAll(Arrays.asList(fJarPackage.getPackagesToSeal()))) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.sealedPackagesNotInSelection")); //$NON-NLS-1$
return false;
}
if (!fJarPackage.isMainClassValid(getContainer()) || (fJarPackage.getMainClass() == null && fMainClassText.getText().length() > 0)) {
setErrorMessage(JarPackagerMessages.getString("JarManifestWizardPage.error.invalidMainClass")); //$NON-NLS-1$
return false;
}
if (incompleteButNotAnError) {
setErrorMessage(null);
return false;
}
setErrorMessage(null);
return true;
}
/*
* Implements method from IWizardPage.
*/
public void setPreviousPage(IWizardPage page) {
super.setPreviousPage(page);
fMainTypes= null;
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 (!fJarPackage.isUsedToInitialize())
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(fJarPackage.getMainClassName());
}
/**
* 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
* @see #createFile
*/
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);
}
JavaElementContentProvider cp= new JavaElementContentProvider() {
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.getDefault().getWorkspace().getRoot()));
dialog.addFilter(new EmptyInnerPackageFilter());
dialog.addFilter(new LibraryFilter());
dialog.addFilter(new SealPackagesFilter(packages));
dialog.setValidator(new ISelectionValidator() {
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() == dialog.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 JavaElementContentProvider();
ILabelProvider labelProvider= new JavaElementLabelProvider(labelFlags);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, contentProvider);
dialog.setAllowMultiple(false);
dialog.setValidator(new ISelectionValidator() {
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.getDefault().getWorkspace().getRoot()));
return dialog;
}
}
|
11,424 |
Bug 11424 ArrayIndexOutOfBoundsException at "Expand Selection to Previous Element"
|
This happens with eclipse-SDK-20020312-win32.zip every time if I'm inside a method and I apply this action a few times. When the action selects the whole method block and I try the action once more, it throws this error: java.lang.ArrayIndexOutOfBoundsException at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectPreviousAction.getPreviousNode(StructureSelectPreviousAction.java:44) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectPreviousAction.internalGetNewSelectionRange(StructureSelectPreviousAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectionAction.getNewSelectionRange(StructureSelectionAction.java:50) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectionAction.run(StructureSelectionAction.java:38) at org.eclipse.jface.action.Action.runWithEvent(Action.java:466) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:692) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) 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:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
verified fixed
|
025a13c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T16:34:19Z | 2002-03-14T23:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/resources/StructureSelectionAction/A_test24.java
| |
11,424 |
Bug 11424 ArrayIndexOutOfBoundsException at "Expand Selection to Previous Element"
|
This happens with eclipse-SDK-20020312-win32.zip every time if I'm inside a method and I apply this action a few times. When the action selects the whole method block and I try the action once more, it throws this error: java.lang.ArrayIndexOutOfBoundsException at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectPreviousAction.getPreviousNode(StructureSelectPreviousAction.java:44) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectPreviousAction.internalGetNewSelectionRange(StructureSelectPreviousAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectionAction.getNewSelectionRange(StructureSelectionAction.java:50) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectionAction.run(StructureSelectionAction.java:38) at org.eclipse.jface.action.Action.runWithEvent(Action.java:466) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:692) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) 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:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
verified fixed
|
025a13c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T16:34:19Z | 2002-03-14T23:53:20Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,424 |
Bug 11424 ArrayIndexOutOfBoundsException at "Expand Selection to Previous Element"
|
This happens with eclipse-SDK-20020312-win32.zip every time if I'm inside a method and I apply this action a few times. When the action selects the whole method block and I try the action once more, it throws this error: java.lang.ArrayIndexOutOfBoundsException at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectPreviousAction.getPreviousNode(StructureSelectPreviousAction.java:44) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectPreviousAction.internalGetNewSelectionRange(StructureSelectPreviousAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectionAction.getNewSelectionRange(StructureSelectionAction.java:50) at org.eclipse.jdt.internal.ui.refactoring.actions.structureselection.StructureSelectionAction.run(StructureSelectionAction.java:38) at org.eclipse.jface.action.Action.runWithEvent(Action.java:466) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:74) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:637) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1420) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1208) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:692) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) 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:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
verified fixed
|
025a13c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T16:34:19Z | 2002-03-14T23:53:20Z |
cases/org/eclipse/jdt/ui/tests/actions/StructureSelectionActionTests.java
| |
11,440 |
Bug 11440 npe in rename temp
|
Log: Fri Mar 15 11:31:18 GMT+01:00 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.core.dom.DefaultBindingResolver.retrieveEnclosingScope (DefaultBindingResolver.java:528) at org.eclipse.jdt.core.dom.DefaultBindingResolver.returnBindingForQualifiedNamePar t(DefaultBindingResolver.java:573) at org.eclipse.jdt.core.dom.DefaultBindingResolver.internalResolveNameForSimpleName (DefaultBindingResolver.java:617) at org.eclipse.jdt.core.dom.DefaultBindingResolver.resolveName (DefaultBindingResolver.java:137) at org.eclipse.jdt.core.dom.Name.resolveBinding(Name.java:75) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visitNameReference(TempOccurrenceFinder.java:53) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visit(TempOccurrenceFinder.java:79) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java:87) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.QualifiedName.accept0(QualifiedName.java:80) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.VariableDeclarationFragment.accept0 (VariableDeclarationFragment.java:90) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.FieldDeclaration.accept0 (FieldDeclaration.java:113) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder.findTemp OccurrenceOffsets(TempOccurrenceFinder.java:25) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOccu rrenceOffsets(RenameTempRefactoring.java:219) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.createC hange(RenameTempRefactoring.java:196) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:97) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:122) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:65) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
e55ecaa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T19:08:00Z | 2002-03-15T11:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test39_in.java
| |
11,440 |
Bug 11440 npe in rename temp
|
Log: Fri Mar 15 11:31:18 GMT+01:00 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.core.dom.DefaultBindingResolver.retrieveEnclosingScope (DefaultBindingResolver.java:528) at org.eclipse.jdt.core.dom.DefaultBindingResolver.returnBindingForQualifiedNamePar t(DefaultBindingResolver.java:573) at org.eclipse.jdt.core.dom.DefaultBindingResolver.internalResolveNameForSimpleName (DefaultBindingResolver.java:617) at org.eclipse.jdt.core.dom.DefaultBindingResolver.resolveName (DefaultBindingResolver.java:137) at org.eclipse.jdt.core.dom.Name.resolveBinding(Name.java:75) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visitNameReference(TempOccurrenceFinder.java:53) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visit(TempOccurrenceFinder.java:79) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java:87) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.QualifiedName.accept0(QualifiedName.java:80) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.VariableDeclarationFragment.accept0 (VariableDeclarationFragment.java:90) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.FieldDeclaration.accept0 (FieldDeclaration.java:113) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder.findTemp OccurrenceOffsets(TempOccurrenceFinder.java:25) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOccu rrenceOffsets(RenameTempRefactoring.java:219) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.createC hange(RenameTempRefactoring.java:196) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:97) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:122) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:65) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
e55ecaa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T19:08:00Z | 2002-03-15T11:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test39_out.java
| |
11,440 |
Bug 11440 npe in rename temp
|
Log: Fri Mar 15 11:31:18 GMT+01:00 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.core.dom.DefaultBindingResolver.retrieveEnclosingScope (DefaultBindingResolver.java:528) at org.eclipse.jdt.core.dom.DefaultBindingResolver.returnBindingForQualifiedNamePar t(DefaultBindingResolver.java:573) at org.eclipse.jdt.core.dom.DefaultBindingResolver.internalResolveNameForSimpleName (DefaultBindingResolver.java:617) at org.eclipse.jdt.core.dom.DefaultBindingResolver.resolveName (DefaultBindingResolver.java:137) at org.eclipse.jdt.core.dom.Name.resolveBinding(Name.java:75) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visitNameReference(TempOccurrenceFinder.java:53) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visit(TempOccurrenceFinder.java:79) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java:87) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.QualifiedName.accept0(QualifiedName.java:80) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.VariableDeclarationFragment.accept0 (VariableDeclarationFragment.java:90) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.FieldDeclaration.accept0 (FieldDeclaration.java:113) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder.findTemp OccurrenceOffsets(TempOccurrenceFinder.java:25) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOccu rrenceOffsets(RenameTempRefactoring.java:219) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.createC hange(RenameTempRefactoring.java:196) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:97) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:122) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:65) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
e55ecaa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T19:08:00Z | 2002-03-15T11:00:00Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
11,440 |
Bug 11440 npe in rename temp
|
Log: Fri Mar 15 11:31:18 GMT+01:00 2002 4 org.eclipse.jdt.ui 1 Internal Error java.lang.reflect.InvocationTargetException: java.lang.NullPointerException at org.eclipse.jdt.core.dom.DefaultBindingResolver.retrieveEnclosingScope (DefaultBindingResolver.java:528) at org.eclipse.jdt.core.dom.DefaultBindingResolver.returnBindingForQualifiedNamePar t(DefaultBindingResolver.java:573) at org.eclipse.jdt.core.dom.DefaultBindingResolver.internalResolveNameForSimpleName (DefaultBindingResolver.java:617) at org.eclipse.jdt.core.dom.DefaultBindingResolver.resolveName (DefaultBindingResolver.java:137) at org.eclipse.jdt.core.dom.Name.resolveBinding(Name.java:75) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visitNameReference(TempOccurrenceFinder.java:53) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder$TempOccu rrenceAnalyzer.visit(TempOccurrenceFinder.java:79) at org.eclipse.jdt.core.dom.SimpleName.accept0(SimpleName.java:87) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.QualifiedName.accept0(QualifiedName.java:80) at org.eclipse.jdt.core.dom.ASTNode.acceptChild(ASTNode.java:957) at org.eclipse.jdt.core.dom.VariableDeclarationFragment.accept0 (VariableDeclarationFragment.java:90) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.FieldDeclaration.accept0 (FieldDeclaration.java:113) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.TypeDeclaration.accept0 (TypeDeclaration.java:153) at org.eclipse.jdt.core.dom.ASTNode.acceptChildren(ASTNode.java:986) at org.eclipse.jdt.core.dom.CompilationUnit.accept0 (CompilationUnit.java:138) at org.eclipse.jdt.core.dom.ASTNode.accept(ASTNode.java:906) at org.eclipse.jdt.internal.corext.refactoring.rename.TempOccurrenceFinder.findTemp OccurrenceOffsets(TempOccurrenceFinder.java:25) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.getOccu rrenceOffsets(RenameTempRefactoring.java:219) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.createC hange(RenameTempRefactoring.java:196) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:97) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:118) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:249) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:713) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:330) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:122) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:461) at org.eclipse.jface.wizard.WizardDialog.finishPressed (WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed (WizardDialog.java:311) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:363) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:78) at org.eclipse.jdt.internal.ui.refactoring.actions.TextSelectionBasedRefactoringAct ion.run(TextSelectionBasedRefactoringAction.java:28) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringActionDelegate.run (RefactoringActionDelegate.java:65) at org.eclipse.ui.internal.PluginAction.runWithEvent (PluginAction.java:204) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:675) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:151) at org.eclipse.core.launcher.Main.run(Main.java:502) at org.eclipse.core.launcher.Main.main(Main.java:362)
|
resolved fixed
|
e55ecaa
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-15T19:08:00Z | 2002-03-15T11:00:00Z |
cases/org/eclipse/jdt/ui/tests/refactoring/RenameTempTests.java
| |
11,416 |
Bug 11416 Error markers not shown in parents when resource added
|
Using 20020214 Eclipse build. If you add a new resource to a project and that resource has an error, the Java Packages view will show an X on the resource but not on its ancestor containers. This could happen, for instance, when adding a resource from a Team repository. The problem is in org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager.checkInvalidate(). The following should be changed, from: ============================ if (kind == IResourceDelta.REMOVED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) { ============================ to: ============================ if (kind == IResourceDelta.REMOVED || ((kind == IResourceDelta.ADDED || kind == IResourceDelta.CHANGED) && isErrorDelta(delta))) { ============================
|
resolved fixed
|
c3d3e3a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-18T14:56:22Z | 2002-03-14T21:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/ProblemMarkerManager.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.viewsupport;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IMarkerDelta;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Listens to resource deltas and filters for marker changes of type IMarker.PROBLEM
* Viewers showing error ticks should register as listener to
* this type.
*/
public class ProblemMarkerManager implements IResourceChangeListener {
/**
* Visitors used to filter the element delta changes
*/
private static class ProjectErrorVisitor implements IResourceDeltaVisitor {
private HashSet fChangedElements;
public ProjectErrorVisitor(HashSet changedElements) {
fChangedElements= changedElements;
}
public boolean visit(IResourceDelta delta) throws CoreException {
IResource res= delta.getResource();
if (res instanceof IProject && delta.getKind() == IResourceDelta.CHANGED) {
try {
IProject project= (IProject) res;
if (!(project.hasNature(JavaCore.NATURE_ID) && project.isOpen())) {
// only track open Java projects
return false;
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
return false;
}
}
checkInvalidate(delta, res.getFullPath());
return true;
}
private void checkInvalidate(IResourceDelta delta, IPath path) {
int kind= delta.getKind();
if (kind == IResourceDelta.REMOVED || (kind == IResourceDelta.CHANGED && isErrorDelta(delta))) {
// invalidate the path and all parent paths
while (!path.isEmpty() && !path.isRoot() && !fChangedElements.contains(path)) {
fChangedElements.add(path);
path= path.removeLastSegments(1);
}
}
}
private boolean isErrorDelta(IResourceDelta delta) {
if ((delta.getFlags() & IResourceDelta.MARKERS) != 0) {
IMarkerDelta[] markerDeltas= delta.getMarkerDeltas();
for (int i= 0; i < markerDeltas.length; i++) {
if (markerDeltas[i].isSubtypeOf(IMarker.PROBLEM)) {
int kind= markerDeltas[i].getKind();
if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED)
return true;
int severity= markerDeltas[i].getAttribute(IMarker.SEVERITY, -1);
int newSeverity= markerDeltas[i].getMarker().getAttribute(IMarker.SEVERITY, -1);
if (newSeverity != severity)
return true;
}
}
}
return false;
}
}
private ListenerList fListeners;
public ProblemMarkerManager() {
fListeners= new ListenerList(5);
}
/*
* @see IResourceChangeListener#resourceChanged
*/
public void resourceChanged(IResourceChangeEvent event) {
HashSet changedElements= new HashSet();
try {
IResourceDelta delta= event.getDelta();
if (delta != null)
delta.accept(new ProjectErrorVisitor(changedElements));
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
if (changedElements.size() > 0) {
fireChanges(changedElements);
}
}
/**
* Adds a listener for problem marker changes.
*/
public void addListener(IProblemChangedListener listener) {
if (fListeners.isEmpty()) {
JavaPlugin.getWorkspace().addResourceChangeListener(this);
}
fListeners.add(listener);
}
/**
* Removes a <code>IProblemChangedListener</code>.
*/
public void removeListener(IProblemChangedListener listener) {
fListeners.remove(listener);
if (fListeners.isEmpty()) {
JavaPlugin.getWorkspace().removeResourceChangeListener(this);
}
}
private void fireChanges(Set changes) {
Object[] listeners= fListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
IProblemChangedListener curr= (IProblemChangedListener) listeners[i];
curr.problemsChanged(changes);
}
}
}
|
11,537 |
Bug 11537 Refactoring - extract local adds incorrect import
|
In a method, given this: return fMyField.getArrayOfFoo() where the method getArrayOfFoo has a return type of Foo[], if I use extract local variable to extract "fMyField.getArrayOfFoo()" into a local variable "foos", it adds an (incorrect) import in the format import myPackage.Foo[]; Note that the array brackets should not appear in the import statement. Also note that in my case, the imports already included an import for the type "myPackage.Foo"... if that matters when trying to reproduce it.
|
resolved fixed
|
bbecec8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-19T11:43:08Z | 2002-03-18T14:00:00Z |
org.eclipse.jdt.ui/core
| |
11,537 |
Bug 11537 Refactoring - extract local adds incorrect import
|
In a method, given this: return fMyField.getArrayOfFoo() where the method getArrayOfFoo has a return type of Foo[], if I use extract local variable to extract "fMyField.getArrayOfFoo()" into a local variable "foos", it adds an (incorrect) import in the format import myPackage.Foo[]; Note that the array brackets should not appear in the import statement. Also note that in my case, the imports already included an import for the type "myPackage.Foo"... if that matters when trying to reproduce it.
|
resolved fixed
|
bbecec8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-19T11:43:08Z | 2002-03-18T14:00:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportEdit.java
| |
10,247 |
Bug 10247 Template - code assist ends template editing
|
Build > 20020214.1 Create the following class import java.util.List; public class T { public List getList() { return null; } public void foo() { T t= null; for <= code assist } } - select for - iterate over collection - press tab - type t.get <= code assist - select getList observe: template editing gets ended.
|
verified fixed
|
c0eba38
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-19T12:09:42Z | 2002-02-26T13:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ExperimentalResultCollector.java
|
package org.eclipse.jdt.internal.ui.text.java;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import org.eclipse.jface.text.ITextViewer;
/**
* Bin to collect the proposal of the infrastructure on code assist in a java text.
*/
public class ExperimentalResultCollector extends ResultCollector {
private ITextViewer fViewer;
protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end) {
JavaCompletionProposal original= super.createMethodCallCompletion(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end);
// XXX hack to handle empty code completion
if ((completionName.length == 0) || ((completionName.length == 1) && completionName[0] == ')'))
return original;
int count= parameterNames.length;
int[] offsets= new int[count];
int[] lengths= new int[count];
StringBuffer buffer= new StringBuffer();
buffer.append(name);
buffer.append('(');
for (int i= 0; i != count; i++) {
if (i != 0)
buffer.append(", ");
offsets[i]= buffer.length();
buffer.append(parameterNames[i]);
lengths[i]= buffer.length() - offsets[i];
}
buffer.append(')');
return new ExperimentalProposal(buffer.toString(), start, end - start, original.getImage(),
original.getDisplayString(), offsets, lengths, fViewer);
}
/**
* Sets the viewer.
* @param viewer The viewer to set
*/
public void setViewer(ITextViewer viewer) {
fViewer= viewer;
}
}
|
10,247 |
Bug 10247 Template - code assist ends template editing
|
Build > 20020214.1 Create the following class import java.util.List; public class T { public List getList() { return null; } public void foo() { T t= null; for <= code assist } } - select for - iterate over collection - press tab - type t.get <= code assist - select getList observe: template editing gets ended.
|
verified fixed
|
c0eba38
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-19T12:09:42Z | 2002-02-26T13:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionUI.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.text.link;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.BadPositionCategoryException;
import org.eclipse.jface.text.DefaultPositionUpdater;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IPositionUpdater;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.util.Assert;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* A user interface for <code>LinkedPositionManager</code>, using <code>ITextViewer</code>.
*/
public class LinkedPositionUI implements LinkedPositionListener,
ITextInputListener, ModifyListener, VerifyListener, VerifyKeyListener, PaintListener {
/**
* A listener for notification when the user cancelled the edit operation.
*/
public interface ExitListener {
void exit(boolean accept);
}
// leave flags
private static final int UNINSTALL= 1; // uninstall linked position manager
private static final int COMMIT= 2; // commit changes
private static final int DOCUMENT_CHANGED= 4; // document has changed
private static final int UPDATE_CARET= 8; // update caret
private static final String CARET_POSITION= "LinkedPositionUI.caret.position";
private static final IPositionUpdater fgUpdater= new DefaultPositionUpdater(CARET_POSITION);
private final ITextViewer fViewer;
private final LinkedPositionManager fManager;
private final Color fFrameColor;
private int fFinalCaretOffset= -1; // no final caret offset
private Position fFramePosition;
private int fCaretOffset;
private ExitListener fExitListener;
/**
* Creates a user interface for <code>LinkedPositionManager</code>.
*
* @param viewer the text viewer.
* @param manager the <code>LinkedPositionManager</code> managing a <code>IDocument</code> of the <code>ITextViewer</code>.
*/
public LinkedPositionUI(ITextViewer viewer, LinkedPositionManager manager) {
Assert.isNotNull(viewer);
Assert.isNotNull(manager);
fViewer= viewer;
fManager= manager;
fManager.setLinkedPositionListener(this);
fFrameColor= viewer.getTextWidget().getDisplay().getSystemColor(SWT.COLOR_RED);
}
/**
* Sets the final position of the caret when the linked mode is exited
* successfully by leaving the last linked position using TAB.
*/
public void setFinalCaretOffset(int offset) {
fFinalCaretOffset= offset;
}
/**
* Sets a <code>CancelListener</code> which is notified if the linked mode
* is exited unsuccessfully by hitting ESC.
*/
public void setCancelListener(ExitListener listener) {
fExitListener= listener;
}
/*
* @see LinkedPositionManager.LinkedPositionListener#setCurrentPositions(Position, int)
*/
public void setCurrentPosition(Position position, int caretOffset) {
if (!fFramePosition.equals(position)) {
redrawRegion();
fFramePosition= position;
}
fCaretOffset= caretOffset;
}
/**
* Enters the linked mode. The linked mode can be left by calling
* <code>exit</code>.
*
* @see exit(boolean)
*/
public void enter() {
// track final caret
IDocument document= fViewer.getDocument();
document.addPositionCategory(CARET_POSITION);
document.addPositionUpdater(fgUpdater);
try {
if (fFinalCaretOffset != -1)
document.addPosition(CARET_POSITION, new Position(fFinalCaretOffset));
} catch (BadLocationException e) {
openErrorDialog(fViewer.getTextWidget().getShell(), e);
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
fViewer.addTextInputListener(this);
StyledText text= fViewer.getTextWidget();
text.addVerifyListener(this);
text.addVerifyKeyListener(this);
text.addModifyListener(this);
text.addPaintListener(this);
text.showSelection();
fFramePosition= fManager.getFirstPosition();
if (fFramePosition == null)
leave(UNINSTALL | COMMIT | UPDATE_CARET);
}
/**
* @see LinkedPositionManager.LinkedPositionListener#exit(boolean)
*/
public void exit(boolean success) {
// no UNINSTALL since manager has already uninstalled itself
leave((success ? COMMIT : 0) | UPDATE_CARET);
}
/**
* Returns the cursor selection, after having entered the linked mode.
* <code>enter()</code> must be called prior to a call to this method.
*/
public IRegion getSelectedRegion() {
if (fFramePosition == null)
return new Region(fFinalCaretOffset, 0);
else
return new Region(fFramePosition.getOffset(), fFramePosition.getLength());
}
private void leave(int flags) {
if ((flags & UNINSTALL) != 0)
fManager.uninstall((flags & COMMIT) != 0);
StyledText text= fViewer.getTextWidget();
text.removePaintListener(this);
text.removeModifyListener(this);
text.removeVerifyKeyListener(this);
text.removeVerifyListener(this);
fViewer.removeTextInputListener(this);
try {
IRegion region= fViewer.getVisibleRegion();
IDocument document= fViewer.getDocument();
if (((flags & COMMIT) != 0) &&
((flags & DOCUMENT_CHANGED) == 0) &&
((flags & UPDATE_CARET) != 0))
{
Position[] positions= document.getPositions(CARET_POSITION);
if ((positions != null) && (positions.length != 0)) {
int offset= positions[0].getOffset() - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
text.setSelection(offset, offset);
}
}
document.removePositionUpdater(fgUpdater);
document.removePositionCategory(CARET_POSITION);
if (fExitListener != null)
fExitListener.exit(
((flags & COMMIT) != 0) ||
((flags & DOCUMENT_CHANGED) != 0));
} catch (BadPositionCategoryException e) {
JavaPlugin.log(e);
Assert.isTrue(false);
}
if ((flags & DOCUMENT_CHANGED) == 0)
text.redraw();
}
private void next() {
redrawRegion();
fFramePosition= fManager.getNextPosition(fFramePosition.getOffset());
if (fFramePosition == null) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
} else {
selectRegion();
redrawRegion();
}
}
private void previous() {
redrawRegion();
Position position= fManager.getPreviousPosition(fFramePosition.getOffset());
if (position == null) {
fViewer.getTextWidget().getDisplay().beep();
} else {
fFramePosition= position;
selectRegion();
redrawRegion();
}
}
/*
* @see VerifyKeyListener#verifyKey(VerifyEvent)
*/
public void verifyKey(VerifyEvent event) {
switch (event.character) {
// [SHIFT-]TAB = hop between edit boxes
case 0x09:
{
Point selection= fViewer.getTextWidget().getSelection();
IRegion region= fViewer.getVisibleRegion();
int offset= selection.x + region.getOffset();
int length= selection.y - selection.x;
// if tab was treated as a document change, would it exceed variable range?
if (!LinkedPositionManager.includes(fFramePosition, offset, length)) {
leave(UNINSTALL | COMMIT | UPDATE_CARET);
return;
}
}
if (event.stateMask == SWT.SHIFT)
previous();
else
next();
event.doit= false;
break;
// ESC = cancel
case 0x1B:
leave(UNINSTALL);
event.doit= false;
break;
}
}
/*
* @see VerifyListener#verifyText(VerifyEvent)
*/
public void verifyText(VerifyEvent event) {
if (!event.doit)
return;
IRegion region= fViewer.getVisibleRegion();
int offset= event.start + region.getOffset();
int length= event.end - event.start;
// allow changes only within linked positions when coming through UI
if (!fManager.anyPositionIncludes(offset, length))
leave(UNINSTALL | COMMIT);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fFramePosition == null)
return;
IRegion region= fViewer.getVisibleRegion();
// #6824
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
StyledText text= fViewer.getTextWidget();
// 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;
gc.setForeground(fFrameColor);
gc.drawLine(x1, y, x2, y);
}
private static Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private static Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
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;
}
private void redrawRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() - region.getOffset();
int length= fFramePosition.getLength();
fViewer.getTextWidget().redrawRange(offset, length, true);
}
private void selectRegion() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int start= fFramePosition.getOffset() - region.getOffset();
int end= fFramePosition.getLength() + start;
fViewer.getTextWidget().setSelection(start, end);
}
private void updateCaret() {
IRegion region= fViewer.getVisibleRegion();
if (!includes(region, fFramePosition)) {
leave(UNINSTALL | COMMIT | DOCUMENT_CHANGED);
return;
}
int offset= fFramePosition.getOffset() + fCaretOffset - region.getOffset();
if ((offset >= 0) && (offset <= region.getLength()))
fViewer.getTextWidget().setCaretOffset(offset);
}
/*
* @see ModifyListener#modifyText(ModifyEvent)
*/
public void modifyText(ModifyEvent e) {
// reposition caret after StyledText
redrawRegion();
updateCaret();
}
private static void openErrorDialog(Shell shell, Exception e) {
MessageDialog.openError(shell, LinkedPositionMessages.getString("LinkedPositionUI.error.title"), e.getMessage()); //$NON-NLS-1$
}
/*
* @see ITextInputListener#inputDocumentAboutToBeChanged(IDocument, IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
// 5326: leave linked mode on document change
int flags= UNINSTALL | COMMIT | (oldInput.equals(newInput) ? 0 : DOCUMENT_CHANGED);
leave(flags);
}
/*
* @see ITextInputListener#inputDocumentChanged(IDocument, IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
}
private static boolean includes(IRegion region, Position position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
}
|
11,748 |
Bug 11748 switch to new DecoratorManager API
|
From the workbench change notes: API changes IWorkbenchPartSite.getDecoratorManager() - As the DecoratorManager has proven to be required for more than just IWorkbenchPartSites we have moved getDecoratorManager() to IWorkbench and deprecated the getDecoratorManager() in IWorkbenchPartSite. The one in IWorkbenchPartSite will be removed after the other Eclipse components have had a chance to switch to the new API.
|
resolved fixed
|
1035d37
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-20T16:58:55Z | 2002-03-19T23:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.Collection;
import java.util.Comparator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
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.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenPerspectiveMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.internal.framelist.BackAction;
import org.eclipse.ui.views.internal.framelist.ForwardAction;
import org.eclipse.ui.views.internal.framelist.GoIntoAction;
import org.eclipse.ui.views.internal.framelist.UpAction;
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.IWorkingCopy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.packageview.BuildGroup;
import org.eclipse.jdt.internal.ui.packageview.OpenResourceAction;
import org.eclipse.jdt.internal.ui.packageview.PackagesMessages;
import org.eclipse.jdt.internal.ui.packageview.ShowInNavigatorAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener {
private ILabelProvider fLabelProvider;
private ILabelProvider fTitleProvider;
private StructuredViewer fViewer;
private IMemento fMemento;
private JavaElementTypeComparator fTypeComparator;
// Actions
private ContextMenuGroup[] fStandardGroups;
private Menu fContextMenu;
private OpenResourceAction fOpenCUAction;
private Action fOpenToAction;
private Action fShowNavigatorAction;
private PropertyDialogAction fPropertyDialogAction;
private IRefactoringAction fDeleteAction;
private RefreshAction fRefreshAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private GoIntoAction fZoomInAction;
private UpAction fUpAction;
// private GotoTypeAction fGotoTypeAction;
// private GotoPackageAction fGotoPackageAction;
private IWorkbenchPart fPreviousSelectionProvider;
private Image fOriginalTitleImage;
/*
* Ensure selection changed events being processed only if
* initiated by user interaction with this part.
*/
private boolean fProcessSelectionEvents= true;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
setSelectionFromEditor(part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
/*
* Implements method from IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* Implements method from IViewPart.
*/
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
// XXX: need to save state here
// fViewer.saveState(memento);
}
/**
* Creates the search list inner viewer.
*/
public void createPartControl(Composite parent) {
Assert.isTrue(fViewer == null);
if (fMemento != null)
// XXX: Restore state here
// fViewer.restoreState(fMemento);
fMemento= null;
fTypeComparator= new JavaElementTypeComparator();
// Setup viewer
fViewer= createViewer(parent);
fLabelProvider= createLabelProvider();
ILabelDecorator decorationMgr= getViewSite().getDecoratorManager();
fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr));
fViewer.setSorter(new JavaElementSorter());
fViewer.setUseHashlookup(true);
JavaPlugin.getDefault().getProblemMarkerManager().addListener((IProblemChangedListener)fViewer);
fTitleProvider= createTitleProvider();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getControl());
fViewer.getControl().setMenu(fContextMenu);
getSite().registerContextMenu(menuMgr, fViewer);
createActions(); // call before registering for selection changes
addKeyListener();
getSite().setSelectionProvider(fViewer);
// Status line
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
hookViewerListeners();
// Initialize viewer input
fViewer.setContentProvider(createContentProvider());
setInitialInput();
// Initialize selecton
setInitialSelection();
// Filters
addFilters();
fillToolBar(getViewSite().getActionBars().getToolBarManager());
// Listen to workbench window changes
getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this);
getViewSite().getPage().addPartListener(fPartListener);
setHelp();
}
//---- IWorkbenchPart ------------------------------------------------------
public void setFocus() {
fViewer.getControl().setFocus();
}
public void dispose() {
if (fViewer != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener((IProblemChangedListener)fViewer);
getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
getViewSite().getPage().removePartListener(fPartListener);
fViewer= null;
}
super.dispose();
}
/**
* Adds the KeyListener
*/
protected void addKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyReleased(event);
}
});
}
protected void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} else if (key == SWT.F4) {
OpenTypeHierarchyUtil.open(getSelectionProvider().getSelection(), getSite().getWorkbenchWindow());
} else if (key == SWT.F3) {
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
fOpenCUAction.run();
}
else if (event.character == SWT.DEL) {
fDeleteAction.update();
if (fDeleteAction.isEnabled())
fDeleteAction.run();
}
}
//---- Adding Action to Toolbar -------------------------------------------
protected void fillToolBar(IToolBarManager tbm) {
// fViewer.fillToolBar(tbm);
}
// protected void setContextMenuContributor(final IContextMenuContributor contributor) {
// // Make sure we are doing it in the right thread.
// getDisplay().syncExec(new Runnable() {
// public void run() {
//// getViewer().setContextMenuTarget(contributor);
// }
// });
// }
/**
* Called when the context menu is about to open.
* Override to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
fPropertyDialogAction.selectionChanged(selection);
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// updateActions(selection);
// Object element= selection.getFirstElement();
// if (selection.size() == 1 && fViewer.isExpandable(element))
// menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
// addGotoMenu(menu);
//
// Open menus
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction);
addOpenWithMenu(menu, selection);
addOpenToMenu(menu, selection);
addRefactoring(menu);
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
fRefreshAction.selectionChanged(selection);
menu.add(new Separator());
if (fPropertyDialogAction.isApplicableForSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void createActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenCUAction= new OpenResourceAction(provider);
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
fShowNavigatorAction= new ShowInNavigatorAction(provider);
fStandardGroups= new ContextMenuGroup[] {
new BuildGroup(),
new ReorgGroup(),
new GenerateGroup(),
new JavaSearchGroup()
};
fDeleteAction= ReorgGroup.createDeleteAction(provider);
fRefreshAction= new RefreshAction(getShell());
// fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
// fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
// fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$
// fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$
// fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$
// fBackAction= new BackAction(fFrameList);
// fForwardAction= new ForwardAction(fFrameList);
// fZoomInAction= new GoIntoAction(fFrameList);
// fUpAction= new UpAction(fFrameList);
// fGotoTypeAction= new GotoTypeAction(this);
// fGotoPackageAction= new GotoPackageAction(this);
IActionBars actionService= getViewSite().getActionBars();
actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction);
ReorgGroup.addGlobalReorgActions(actionService, provider);
}
private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) {
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable) selection.getFirstElement();
IResource resource= (IResource)element.getAdapter(IResource.class);
if ((resource instanceof IContainer)) {
// Create a menu flyout.
MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$
submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource));
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getControl().getShell();
}
protected final Display getDisplay() {
return fViewer.getControl().getDisplay();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* 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
*/
abstract protected boolean isValidInput(Object element);
/**
* 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 == null)
return false;
element= getSuitableJavaElement(element);
if (element == null)
return false;
Object input= getViewer().getInput();
if (input == null)
return false;
if (input instanceof Collection)
return ((Collection)input).contains(element);
else
return input.equals(element);
}
private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) {
if (newInput == null)
return part == fPreviousSelectionProvider;
if (input instanceof IJavaElement && newInput instanceof IJavaElement)
return getTypeComparator().compare(newInput, input) > 0;
else
return false;
}
protected boolean isAncestorOf(Object ancestor, Object element) {
if (element instanceof IJavaElement && ancestor instanceof IJavaElement)
return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element);
return false;
}
private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) {
if (element != null)
return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent());
else
return false;
}
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (!fProcessSelectionEvents || part == this || !(selection instanceof IStructuredSelection))
return;
if (selection.isEmpty() && part instanceof JavaBrowsingPart && !(part instanceof ProjectsView))
return;
// Set input
Object newInput= getElementFromSingleSelection(selection);
Object currentInput= (IJavaElement)getViewer().getInput();
if (newInput != null && newInput.equals(currentInput)) {
IJavaElement elementToSelect= findElementToSelect(getElementFromSingleSelection(selection));
if (elementToSelect != null && getTypeComparator().compare(newInput, elementToSelect) < 0)
setSelection(new StructuredSelection(elementToSelect), true);
fPreviousSelectionProvider= part;
return;
}
// Clear input if needed
if (part != fPreviousSelectionProvider && newInput != null && !newInput.equals(currentInput) && isInputResetBy(newInput, currentInput, part)) {
if (!isAncestorOf(newInput, currentInput))
setInput(null);
fPreviousSelectionProvider= part;
return;
} else if (newInput == null && part == fPreviousSelectionProvider) {
setInput(null);
fPreviousSelectionProvider= part;
return;
}
fPreviousSelectionProvider= part;
// Set selection
if (newInput instanceof IJavaElement)
adjustInputAndSetSelection((IJavaElement)newInput);
else
setSelection(StructuredSelection.EMPTY, true);
}
protected void setInput(Object input) {
if (input == null)
setTitleImage(fOriginalTitleImage);
else if (input instanceof Collection) {
if (((Collection)input).isEmpty())
setTitleImage(fOriginalTitleImage);
else {
Object firstElement= ((Collection)input).iterator().next();
setTitleImage(fTitleProvider.getImage(firstElement));
}
} else
setTitleImage(fTitleProvider.getImage(input));
setViewerInput(input);
}
private void setViewerInput(Object input) {
fProcessSelectionEvents= false;
fViewer.setInput(input);
fProcessSelectionEvents= true;
}
/**
* Sets or clears the title image of this part and
* store the orignal image on the first call.
*/
protected void setTitleImage(Image titleImage) {
if (fOriginalTitleImage == null)
fOriginalTitleImage= getTitleImage();
if (titleImage == null)
titleImage= fOriginalTitleImage;
super.setTitleImage(titleImage);
}
protected final StructuredViewer getViewer() {
return fViewer;
}
protected ILabelProvider createLabelProvider() {
return new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
}
protected ILabelProvider createTitleProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS);
}
protected final ILabelProvider getLabelProvider() {
return fLabelProvider;
}
protected final ILabelProvider getTitleProvider() {
return fTitleProvider;
}
/**
* Creates the the viewer of this part.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
return new ProblemTableViewer(parent, SWT.SINGLE);
}
protected int getLabelProviderFlags() {
return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS |
JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS;
}
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
// default is to have no filters
}
/**
* Creates the the content provider of this part.
*/
protected BaseJavaElementContentProvider createContentProvider() {
return new JavaElementContentProvider(true, this); //
}
protected void setInitialInput() {
// Use the selection, if any
ISelection selection= getSite().getPage().getSelection();
Object input= getElementFromSingleSelection(selection);
if (!(input instanceof IJavaElement)) {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement) && input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
}
setInput(findInputForJavaElement((JavaElement)input));
}
protected void setInitialSelection() {
// Use the selection, if any
Object input;
ISelection selection= getSite().getPage().getSelection();
if (selection != null && !selection.isEmpty())
input= getElementFromSingleSelection(selection);
else {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement) && input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
else
return;
}
if (findElementToSelect((IJavaElement)input) != null)
adjustInputAndSetSelection((IJavaElement)input);
}
final protected void setHelp() {
JavaUIHelp.setHelp(fViewer, getHelpContextId());
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
abstract protected String getHelpContextId();
/**
* Adds additional listeners to this view.
*/
protected void hookViewerListeners() {
fViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
if (!fProcessSelectionEvents)
return;
if (JavaBrowsingPreferencePage.openEditorOnSingleClick())
new ShowInEditorAction().run(event.getSelection(), getSite().getPage());
else
linkToEditor((IStructuredSelection)event.getSelection());
}
});
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
if (fProcessSelectionEvents && !JavaBrowsingPreferencePage.openEditorOnSingleClick())
new ShowInEditorAction().run(event.getSelection(), getSite().getPage());
}
});
}
void adjustInputAndSetSelection(IJavaElement je) {
je= getSuitableJavaElement(je);
IJavaElement elementToSelect= findElementToSelect(je);
IJavaElement newInput= findInputForJavaElement(je);
if (elementToSelect == null && !isValidInput(newInput))
// Clear input
setInput(null);
else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null)
// Adjust input to selection
setInput(findInputForJavaElement(je));
if (elementToSelect != null)
setSelection(new StructuredSelection(elementToSelect), true);
else
setSelection(StructuredSelection.EMPTY, true);
}
/**
* 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)
return null;
if (isValidInput(je))
return je;
return findInputForJavaElement(je.getParent());
}
final protected IJavaElement findElementToSelect(Object obj) {
if (obj instanceof IJavaElement)
return findElementToSelect((IJavaElement)obj);
return null;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
abstract protected IJavaElement findElementToSelect(IJavaElement je);
private Object getElementFromSingleSelection(ISelection selection) {
if (selection instanceof StructuredSelection
&& ((StructuredSelection)selection).size() == 1)
return ((StructuredSelection)selection).getFirstElement();
return null;
}
/**
* Gets the typeComparator.
* @return Returns a JavaElementTypeComparator
*/
protected Comparator getTypeComparator() {
return fTypeComparator;
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
if (selection == null || selection.isEmpty())
return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private void setSelectionFromEditor(IWorkbenchPart part) {
if (part == null)
return;
IWorkbenchPartSite site= part.getSite();
if (site == null)
return;
ISelectionProvider provider= site.getSelectionProvider();
if (provider != null)
setSelectionFromEditor(part, provider.getSelection());
}
private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart && JavaBrowsingPreferencePage.linkViewSelectionToEditor()) {
IEditorInput ei= ((IEditorPart)part).getEditorInput();
if (selection instanceof ITextSelection) {
int offset= ((ITextSelection)selection).getOffset();
IJavaElement element= getElementForInputAt(ei, offset);
if (element != null) {
adjustInputAndSetSelection(element);
return;
}
}
if (ei instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput)ei).getFile();
IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class);
if (je == null) {
setSelection(null, false);
return;
}
adjustInputAndSetSelection(je);
} else if (ei instanceof IClassFileEditorInput) {
IClassFile cf= ((IClassFileEditorInput)ei).getClassFile();
adjustInputAndSetSelection(cf);
}
return;
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
private void setSelection(ISelection selection, boolean reveal) {
if (selection != null && selection.equals(fViewer.getSelection()))
return;
fProcessSelectionEvents= false;
fViewer.setSelection(selection, reveal);
fProcessSelectionEvents= true;
}
/**
* Tries to find the given element in a workingcopy.
*/
protected static IJavaElement getWorkingCopy(IJavaElement input) {
try {
if (input instanceof ICompilationUnit)
return EditorUtility.getWorkingCopy((ICompilationUnit)input);
else
return EditorUtility.getWorkingCopy(input, true);
} catch (JavaModelException ex) {
}
return null;
}
/**
* Returns the original element from which the specified working copy
* element was created from. This is a handle only method, the
* returned element may or may not exist.
*
* @param workingCopy the element for which to get the original
* @return the original Java element or <code>null</code> if this is not a working copy element
*/
protected static IJavaElement getOriginal(IJavaElement workingCopy) {
ICompilationUnit cu= getCompilationUnit(workingCopy);
if (cu != null)
return ((IWorkingCopy)cu).getOriginal(workingCopy);
return null;
}
/**
* Returns the compilation unit for the given java element.
*
* @param element the java element whose compilation unit is searched for
* @return the compilation unit of the given java element
*/
protected static ICompilationUnit getCompilationUnit(IJavaElement element) {
if (element == null)
return null;
if (element instanceof IMember)
return ((IMember) element).getCompilationUnit();
int type= element.getElementType();
if (IJavaElement.COMPILATION_UNIT == type)
return (ICompilationUnit) element;
if (IJavaElement.CLASS_FILE == type)
return null;
return getCompilationUnit(element.getParent());
}
/**
* Converts the given Java element to one which is suitable for this
* view. It takes into account wether the view shows working copies or not.
*
* @param element the Java element to be converted
* @return an element suitable for this view
*/
protected IJavaElement getSuitableJavaElement(Object obj) {
if (!(obj instanceof IJavaElement))
return null;
IJavaElement element= (IJavaElement)obj;
if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0)
return element;
if (element.getElementType() == IJavaElement.CLASS_FILE)
return element;
if (((BaseJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy()) {
IJavaElement wc= getWorkingCopy(element);
if (wc != null)
element= wc;
return element;
}
else {
ICompilationUnit cu= getCompilationUnit(element);
if (cu != null && ((IWorkingCopy)cu).isWorkingCopy())
return ((IWorkingCopy)cu).getOriginal(element);
else
return element;
}
}
/**
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementForInputAt(IEditorInput input, int offset) {
if (input instanceof IClassFileEditorInput) {
try {
return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset);
} catch (JavaModelException ex) {
return null;
}
}
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(input);
if (unit != null)
synchronized (unit) {
try {
unit.reconcile(null);
return unit.getElementAt(offset);
} catch (JavaModelException x) {
}
}
return null;
}
protected IType getTypeForCU(ICompilationUnit cu) {
cu= (ICompilationUnit)getSuitableJavaElement(cu);
// Use primary type if possible
IType primaryType= JavaModelUtil.findPrimaryType(cu);
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;
}
}
}
|
11,748 |
Bug 11748 switch to new DecoratorManager API
|
From the workbench change notes: API changes IWorkbenchPartSite.getDecoratorManager() - As the DecoratorManager has proven to be required for more than just IWorkbenchPartSites we have moved getDecoratorManager() to IWorkbench and deprecated the getDecoratorManager() in IWorkbenchPartSite. The one in IWorkbenchPartSite will be removed after the other Eclipse components have had a chance to switch to the new API.
|
resolved fixed
|
1035d37
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-20T16:58:55Z | 2002-03-19T23:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import org.eclipse.swt.SWT;
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.util.Assert;
import org.eclipse.jface.util.ListenerList;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
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.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.jdt.core.ElementChangedEvent;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IElementChangedListener;
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.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaElementSorter;
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.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.actions.OpenHierarchyAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.viewsupport.OverrideAdornmentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
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() + ".outliner"</code>.
*/
class JavaOutlinePage extends Page implements IContentOutlinePage {
/**
* The element change listener of the java outline viewer.
* @see IElementChangedListener
*/
class ElementChangedListener implements IElementChangedListener {
public void elementChanged(final ElementChangedEvent e) {
Display d= getControl().getDisplay();
if (d != null) {
d.asyncExec(new Runnable() {
public void run() {
IJavaElementDelta delta= findElement( (ICompilationUnit) fInput, e.getDelta());
if (delta != null && fOutlineViewer != null) {
fOutlineViewer.reconcile(delta);
}
}
});
}
}
protected IJavaElementDelta findElement(ICompilationUnit 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;
}
};
/**
* Content provider for the children of an ICompilationUnit or
* an IClassFile
* @see ITreeContentProvider
*/
class ChildrenProvider implements ITreeContentProvider {
private ElementChangedListener fListener;
private JavaOutlineErrorTickUpdater fErrorTickUpdater;
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.getDefault().logErrorStatus(JavaEditorMessages.getString("JavaOutlinePage.error.ChildrenProvider.getChildren.message1"), x.getStatus()); //$NON-NLS-1$
}
}
return new Object[0];
}
public Object[] getElements(Object parent) {
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.getDefault().logErrorStatus(JavaEditorMessages.getString("JavaOutlinePage.error.ChildrenProvider.hasChildren.message1"), x.getStatus()); //$NON-NLS-1$
}
}
return false;
}
public boolean isDeleted(Object o) {
return false;
}
public void dispose() {
if (fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
}
if (fErrorTickUpdater != null) {
fErrorTickUpdater.setAnnotationModel(null);
fErrorTickUpdater= 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);
fErrorTickUpdater= new JavaOutlineErrorTickUpdater(fOutlineViewer);
fErrorTickUpdater.setAnnotationModel(fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput()));
} else if (isCU && fErrorTickUpdater != null) {
fErrorTickUpdater.setAnnotationModel(fEditor.getDocumentProvider().getAnnotationModel(fEditor.getEditorInput()));
} else if (!isCU && fListener != null) {
JavaCore.removeElementChangedListener(fListener);
fListener= null;
fErrorTickUpdater.setAnnotationModel(null);
fErrorTickUpdater= 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;
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) {
if (getSorter() == null) {
Widget w= findItem(fInput);
if (w != null)
update(w, delta);
} else {
// just for now
refresh();
}
}
/*
* @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;
}
/*
* @see TreeViewer#createTreeItem
*/
protected void createTreeItem(Widget parent, Object element, int ix) {
Item[] children= getChildren(parent);
boolean expand= (parent instanceof Item && (children == null || children.length == 0));
Item item= newItem(parent, SWT.NULL, ix);
updateItem(item, element);
updatePlus(item, element);
if (expand)
setExpanded((Item) parent, true);
internalExpandToLevel(item, ALL_LEVELS);
}
protected boolean mustUpdateParent(IJavaElementDelta delta, IJavaElement element) {
if (element instanceof IMethod) {
if ((delta.getKind() & IJavaElementDelta.ADDED) != 0) {
try {
return JavaModelUtil.isMainMethod((IMethod)element);
} 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)
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);
}
}
// 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());
}
};
class LexicalSortingAction extends Action {
private JavaElementSorter fSorter= new JavaElementSorter();
public LexicalSortingAction() {
super();
setText(JavaEditorMessages.getString("JavaOutlinePage.Sort.label")); //$NON-NLS-1$
JavaPluginImages.setLocalImageDescriptors(this, "alphab_sort_co.gif"); //$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(boolean on, boolean store) {
setChecked(on);
fOutlineViewer.setSorter(on ? fSorter : null);
setToolTipText(on ? JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip.checked") : JavaEditorMessages.getString("JavaOutlinePage.Sort.tooltip.unchecked")); //$NON-NLS-2$ //$NON-NLS-1$
setDescription(on ? JavaEditorMessages.getString("JavaOutlinePage.Sort.description.checked") : JavaEditorMessages.getString("JavaOutlinePage.Sort.description.unchecked")); //$NON-NLS-2$ //$NON-NLS-1$
if (store)
JavaPlugin.getDefault().getPreferenceStore().setValue("LexicalSortingAction.isChecked", on); //$NON-NLS-1$
}
};
private IJavaElement fInput;
private String fContextMenuID;
private Menu fMenu;
private JavaOutlineViewer fOutlineViewer;
private JavaEditor fEditor;
private MemberFilterActionGroup fMemberFilterActionGroup;
private ListenerList fSelectionChangedListeners= new ListenerList();
private Hashtable fActions= new Hashtable();
private ContextMenuGroup[] fActionGroups;
public JavaOutlinePage(String contextMenuID, JavaEditor editor) {
super();
Assert.isNotNull(editor);
fContextMenuID= contextMenuID;
fEditor= editor;
}
/*
* @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();
}
private void registerToolbarActions() {
IToolBarManager toolBarManager= getSite().getActionBars().getToolBarManager();
if (toolBarManager != null) {
Action action= new LexicalSortingAction();
toolBarManager.add(action);
fMemberFilterActionGroup= new MemberFilterActionGroup(fOutlineViewer, "JavaOutlineViewer");
fMemberFilterActionGroup.contributeToToolBar(toolBarManager);
}
}
/*
* @see IPage#createControl
*/
public void createControl(Composite parent) {
Tree tree= new Tree(parent, SWT.MULTI);
StandardJavaUILabelProvider lprovider= new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.F_APP_TYPE_SIGNATURE,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS,
StandardJavaUILabelProvider.getAdornmentProviders(true, new OverrideAdornmentProvider())
);
fOutlineViewer= new JavaOutlineViewer(tree);
fOutlineViewer.setContentProvider(new ChildrenProvider());
fOutlineViewer.setLabelProvider(new DecoratingLabelProvider(
lprovider, fEditor.getSite().getDecoratorManager()));
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++) {
fSelectionChangedListeners.remove(listeners[i]);
fOutlineViewer.addSelectionChangedListener((ISelectionChangedListener) listeners[i]);
}
MenuManager manager= new MenuManager(fContextMenuID, fContextMenuID);
manager.setRemoveAllWhenShown(true);
manager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(IMenuManager manager) {
contextMenuAboutToShow(manager);
}
});
fMenu= manager.createContextMenu(tree);
tree.setMenu(fMenu);
getSite().registerContextMenu(JavaPlugin.getDefault().getPluginId() + ".outline", manager, fOutlineViewer);
getSite().setSelectionProvider(fOutlineViewer);
IStatusLineManager statusLineManager= getSite().getActionBars().getStatusLineManager();
if (statusLineManager != null) {
StatusBarUpdater updater= new StatusBarUpdater(statusLineManager);
fOutlineViewer.addSelectionChangedListener(updater);
}
registerToolbarActions();
fActionGroups= new ContextMenuGroup[] { new GenerateGroup(), new JavaSearchGroup(), new ReorgGroup() };
ReorgGroup.addGlobalReorgActions(getSite().getActionBars(), fOutlineViewer);
fOutlineViewer.setInput(fInput);
fOutlineViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
handleKeyPressed(e);
}
});
}
public void dispose() {
if (fEditor == null)
return;
fEditor.outlinePageClosed();
fEditor= null;
Object[] listeners= fSelectionChangedListeners.getListeners();
for (int i= 0; i < listeners.length; i++)
fSelectionChangedListeners.remove(listeners[i]);
fSelectionChangedListeners= null;
if (fMenu != null && !fMenu.isDisposed()) {
fMenu.dispose();
fMenu= 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);
}
/**
* 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);
}
}
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(JavaEditorMessages.getString("JavaOutlinePage.ContextMenu.refactoring.label")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fOutlineViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenPerspectiveItem(IMenuManager menu) {
ISelection s= getSelection();
if (s.isEmpty() || ! (s instanceof IStructuredSelection))
return;
IStructuredSelection selection= (IStructuredSelection)s;
if (selection.size() != 1)
return;
Object element= selection.getFirstElement();
if (!(element instanceof IType))
return;
IType[] input= {(IType)element};
IWorkbenchWindow w= getSite().getWorkbenchWindow();
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, new OpenHierarchyAction(w, input));
}
protected void contextMenuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
if (OrganizeImportsAction.canActionBeAdded(getSelection())) {
addAction(menu, IContextMenuConstants.GROUP_REORGANIZE, "OrganizeImports"); //$NON-NLS-1$
}
addAction(menu, IContextMenuConstants.GROUP_OPEN, "OpenImportDeclaration"); //$NON-NLS-1$
addAction(menu, IContextMenuConstants.GROUP_SHOW, "ShowInPackageView"); //$NON-NLS-1$
ContextMenuGroup.add(menu, fActionGroups, fOutlineViewer);
addRefactoring(menu);
addOpenPerspectiveItem(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.getElementType() == IJavaElement.TYPE) {
IJavaElement parent= element.getParent();
int type= parent.getElementType();
return (type != IJavaElement.COMPILATION_UNIT && type != IJavaElement.CLASS_FILE);
}
return false;
}
/**
* Handles key events in viewer.
*/
private void handleKeyPressed(KeyEvent event) {
if (event.stateMask != 0)
return;
IAction action= null;
if (event.character == SWT.DEL) {
action= getAction("DeleteElement"); //$NON-NLS-1$
if (action instanceof IRefactoringAction){
//special case - DeleteAction is not a ISelectionChangedListener
((IRefactoringAction)action).update();
if (! action.isEnabled())
return;
}
} else if (event.keyCode == SWT.F4) {
// Special case since Open Type Hierarchy is no action.
OpenTypeHierarchyUtil.open(getSelection(), fEditor.getSite().getWorkbenchWindow());
}
if (action != null && action.isEnabled())
action.run();
}
}
|
11,748 |
Bug 11748 switch to new DecoratorManager API
|
From the workbench change notes: API changes IWorkbenchPartSite.getDecoratorManager() - As the DecoratorManager has proven to be required for more than just IWorkbenchPartSites we have moved getDecoratorManager() to IWorkbench and deprecated the getDecoratorManager() in IWorkbenchPartSite. The one in IWorkbenchPartSite will be removed after the other Eclipse components have had a chance to switch to the new API.
|
resolved fixed
|
1035d37
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-20T16:58:55Z | 2002-03-19T23:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DragSource;
import org.eclipse.swt.dnd.FileTransfer;
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.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.Action;
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.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
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.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.AddBookmarkAction;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenPerspectiveMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.part.ISetSelectionTarget;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.internal.framelist.BackAction;
import org.eclipse.ui.views.internal.framelist.ForwardAction;
import org.eclipse.ui.views.internal.framelist.FrameList;
import org.eclipse.ui.views.internal.framelist.GoIntoAction;
import org.eclipse.ui.views.internal.framelist.UpAction;
import org.eclipse.search.ui.IWorkingSet;
import org.eclipse.search.ui.SearchUI;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IPackagesViewPart;
import org.eclipse.jdt.ui.JavaElementContentProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
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.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter;
import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter;
import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer;
import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter;
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.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
/**
* The ViewPart for the ProjectExplorer. It listens to part activation events.
* When selection linking with the editor is enabled the view selection tracks
* the active editor page. Similarly when a resource is selected in the packages
* view the corresponding editor is activated.
*/
public class PackageExplorerPart extends ViewPart implements ISetSelectionTarget, IMenuListener, IPackagesViewPart, IPropertyChangeListener {
public final static String VIEW_ID= JavaUI.ID_PACKAGES;
// Persistance tags.
static final String TAG_SELECTION= "selection"; //$NON-NLS-1$
static final String TAG_EXPANDED= "expanded"; //$NON-NLS-1$
static final String TAG_ELEMENT= "element"; //$NON-NLS-1$
static final String TAG_PATH= "path"; //$NON-NLS-1$
static final String TAG_VERTICAL_POSITION= "verticalPosition"; //$NON-NLS-1$
static final String TAG_HORIZONTAL_POSITION= "horizontalPosition"; //$NON-NLS-1$
static final String TAG_FILTERS = "filters"; //$NON-NLS-1$
static final String TAG_FILTER = "filter"; //$NON-NLS-1$
static final String TAG_SHOWLIBRARIES = "showLibraries"; //$NON-NLS-1$
static final String TAG_SHOWBINARIES = "showBinaries"; //$NON-NLS-1$
static final String TAG_WORKINGSET = "workingset"; //$NON-NLS-1$
private JavaElementPatternFilter fPatternFilter= new JavaElementPatternFilter();
private LibraryFilter fLibraryFilter= new LibraryFilter();
private BinaryProjectFilter fBinaryFilter= new BinaryProjectFilter();
private WorkingSetFilter fWorkingSetFilter= new WorkingSetFilter();
private MemberFilterActionGroup fMemberFilterActionGroup;
private ProblemTreeViewer fViewer;
private StandardJavaUILabelProvider fJavaElementLabelProvider;
private PackagesFrameSource fFrameSource;
private FrameList fFrameList;
private ContextMenuGroup[] fStandardGroups;
private Menu fContextMenu;
private OpenResourceAction fOpenCUAction;
private Action fOpenToAction;
private Action fShowTypeHierarchyAction;
private Action fShowNavigatorAction;
private PropertyDialogAction fPropertyDialogAction;
private IRefactoringAction fDeleteAction;
private RefreshAction fRefreshAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private GoIntoAction fZoomInAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private AddBookmarkAction fAddBookmarkAction;
private FilterSelectionAction fFilterAction;
private ShowLibrariesAction fShowLibrariesAction;
private ShowBinariesAction fShowBinariesAction;
private FilterWorkingSetAction fFilterWorkingSetAction;
private RemoveWorkingSetFilterAction fRemoveWorkingSetAction;
private IMemento fMemento;
private ISelectionChangedListener fSelectionListener;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
if (part instanceof IEditorPart)
editorActivated((IEditorPart) part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
private ITreeViewerListener fExpansionListener= new ITreeViewerListener() {
public void treeCollapsed(TreeExpansionEvent event) {
}
public void treeExpanded(TreeExpansionEvent event) {
Object element= event.getElement();
if (element instanceof ICompilationUnit ||
element instanceof IClassFile)
expandMainType(element);
}
};
public PackageExplorerPart() {
}
/* (non-Javadoc)
* Method declared on IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/**
* Initializes the default preferences
*/
public static void initDefaults(IPreferenceStore store) {
store.setDefault(TAG_SHOWLIBRARIES, true);
store.setDefault(TAG_SHOWBINARIES, true);
}
/**
* Returns the package explorer part of the active perspective. If
* there isn't any package explorer part <code>null</code> is returned.
*/
public static PackageExplorerPart getFromActivePerspective() {
IViewPart view= JavaPlugin.getActivePage().findView(VIEW_ID);
if (view instanceof PackageExplorerPart)
return (PackageExplorerPart)view;
return null;
}
/**
* Makes the package explorer part visible in the active perspective. If there
* isn't a package explorer part registered <code>null</code> is returned.
* Otherwise the opened view part is returned.
*/
public static PackageExplorerPart openInActivePerspective() {
try {
return (PackageExplorerPart)JavaPlugin.getActivePage().showView(VIEW_ID);
} catch(PartInitException pe) {
return null;
}
}
public void dispose() {
if (fViewer != null)
JavaPlugin.getDefault().getProblemMarkerManager().removeListener(fViewer);
if (fContextMenu != null && !fContextMenu.isDisposed())
fContextMenu.dispose();
getSite().getPage().removePartListener(fPartListener);
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
if (fViewer != null)
fViewer.removeTreeListener(fExpansionListener);
super.dispose();
}
/**
* Implementation of IWorkbenchPart.createPartControl(Composite)
*/
public void createPartControl(Composite parent) {
fViewer= new ProblemTreeViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
fViewer.setContentProvider(new JavaElementContentProvider(showCUChildren, false));
JavaPlugin.getDefault().getProblemMarkerManager().addListener(fViewer);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
fJavaElementLabelProvider=
new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS | JavaElementLabels.P_COMPRESSED,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
fViewer.setLabelProvider(new DecoratingLabelProvider(
fJavaElementLabelProvider, getViewSite().getDecoratorManager())
);
fViewer.setSorter(new JavaElementSorter());
fViewer.addFilter(new EmptyInnerPackageFilter());
fViewer.setUseHashlookup(true);
fViewer.addFilter(fPatternFilter);
fViewer.addFilter(fLibraryFilter);
fMemberFilterActionGroup= new MemberFilterActionGroup(fViewer, "PackageView"); // adds filter
fViewer.addFilter(fWorkingSetFilter);
if(fMemento != null)
restoreFilters();
else
initFilterFromPreferences();
// Set input after filter and sorter has been set. This avoids resorting
// and refiltering.
fViewer.setInput(findInputElement());
initDragAndDrop();
initFrameList();
initKeyListener();
updateTitle();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getTree());
fViewer.getTree().setMenu(fContextMenu);
getSite().registerContextMenu(menuMgr, fViewer);
makeActions(); // call before registering for selection changes
fSelectionListener= new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
handleSelectionChanged(event);
}
};
fViewer.addSelectionChangedListener(fSelectionListener);
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
handleDoubleClick(event);
}
});
getSite().setSelectionProvider(fViewer);
getSite().getPage().addPartListener(fPartListener);
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
fViewer.addTreeListener(fExpansionListener);
if (fMemento != null)
restoreState(fMemento);
fMemento= null;
// Set help for the view
JavaUIHelp.setHelp(fViewer, IJavaHelpContextIds.PACKAGES_VIEW);
fillActionBars();
}
private void fillActionBars() {
IActionBars actionBars= getViewSite().getActionBars();
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
actionBars.updateActionBars();
IMenuManager menu= actionBars.getMenuManager();
menu.add(fFilterAction);
menu.add(fShowLibrariesAction);
//menu.add(fShowBinariesAction);
menu.add(fFilterWorkingSetAction);
menu.add(fRemoveWorkingSetAction);
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
private void fillToolBar(IToolBarManager toolBar) {
toolBar.removeAll();
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
if (JavaBasePreferencePage.showCompilationUnitChildren()) {
toolBar.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(toolBar);
}
}
private Object findInputElement() {
Object input= getSite().getPage().getInput();
if (input instanceof IWorkspace) {
return JavaCore.create(((IWorkspace)input).getRoot());
} else if (input instanceof IContainer) {
return JavaCore.create((IContainer)input);
}
//1GERPRT: ITPJUI:ALL - Packages View is empty when shown in Type Hierarchy Perspective
// we can't handle the input
// fall back to show the workspace
return JavaCore.create(JavaPlugin.getWorkspace().getRoot());
}
/**
* Answer the property defined by key.
*/
public Object getAdapter(Class key) {
if (key.equals(ISelectionProvider.class))
return fViewer;
return super.getAdapter(key);
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= PackagesMessages.getString("PackageExplorer.title"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
IWorkingSet ws= fWorkingSetFilter.getWorkingSet();
if (ws == null)
return result;
String wsstr= "Working Set: "+ws.getName();
if (result.length() == 0)
return wsstr;
return result + " - " + wsstr;
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
/**
* @see IWorkbenchPart#setFocus()
*/
public void setFocus() {
fViewer.getTree().setFocus();
}
/**
* Sets the working set to be used for filtering this part
*/
public void setWorkingSet(IWorkingSet ws) {
fWorkingSetFilter.setWorkingSet(ws);
firePropertyChange(IWorkbenchPart.PROP_TITLE);
fFilterWorkingSetAction.setChecked(ws != null);
fRemoveWorkingSetAction.setEnabled(ws != null);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getTree().getShell();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* Returns the current selection.
*/
private ISelection getSelection() {
return fViewer.getSelection();
}
//---- Action handling ----------------------------------------------------------
/**
* Called when the context menu is about to open. Override
* to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
Object element= selection.getFirstElement();
fPropertyDialogAction.selectionChanged(selection);
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// updateActions(selection);
if (selection.size() == 1 && fViewer.isExpandable(element))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
addGotoMenu(menu);
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction);
addOpenWithMenu(menu, selection);
addOpenToMenu(menu, selection);
addRefactoring(menu);
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
if (onlyFilesSelected(selection)) {
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddBookmarkAction);
fAddBookmarkAction.selectionChanged(selection);
}
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
fRefreshAction.selectionChanged(selection);
menu.add(new Separator());
if (fPropertyDialogAction.isApplicableForSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
void addGotoMenu(IMenuManager menu) {
MenuManager gotoMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.gotoTitle")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, gotoMenu);
gotoMenu.add(fBackAction);
gotoMenu.add(fForwardAction);
gotoMenu.add(fUpAction);
gotoMenu.add(fGotoTypeAction);
gotoMenu.add(fGotoPackageAction);
}
private boolean onlyFilesSelected(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
for (Iterator enum= selection.iterator(); enum.hasNext();) {
Object o= enum.next();
if (o instanceof IFile)
continue;
if (o instanceof IAdaptable) {
Object resource= ((IAdaptable)o).getAdapter(IResource.class);
if (!(resource instanceof IFile))
return false;
} else {
return false;
}
}
return true;
}
private void makeActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenCUAction= new OpenResourceAction(provider);
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
// fShowTypeHierarchyAction= new ShowTypeHierarchyAction(provider);
fShowNavigatorAction= new ShowInNavigatorAction(provider);
fAddBookmarkAction= new AddBookmarkAction(getShell());
fStandardGroups= new ContextMenuGroup[] {
new BuildGroup(),
new ReorgGroup(),
new GenerateGroup(),
new JavaSearchGroup()
};
fDeleteAction= ReorgGroup.createDeleteAction(provider);
fRefreshAction= new RefreshAction(getShell());
fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$
fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$
fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$
fBackAction= new BackAction(fFrameList);
fForwardAction= new ForwardAction(fFrameList);
fZoomInAction= new GoIntoAction(fFrameList);
fUpAction= new UpAction(fFrameList);
fGotoTypeAction= new GotoTypeAction(this);
fGotoPackageAction= new GotoPackageAction(this);
IActionBars actionService= getViewSite().getActionBars();
actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction);
ReorgGroup.addGlobalReorgActions(actionService, getSelectionProvider());
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) {
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable) selection.getFirstElement();
IResource resource= (IResource)element.getAdapter(IResource.class);
if ((resource instanceof IContainer)) {
// Create a menu flyout.
MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$
submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource));
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
private boolean isSelectionOfType(ISelection s, Class clazz, boolean considerUnderlyingResource) {
if (! (s instanceof IStructuredSelection) || s.isEmpty())
return false;
IStructuredSelection selection= (IStructuredSelection)s;
Iterator iter= selection.iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (clazz.isInstance(o))
return true;
if (considerUnderlyingResource) {
if (! (o instanceof IJavaElement))
return false;
IJavaElement element= (IJavaElement)o;
Object resource= element.getAdapter(IResource.class);
if (! clazz.isInstance(resource))
return false;
}
}
return true;
}
//---- Event handling ----------------------------------------------------------
private void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE;
final LocalSelectionTransfer lt= LocalSelectionTransfer.getInstance();
Transfer[] transfers= new Transfer[] {
lt,
ResourceTransfer.getInstance(),
FileTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer),
new FileTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(fViewer),
new FileTransferDragAdapter(fViewer)
};
DragSource source= new DragSource(control, ops);
// Note, that the transfer agents are set by the delegating drag adapter itself.
source.addDragListener(new DelegatingDragAdapter(dragListeners));
}
/**
* Handles double clicks in viewer.
* Opens editor if file double-clicked.
*/
private void handleDoubleClick(DoubleClickEvent event) {
IStructuredSelection s= (IStructuredSelection) event.getSelection();
Object element= s.getFirstElement();
if (fOpenCUAction.isEnabled()) {
fOpenCUAction.run();
return;
}
if (fViewer.isExpandable(element)) {
if (JavaBasePreferencePage.doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
fViewer.setExpandedState(element, !fViewer.getExpandedState(element));
//expandMainType(element);
}
}
}
/**
* Handles selection changed in viewer.
* Updates global actions.
* Links to editor (if option enabled)
*/
private void handleSelectionChanged(SelectionChangedEvent event) {
IStructuredSelection sel= (IStructuredSelection) event.getSelection();
//updateGlobalActions(sel);
fZoomInAction.update();
linkToEditor(sel);
}
public void selectReveal(ISelection selection) {
ISelection javaSelection= convertSelection(selection);
fViewer.setSelection(javaSelection, true);
}
private ISelection convertSelection(ISelection s) {
List converted= new ArrayList();
if (s instanceof StructuredSelection) {
Object[] elements= ((StructuredSelection)s).toArray();
for (int i= 0; i < elements.length; i++) {
Object e= elements[i];
if (e instanceof IJavaElement)
converted.add(e);
else if (e instanceof IResource) {
IJavaElement element= JavaCore.create((IResource)e);
if (element != null)
converted.add(element);
else
converted.add(e);
}
}
}
return new StructuredSelection(converted.toArray());
}
public void selectAndReveal(Object element) {
selectReveal(new StructuredSelection(element));
}
/**
* Returns whether the preference to link selection to active editor is enabled.
*/
boolean isLinkingEnabled() {
return JavaBasePreferencePage.linkPackageSelectionToEditor();
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
//if (!isLinkingEnabled())
// return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
saveExpansionState(memento);
saveSelectionState(memento);
saveScrollState(memento, fViewer.getTree());
savePatternFilterState(memento);
saveFilterState(memento);
saveWorkingSetState(memento);
saveMemberFilterState(memento);
}
protected void saveFilterState(IMemento memento) {
boolean showLibraries= getLibraryFilter().getShowLibraries();
String show= "true"; //$NON-NLS-1$
if (!showLibraries)
show= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWLIBRARIES, show);
//save binary filter
boolean showBinaries= getBinaryFilter().getShowBinaries();
String showBinString= "true"; //$NON-NLS-1$
if (!showBinaries)
showBinString= "false"; //$NON-NLS-1$
memento.putString(TAG_SHOWBINARIES, showBinString);
}
protected void savePatternFilterState(IMemento memento) {
String filters[] = getPatternFilter().getPatterns();
if(filters.length > 0) {
IMemento filtersMem = memento.createChild(TAG_FILTERS);
for (int i = 0; i < filters.length; i++){
IMemento child = filtersMem.createChild(TAG_FILTER);
child.putString(TAG_ELEMENT,filters[i]);
}
}
}
protected void saveScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_POSITION, String.valueOf(position));
//save horizontal position
bar= tree.getHorizontalBar();
position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_HORIZONTAL_POSITION, String.valueOf(position));
}
protected void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTION);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
}
}
}
protected void saveExpansionState(IMemento memento) {
Object expandedElements[]= fViewer.getExpandedElements();
if (expandedElements.length > 0) {
IMemento expandedMem= memento.createChild(TAG_EXPANDED);
for (int i= 0; i < expandedElements.length; i++) {
IMemento elementMem= expandedMem.createChild(TAG_ELEMENT);
// we can only persist JavaElements for now
Object o= expandedElements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_PATH, ((IJavaElement) expandedElements[i]).getHandleIdentifier());
}
}
}
protected void saveWorkingSetState(IMemento memento) {
IWorkingSet ws= getWorkingSetFilter().getWorkingSet();
if (ws != null) {
memento.putString(TAG_WORKINGSET, ws.getName());
}
}
/**
* Saves the state of the filter actions
*/
public void saveMemberFilterState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
}
void restoreState(IMemento memento) {
restoreExpansionState(memento);
restoreSelectionState(memento);
restoreScrollState(memento, fViewer.getTree());
}
protected void restoreScrollState(IMemento memento, Tree tree) {
ScrollBar bar= tree.getVerticalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_VERTICAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore, don't set scrollposition
}
}
bar= tree.getHorizontalBar();
if (bar != null) {
try {
String posStr= memento.getString(TAG_HORIZONTAL_POSITION);
int position;
position= new Integer(posStr).intValue();
bar.setSelection(position);
} catch (NumberFormatException e) {
// ignore don't set scroll position
}
}
}
protected void restoreSelectionState(IMemento memento) {
IMemento childMem;
childMem= memento.getChild(TAG_SELECTION);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
list.add(element);
}
fViewer.setSelection(new StructuredSelection(list));
}
}
protected void restoreExpansionState(IMemento memento) {
IMemento childMem= memento.getChild(TAG_EXPANDED);
if (childMem != null) {
ArrayList elements= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
Object element= JavaCore.create(elementMem[i].getString(TAG_PATH));
elements.add(element);
}
fViewer.setExpandedElements(elements.toArray());
}
}
/**
* Create the KeyListener for doing the refresh on the viewer.
*/
private void initKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
doKeyPressed(event);
}
});
}
private void doKeyPressed(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} else if (key == SWT.F4) {
OpenTypeHierarchyUtil.open(getSelection(), getSite().getWorkbenchWindow());
} else if (key == SWT.F3) {
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
fOpenCUAction.run();
} else if (event.character == SWT.DEL){
fDeleteAction.update();
if (fDeleteAction.isEnabled())
fDeleteAction.run();
}
}
void initFrameList() {
fFrameSource= new PackagesFrameSource(this);
fFrameList= new FrameList(fFrameSource);
fFrameSource.connectTo(fFrameList);
}
/**
* An editor has been activated. Set the selection in this Packages Viewer
* to be the editor's input, if linking is enabled.
*/
void editorActivated(IEditorPart editor) {
if (!isLinkingEnabled())
return;
Object input= getElementOfInput(editor.getEditorInput());
Object element= null;
if (input instanceof IFile)
element= JavaCore.create((IFile)input);
if (element == null) // try a non Java resource
element= input;
if (element != null) {
// if the current selection is a child of the new
// selection then ignore it.
IStructuredSelection oldSelection= (IStructuredSelection)getSelection();
if (oldSelection.size() == 1) {
Object o= oldSelection.getFirstElement();
if (o instanceof IMember) {
IMember m= (IMember)o;
if (element.equals(m.getCompilationUnit()))
return;
if (element.equals(m.getClassFile()))
return;
}
}
ISelection newSelection= new StructuredSelection(element);
if (!fViewer.getSelection().equals(newSelection)) {
try {
fViewer.removeSelectionChangedListener(fSelectionListener);
fViewer.setSelection(newSelection);
} finally {
fViewer.addSelectionChangedListener(fSelectionListener);
}
}
}
}
/**
* A compilation unit or class was expanded, expand
* the main type.
*/
void expandMainType(Object element) {
try {
IType type= null;
if (element instanceof ICompilationUnit) {
ICompilationUnit cu= (ICompilationUnit)element;
IType[] types= cu.getTypes();
if (types.length > 0)
type= types[0];
}
else if (element instanceof IClassFile) {
IClassFile cf= (IClassFile)element;
type= cf.getType();
}
if (type != null) {
final IType type2= type;
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.expandToLevel(type2, 1);
}
});
}
}
} catch(JavaModelException e) {
// no reveal
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
/**
* Returns the Viewer.
*/
TreeViewer getViewer() {
return fViewer;
}
/**
* Returns the pattern filter for this view.
* @return the pattern filter
*/
JavaElementPatternFilter getPatternFilter() {
return fPatternFilter;
}
/**
* Returns the library filter for this view.
* @return the library filter
*/
LibraryFilter getLibraryFilter() {
return fLibraryFilter;
}
/**
* Returns the working set filter for this view.
* @return the working set filter
*/
WorkingSetFilter getWorkingSetFilter() {
return fWorkingSetFilter;
}
/**
* Returns the Binary filter for this view.
* @return the binary filter
*/
BinaryProjectFilter getBinaryFilter() {
return fBinaryFilter;
}
void restoreFilters() {
IMemento filtersMem= fMemento.getChild(TAG_FILTERS);
if(filtersMem != null) {
IMemento children[]= filtersMem.getChildren(TAG_FILTER);
String filters[]= new String[children.length];
for (int i = 0; i < children.length; i++) {
filters[i]= children[i].getString(TAG_ELEMENT);
}
getPatternFilter().setPatterns(filters);
} else {
getPatternFilter().setPatterns(new String[0]);
}
//restore library
String show= fMemento.getString(TAG_SHOWLIBRARIES);
if (show != null)
getLibraryFilter().setShowLibraries(show.equals("true")); //$NON-NLS-1$
else
initLibraryFilterFromPreferences();
//restore binary fileter
String showbin= fMemento.getString(TAG_SHOWBINARIES);
if (showbin != null)
getBinaryFilter().setShowBinaries(showbin.equals("true")); //$NON-NLS-1$
else
initBinaryFilterFromPreferences();
//restore working set
String workingSetName= fMemento.getString(TAG_WORKINGSET);
if (workingSetName != null) {
IWorkingSet ws= SearchUI.findWorkingSet(workingSetName);
if (ws != null) {
getWorkingSetFilter().setWorkingSet(ws);
}
}
fMemberFilterActionGroup.restoreState(fMemento);
}
void initFilterFromPreferences() {
initBinaryFilterFromPreferences();
initLibraryFilterFromPreferences();
}
void initLibraryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean show= plugin.getPreferenceStore().getBoolean(TAG_SHOWLIBRARIES);
getLibraryFilter().setShowLibraries(show);
}
void initBinaryFilterFromPreferences() {
JavaPlugin plugin= JavaPlugin.getDefault();
boolean showbin= plugin.getPreferenceStore().getBoolean(TAG_SHOWBINARIES);
getBinaryFilter().setShowBinaries(showbin);
}
/**
* Updates the title text and title tool tip.
* Called whenever the input of the viewer changes.
*/
void updateTitle() {
Object input= getViewer().getInput();
String viewName= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
if (input == null
|| (input instanceof IJavaModel)) {
setTitle(viewName);
setTitleToolTip(""); //$NON-NLS-1$
} else {
String inputText= JavaElementLabels.getTextLabel(input, StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS);
String title= PackagesMessages.getFormattedString("PackageExplorer.argTitle", new String[] { viewName, inputText }); //$NON-NLS-1$
setTitle(title);
setTitleToolTip(getToolTipText(input));
}
}
/**
* Sets the decorator for the package explorer.
*
* @param decorator a label decorator or <code>null</code> for no decorations.
* @deprecated To be removed
*/
public void setLabelDecorator(ILabelDecorator decorator) {
if (decorator == null)
fViewer.setLabelProvider(fJavaElementLabelProvider);
else
fViewer.setLabelProvider(new DecoratingLabelProvider(fJavaElementLabelProvider, decorator));
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (fViewer == null)
return;
boolean refreshViewer= false;
if (event.getProperty() == JavaBasePreferencePage.SHOW_CU_CHILDREN) {
IActionBars actionBars= getViewSite().getActionBars();
fillToolBar(actionBars.getToolBarManager());
actionBars.updateActionBars();
boolean showCUChildren= JavaBasePreferencePage.showCompilationUnitChildren();
((JavaElementContentProvider)fViewer.getContentProvider()).setProvideMembers(showCUChildren);
refreshViewer= true;
}
if (refreshViewer)
fViewer.refresh();
}
}
|
11,748 |
Bug 11748 switch to new DecoratorManager API
|
From the workbench change notes: API changes IWorkbenchPartSite.getDecoratorManager() - As the DecoratorManager has proven to be required for more than just IWorkbenchPartSites we have moved getDecoratorManager() to IWorkbench and deprecated the getDecoratorManager() in IWorkbenchPartSite. The one in IWorkbenchPartSite will be removed after the other Eclipse components have had a chance to switch to the new API.
|
resolved fixed
|
1035d37
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-20T16:58:55Z | 2002-03-19T23:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/MethodsViewer.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Table;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.action.ToolBarManager;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaElementSorter;
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.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.actions.OpenJavaElementAction;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.util.SelectionUtil;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
/**
* Method viewer shows a list of methods of a input type.
* Offers filter actions.
* No dependency to the type hierarchy view
*/
public class MethodsViewer extends ProblemTableViewer {
private static final String TAG_SHOWINHERITED= "showinherited"; //$NON-NLS-1$
private static final String TAG_VERTICAL_SCROLL= "mv_vertical_scroll"; //$NON-NLS-1$
private static final int LABEL_BASEFLAGS= StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS;
private MemberFilterActionGroup fMemberFilterActionGroup;
private JavaUILabelProvider fLabelProvider;
private OpenJavaElementAction fOpen;
private ShowInheritedMembersAction fShowInheritedMembersAction;
private ContextMenuGroup[] fStandardGroups;
public MethodsViewer(Composite parent, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
super(new Table(parent, SWT.MULTI));
fLabelProvider= new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS,
StandardJavaUILabelProvider.getAdornmentProviders(true, new HierarchyAdornmentProvider(lifeCycle))
);
setLabelProvider(new DecoratingLabelProvider(fLabelProvider, part.getSite().getDecoratorManager()));
setContentProvider(new MethodsContentProvider(lifeCycle));
fOpen= new OpenJavaElementAction(this);
addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fOpen.run();
}
});
fMemberFilterActionGroup= new MemberFilterActionGroup(this, "HierarchyMethodView");
fShowInheritedMembersAction= new ShowInheritedMembersAction(this, false);
showInheritedMethods(false);
fStandardGroups= new ContextMenuGroup[] {
new JavaSearchGroup(), new GenerateGroup()
};
setSorter(new JavaElementSorter());
JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
}
/**
* Show inherited methods
*/
public void showInheritedMethods(boolean on) {
MethodsContentProvider cprovider= (MethodsContentProvider) getContentProvider();
try {
getTable().setRedraw(false);
cprovider.showInheritedMethods(on);
fShowInheritedMembersAction.setChecked(on);
if (fLabelProvider != null) {
if (on) {
fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() | JavaElementLabels.ALL_POST_QUALIFIED);
} else {
fLabelProvider.setTextFlags(fLabelProvider.getTextFlags() & (-1 ^ JavaElementLabels.ALL_POST_QUALIFIED));
}
refresh();
}
} catch (JavaModelException e) {
ExceptionHandler.handle(e, getControl().getShell(), TypeHierarchyMessages.getString("MethodsViewer.toggle.error.title"), TypeHierarchyMessages.getString("MethodsViewer.toggle.error.message")); //$NON-NLS-2$ //$NON-NLS-1$
} finally {
getTable().setRedraw(true);
}
}
/*
* @see Viewer#inputChanged(Object, Object)
*/
protected void inputChanged(Object input, Object oldInput) {
super.inputChanged(input, oldInput);
}
/**
* Returns <code>true</code> if inherited methods are shown.
*/
public boolean isShowInheritedMethods() {
return ((MethodsContentProvider) getContentProvider()).isShowInheritedMethods();
}
/**
* Saves the state of the filter actions
*/
public void saveState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
memento.putString(TAG_SHOWINHERITED, String.valueOf(isShowInheritedMethods()));
ScrollBar bar= getTable().getVerticalBar();
int position= bar != null ? bar.getSelection() : 0;
memento.putString(TAG_VERTICAL_SCROLL, String.valueOf(position));
}
/**
* Restores the state of the filter actions
*/
public void restoreState(IMemento memento) {
fMemberFilterActionGroup.restoreState(memento);
boolean set= Boolean.valueOf(memento.getString(TAG_SHOWINHERITED)).booleanValue();
showInheritedMethods(set);
ScrollBar bar= getTable().getVerticalBar();
if (bar != null) {
Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL);
if (vScroll != null) {
bar.setSelection(vScroll.intValue());
}
}
}
/**
* Attaches a contextmenu listener to the table
*/
public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(menuListener);
Menu menu= menuMgr.createContextMenu(getTable());
getTable().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
/**
* Fills up the context menu with items for the method viewer
* Should be called by the creator of the context menu
*/
public void contributeToContextMenu(IMenuManager menu) {
if (fOpen.canActionBeAdded()) {
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
}
ContextMenuGroup.add(menu, fStandardGroups, this);
}
/**
* Fills up the tool bar with items for the method viewer
* Should be called by the creator of the tool bar
*/
public void contributeToToolBar(ToolBarManager tbm) {
tbm.add(fShowInheritedMembersAction);
tbm.add(new Separator());
fMemberFilterActionGroup.contributeToToolBar(tbm);
}
/*
* @see StructuredViewer#handleInvalidSelection(ISelection, ISelection)
*/
protected void handleInvalidSelection(ISelection invalidSelection, ISelection newSelection) {
// on change of input, try to keep selected methods stable by selecting a method with the same
// signature: See #5466
List oldSelections= SelectionUtil.toList(invalidSelection);
List newSelections= SelectionUtil.toList(newSelection);
if (!oldSelections.isEmpty()) {
ArrayList newSelectionElements= new ArrayList(newSelections);
try {
Object[] currElements= getFilteredChildren(getInput());
for (int i= 0; i < oldSelections.size(); i++) {
Object curr= oldSelections.get(i);
if (curr instanceof IMethod && !newSelections.contains(curr)) {
IMethod method= (IMethod) curr;
if (method.exists()) {
IMethod similar= findSimilarMethod(method, currElements);
if (similar != null) {
newSelectionElements.add(similar);
}
}
}
}
newSelection= new StructuredSelection(newSelectionElements);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
setSelection(newSelection);
updateSelection(newSelection);
}
private IMethod findSimilarMethod(IMethod meth, Object[] elements) throws JavaModelException {
String name= meth.getElementName();
String[] paramTypes= meth.getParameterTypes();
boolean isConstructor= meth.isConstructor();
for (int i= 0; i < elements.length; i++) {
Object curr= elements[i];
if (curr instanceof IMethod && JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, (IMethod) curr)) {
return (IMethod) curr;
}
}
return null;
}
}
|
11,748 |
Bug 11748 switch to new DecoratorManager API
|
From the workbench change notes: API changes IWorkbenchPartSite.getDecoratorManager() - As the DecoratorManager has proven to be required for more than just IWorkbenchPartSites we have moved getDecoratorManager() to IWorkbench and deprecated the getDecoratorManager() in IWorkbenchPartSite. The one in IWorkbenchPartSite will be removed after the other Eclipse components have had a chance to switch to the new API.
|
resolved fixed
|
1035d37
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-20T16:58:55Z | 2002-03-19T23:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewer.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.typehierarchy;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.actions.OpenJavaElementAction;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.wizards.NewGroup;
public abstract class TypeHierarchyViewer extends ProblemTreeViewer {
private OpenJavaElementAction fOpen;
private ContextMenuGroup[] fStandardGroups;
public TypeHierarchyViewer(Composite parent, IContentProvider contentProvider, TypeHierarchyLifeCycle lifeCycle, IWorkbenchPart part) {
super(new Tree(parent, SWT.SINGLE));
ILabelProvider baseLProvider= new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS,
StandardJavaUILabelProvider.getAdornmentProviders(true, new HierarchyAdornmentProvider(lifeCycle))
);
setLabelProvider(new DecoratingLabelProvider(baseLProvider, part.getSite().getDecoratorManager()));
setContentProvider(contentProvider);
setSorter(new ViewerSorter() {
public boolean isSorterProperty(Object element, Object property) {
return true;
}
public int category(Object element) {
if (element instanceof IType) {
try {
return (((IType)element).isInterface()) ? 2 : 1;
} catch (JavaModelException e) {
}
} else if (element instanceof IMember) {
return 0;
}
return 3;
}
});
fOpen= new OpenJavaElementAction(this);
addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
fOpen.run();
}
});
fStandardGroups= new ContextMenuGroup[] {
new JavaSearchGroup(), new NewGroup(), new GenerateGroup()
};
JavaUIHelp.setHelp(this, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW);
}
/**
* Attaches a contextmenu listener to the tree
*/
public void initContextMenu(IMenuListener menuListener, String popupId, IWorkbenchPartSite viewSite) {
MenuManager menuMgr= new MenuManager();
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(menuListener);
Menu menu= menuMgr.createContextMenu(getTree());
getTree().setMenu(menu);
viewSite.registerContextMenu(popupId, menuMgr, this);
}
/**
* Fills up the context menu with items for the hierarchy viewer
* Should be called by the creator of the context menu
*/
public void contributeToContextMenu(IMenuManager menu) {
if (fOpen.canActionBeAdded()) {
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpen);
}
ContextMenuGroup.add(menu, fStandardGroups, this);
}
/**
* Set the member filter
*/
public void setMemberFilter(IMember[] memberFilter) {
TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
if (contentProvider != null) {
contentProvider.setMemberFilter(memberFilter);
}
}
/**
* Returns if method filtering is enabled.
*/
public boolean isMethodFiltering() {
TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
if (contentProvider != null) {
return contentProvider.getMemberFilter() != null;
}
return false;
}
/**
* Returns true if the hierarchy contains elements. Returns one of them
* With member filtering it is possible that no elements are visible
*/
public Object containsElements() {
TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
if (contentProvider != null) {
Object[] elements= contentProvider.getElements(null);
if (elements.length > 0) {
return elements[0];
}
}
return null;
}
/**
* Returns true if the hierarchy contains elements. Returns one of them
* With member filtering it is possible that no elements are visible
*/
public IType getTreeRootType() {
TypeHierarchyContentProvider contentProvider= getHierarchyContentProvider();
if (contentProvider != null) {
Object[] elements= contentProvider.getElements(null);
if (elements.length > 0 && elements[0] instanceof IType) {
return (IType) elements[0];
}
}
return null;
}
/**
* Returns true if the hierarchy contains element the element.
*/
public boolean isElementShown(Object element) {
return findItem(element) != null;
}
/**
* Updates the content of this viewer: refresh and expanding the tree in the way wanted.
*/
public abstract void updateContent();
/**
* Returns the title for the current view
*/
public abstract String getTitle();
/*
* @see StructuredViewer#setContentProvider
* Content provider must be of type TypeHierarchyContentProvider
*/
public void setContentProvider(IContentProvider cp) {
Assert.isTrue(cp instanceof TypeHierarchyContentProvider);
super.setContentProvider(cp);
}
protected TypeHierarchyContentProvider getHierarchyContentProvider() {
return (TypeHierarchyContentProvider)getContentProvider();
}
}
|
11,317 |
Bug 11317 Won't export some files to .jar.
|
Create a new java project called "Foo". In the file system, create a folder named "Foo scripts", and in this folder create a file named "foo.txt". Drag this folder into the eclipse packages view and add it to the "Foo" project. Now try to export the project "Foo" to a .jar file. Only the manifest file shows up, even if the file "foo.txt" is checked!
|
resolved fixed
|
5f546fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-20T18:10:50Z | 2002-03-13T22:53:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarFileExportOperation.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.jarpackager;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
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 org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
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.Shell;
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.xml.sax.SAXException;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaStatusConstants;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
/**
* Operation for exporting a resource and its children to a new JAR file.
*/
public class JarFileExportOperation implements IRunnableWithProgress {
private JarWriter fJarWriter;
private JarPackage fJarPackage;
private IFile[] fDescriptionFiles;
private Shell fParentShell;
private Map fJavaNameToClassFilesMap;
private IContainer fClassFilesMapContainer;
private MultiStatus fProblems;
/**
* 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(JarPackage jarPackage, Shell parent) {
this(parent);
fJarPackage= jarPackage;
}
/**
* Creates an instance of this class.
*
* @param descriptions an array with JAR package descriptions
* @param parent the parent for the dialog,
* or <code>null</code> if no dialog should be presented
*/
public JarFileExportOperation(IFile[] descriptions, Shell parent) {
this(parent);
fDescriptionFiles= descriptions;
}
/**
* 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>
*/
private JarFileExportOperation(Shell parent) {
fParentShell= parent;
fProblems= new MultiStatus(JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, JarPackagerMessages.getString("JarFileExportOperation.exportFinishedWithWarnings"), null); //$NON-NLS-1$
}
protected void addWarning(String message, Throwable error) {
if (fJarPackage == null || fJarPackage.logWarnings())
fProblems.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), JavaStatusConstants.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) {
if (fJarPackage == null || fJarPackage.logErrors())
fProblems.add(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, message, error));
}
/**
* Answers the number of file resources specified by the JAR package.
*
* @return int
*/
protected int countSelectedElements() {
int count= 0;
Iterator iter= fJarPackage.getSelectedElements().iterator();
while (iter.hasNext()) {
Object element= iter.next();
IResource resource= null;
if (element instanceof IJavaElement) {
IJavaElement je= (IJavaElement)element;
try {
resource= je.getUnderlyingResource();
} catch (JavaModelException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.underlyingResourceNotFound", je.getElementName()), ex); //$NON-NLS-1$
return count;
}
}
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;
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= jProject.findPackageFragmentRoot(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();
if (fJarPackage.useSourceFolderHierarchy()&& !pkgRoot.getElementName().equals(pkgRoot.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 if (element instanceof IPackageFragment)
exportPackageFragment(progressMonitor, (IPackageFragment)element);
else
exportContainer(progressMonitor, resource);
}
private void exportPackageFragment(IProgressMonitor progressMonitor, IPackageFragment pkgFragment) throws java.lang.InterruptedException {
Object[] children;
try {
children= pkgFragment.getChildren();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
children= pkgFragment.getNonJavaResources();
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", pkgFragment.toString()), e); //$NON-NLS-1$
}
}
private void exportContainer(IProgressMonitor progressMonitor, IResource resource) throws java.lang.InterruptedException {
IResource[] children= null;
try {
children= ((IContainer) resource).members();
} catch (CoreException e) {
// this should never happen because an #isAccessible check is done before #members is invoked
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorDuringExport", resource.getFullPath()), e); //$NON-NLS-1$
}
for (int i= 0; i < children.length; i++)
exportElement(children[i], progressMonitor);
}
private void exportResource(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, boolean isInJavaProject, IResource resource, IPath destinationPath, boolean isInOutputFolder) {
boolean isNonJavaResource= !isInJavaProject || (pkgRoot == null && !isInOutputFolder);
boolean isInClassFolder= false;
try {
isInClassFolder= pkgRoot != null && !pkgRoot.isArchive() && pkgRoot.getKind() == pkgRoot.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 (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
private void exportClassFiles(IProgressMonitor progressMonitor, IPackageFragmentRoot pkgRoot, IResource resource, IJavaProject jProject, IPath destinationPath) {
if (fJarPackage.areClassFilesExported() && isJavaFile(resource) && pkgRoot != null) {
try {
// find corresponding file(s) on classpath and export
Iterator iter= filesOnClasspath((IFile)resource, destinationPath, jProject, 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 (IOException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message , ex);
} catch (CoreException ex) {
String message= ex.getMessage();
if (message == null)
message= JarPackagerMessages.getFormattedString("JarFileExportOperation.coreErrorDuringExport", resource.getFullPath()); //$NON-NLS-1$
addWarning(message, ex);
}
}
}
/**
* Exports the resources as specified by the JAR package.
*/
protected void exportSelectedElements(IProgressMonitor progressMonitor) throws InterruptedException {
Iterator iter= fJarPackage.getSelectedElements().iterator();
while (iter.hasNext())
exportElement(iter.next(), 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
*/
protected Iterator filesOnClasspath(IFile file, IPath pathInJar, IJavaProject javaProject, IProgressMonitor progressMonitor) throws CoreException {
IPath 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(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
}
if (isJavaFile(file)) {
// Java CU - search files with .class ending
boolean hasErrors= fJarPackage.hasCompileErrors(file);
boolean hasWarnings= fJarPackage.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 (fClassFilesMapContainer == null || !fClassFilesMapContainer.equals(classContainer)) {
fJavaNameToClassFilesMap= buildJavaToClassMap(classContainer);
fClassFilesMapContainer= classContainer;
}
ArrayList classFiles= (ArrayList)fJavaNameToClassFilesMap.get(file.getName());
if (classFiles == null || classFiles.isEmpty()) {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileOnClasspathNotAccessible", file.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return classFiles.iterator();
}
else {
// resource - search file with same name
List binaryFiles= new ArrayList(1);
IFile cpFile= outputContainer.getFile(pathInJar);
if (cpFile.isAccessible()) {
if (!cpFile.isLocal(IResource.DEPTH_ZERO))
cpFile.setLocal(true , IResource.DEPTH_ZERO, progressMonitor);
binaryFiles.add(cpFile);
}
else {
String msg= JarPackagerMessages.getFormattedString("JarFileExportOperation.resourceOnCasspathNotAccessible", cpFile.getFullPath()); //$NON-NLS-1$
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), JavaStatusConstants.INTERNAL_ERROR, msg, null));
}
return binaryFiles.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 (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;
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];
try {
cfReader= org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader.read(classFile.getLocation().toFile());
} catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.invalidClassFileFormat", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
} catch (IOException ex) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.ioErrorDuringClassFileLookup", classFile.getLocation().toFile()), ex); //$NON-NLS-1$
continue;
}
if (cfReader != null) {
if (cfReader.sourceFileName() == null) {
addWarning(JarPackagerMessages.getFormattedString("JarFileExportOperation.classFileWithoutSourceFileAttribute", classFile.getLocation().toFile()), null); //$NON-NLS-1$
continue;
}
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
* @see #createFile
*/
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.
* If there were any errors, the result is a status object containing
* individual status objects for each error.
* If there were no errors, the result is a status object with error code <code>OK</code>.
*
* @return the status of this operation
*/
public IStatus getStatus() {
if (fProblems.getSeverity() == IStatus.ERROR) {
String message= null;
if (fDescriptionFiles != null && fDescriptionFiles.length > 1)
message= JarPackagerMessages.getString("JarFileExportOperation.creationOfSomeJARsFailed"); //$NON-NLS-1$
else
message= JarPackagerMessages.getString("JarFileExportOperation.jarCreationFailed"); //$NON-NLS-1$
// Create new status because we want another message - no API to set message
return new MultiStatus(JavaPlugin.getPluginId(), 0, fProblems.getChildren(), message, null);
}
return fProblems;
}
/**
* 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.exportErrors())
|| (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()
*/
public void run(IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException {
if (fJarPackage != null)
singleRun(progressMonitor);
else {
int jarCount= fDescriptionFiles.length;
progressMonitor.beginTask("", jarCount); //$NON-NLS-1$
try {
for (int i= 0; i < jarCount; i++) {
SubProgressMonitor subProgressMonitor= new SubProgressMonitor(progressMonitor, 1);
fJarPackage= readJarPackage(fDescriptionFiles[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()) {
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= new JarWriter(fJarPackage, fParentShell);
exportSelectedElements(progressMonitor);
if (getStatus().getSeverity() != IStatus.ERROR) {
progressMonitor.subTask(JarPackagerMessages.getString("JarFileExportOperation.savingFiles")); //$NON-NLS-1$
saveFiles();
}
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFle", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} catch (CoreException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCreateJarFileDueToInvalidManifest", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
} finally {
try {
if (fJarWriter != null)
fJarWriter.close();
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.unableToCloseJarFile", ex.getMessage()); //$NON-NLS-1$
addError(message, ex);
throw new InvocationTargetException(ex, message);
}
progressMonitor.done();
}
}
protected boolean preconditionsOK() {
if (!fJarPackage.areClassFilesExported() && !fJarPackage.areJavaFilesExported()) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noExportTypeChosen"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getSelectedElements() == null || fJarPackage.getSelectedElements().size() == 0) {
addError(JarPackagerMessages.getString("JarFileExportOperation.noResourcesSelected"), null); //$NON-NLS-1$
return false;
}
if (fJarPackage.getJarLocation() == null) {
addError(JarPackagerMessages.getString("JarFileExportOperation.invalidJarLocation"), null); //$NON-NLS-1$
return false;
}
if (!fJarPackage.doesManifestExist()) {
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;
}
IEditorPart[] dirtyEditors= JavaPlugin.getDirtyEditors();
if (dirtyEditors.length > 0) {
List unsavedFiles= new ArrayList(dirtyEditors.length);
List selection= fJarPackage.getSelectedResources();
for (int i= 0; i < dirtyEditors.length; i++) {
if (dirtyEditors[i].getEditorInput() instanceof IFileEditorInput) {
IFile dirtyFile= ((IFileEditorInput)dirtyEditors[i].getEditorInput()).getFile();
if (selection.contains(dirtyFile)) {
unsavedFiles.add(dirtyFile);
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.fileUnsaved", dirtyFile.getFullPath()), null); //$NON-NLS-1$
}
}
}
if (!unsavedFiles.isEmpty())
return false;
}
return true;
}
protected void saveFiles() {
// Save the manifest
if (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$
}
}
}
protected void saveDescription() throws CoreException, IOException {
// Adjust JAR package attributes
if (fJarPackage.isManifestReused())
fJarPackage.setGenerateManifest(false);
ByteArrayOutputStream objectStreamOutput= new ByteArrayOutputStream();
JarPackageWriter objectStream= new JarPackageWriter(objectStreamOutput);
ByteArrayInputStream fileInput= null;
try {
objectStream.writeXML(fJarPackage);
fileInput= new ByteArrayInputStream(objectStreamOutput.toByteArray());
if (fJarPackage.getDescriptionFile().isAccessible()) {
if (fJarPackage.canOverwriteDescription(fParentShell))
fJarPackage.getDescriptionFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getDescriptionFile().create(fileInput, true, null);
}
} finally {
if (fileInput != null)
fileInput.close();
if (objectStream != null)
objectStream.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());
if (fJarPackage.getManifestFile().isAccessible()) {
if (fJarPackage.canOverwriteManifest(fParentShell))
fJarPackage.getManifestFile().setContents(fileInput, true, true, null);
}
else {
fJarPackage.getManifestFile().create(fileInput, true, null);
}
} finally {
if (manifestOutput != null)
manifestOutput.close();
if (fileInput != null)
fileInput.close();
}
}
/**
* Reads the JAR package spec from file.
*/
protected JarPackage readJarPackage(IFile description) {
Assert.isLegal(description.isAccessible());
Assert.isNotNull(description.getFileExtension());
Assert.isLegal(description.getFileExtension().equals(JarPackage.DESCRIPTION_EXTENSION));
JarPackage jarPackage= null;
JarPackageReader reader= null;
try {
reader= new JarPackageReader(description.getContents());
// Do not save - only generate JAR
jarPackage= reader.readXML();
jarPackage.setSaveManifest(false);
jarPackage.setSaveDescription(false);
} catch (CoreException ex) {
addError(JarPackagerMessages.getString("JarFileExportOperation.errorReadingJarPackageFromDescription"), ex); //$NON-NLS-1$
} catch (IOException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.errorReadingFile", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} catch (SAXException ex) {
String message= JarPackagerMessages.getFormattedString("JarFileExportOperation.badXmlFormat", description.getFullPath(), ex.getMessage()); //$NON-NLS-1$
addError(message, null);
} finally {
if ((jarPackage == null || jarPackage.logWarnings()) && reader != null)
// AddWarnings
fProblems.addAll(reader.getWarnings());
try {
if (reader != null)
reader.close();
}
catch (IOException ex) {
addError(JarPackagerMessages.getFormattedString("JarFileExportOperation.errorClosingJarPackageDescriptionReader", description.getFullPath()), ex); //$NON-NLS-1$
}
}
return jarPackage;
}
private boolean isAutoBuilding() {
return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
}
private void buildProjects(IProgressMonitor progressMonitor) {
Set builtProjects= new HashSet(10);
Iterator iter= fJarPackage.getSelectedElementsClosure();
while (iter.hasNext()) {
IProject project= null;
Object element= iter.next();
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);
}
}
}
}
}
|
11,228 |
Bug 11228 package name shortening pref page - tooltip works as help
|
tooltip in the pref page where you can specify pattern to shorten package names contains some useful information that should be exposed on the page itself (you can write patterns with numbers!) current behavior is sub-optimal (users must be lucky to find that feature)
|
verified fixed
|
cc40882
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T10:57:44Z | 2002-03-13T09:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/AppearancePreferencePage.java
|
package org.eclipse.jdt.internal.ui.preferences;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
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.SelectionButtonDialogField;
public class AppearancePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// need to be
public static final String PREF_METHOD_RETURNTYPE= JavaUI.ID_PLUGIN + ".methodreturntype"; //$NON-NLS-1$
public static final String PREF_OVERRIDE_INDICATOR= JavaUI.ID_PLUGIN + ".overrideindicator"; //$NON-NLS-1$
public static boolean showMethodReturnType() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_METHOD_RETURNTYPE);
}
public static boolean showOverrideIndicators() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_OVERRIDE_INDICATOR);
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_METHOD_RETURNTYPE, false);
prefs.setDefault(PREF_OVERRIDE_INDICATOR, true);
}
private SelectionButtonDialogField fShowMethodReturnType;
private SelectionButtonDialogField fShowOverrideIndicator;
public AppearancePreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("AppearancePreferencePage.description")); //$NON-NLS-1$
IDialogFieldListener listener= new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doDialogFieldChanged(field);
}
};
fShowMethodReturnType= new SelectionButtonDialogField(SWT.CHECK);
fShowMethodReturnType.setDialogFieldListener(listener);
fShowMethodReturnType.setLabelText(JavaUIMessages.getString("AppearancePreferencePage.methodreturntype.label")); //$NON-NLS-1$
fShowOverrideIndicator= new SelectionButtonDialogField(SWT.CHECK);
fShowOverrideIndicator.setDialogFieldListener(listener);
fShowOverrideIndicator.setLabelText(JavaUIMessages.getString("AppearancePreferencePage.overrideindicator.label")); //$NON-NLS-1$
}
private void initFields() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fShowMethodReturnType.setSelection(prefs.getBoolean(PREF_METHOD_RETURNTYPE));
fShowOverrideIndicator.setSelection(prefs.getBoolean(PREF_OVERRIDE_INDICATOR));
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.APPEARANCE_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
int nColumns= 1;
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= nColumns;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
fShowMethodReturnType.doFillIntoGrid(composite, nColumns);
fShowOverrideIndicator.doFillIntoGrid(composite, nColumns);
initFields();
return composite;
}
private void doDialogFieldChanged(DialogField field) {
// no validation needed
updateStatus(new StatusInfo());
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_METHOD_RETURNTYPE, fShowMethodReturnType.isSelected());
prefs.setValue(PREF_OVERRIDE_INDICATOR, fShowOverrideIndicator.isSelected());
return super.performOk();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fShowMethodReturnType.setSelection(prefs.getDefaultBoolean(PREF_METHOD_RETURNTYPE));
fShowOverrideIndicator.setSelection(prefs.getDefaultBoolean(PREF_OVERRIDE_INDICATOR));
super.performDefaults();
}
}
|
11,767 |
Bug 11767 java browsing: ignores 'package name shortening' preference
|
java browsing has a packages view but ingores my preference to shorten package names
|
verified fixed
|
78b4961
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T10:59:36Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/PackagesView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jdt.core.IClassFile;
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.internal.ui.jarpackager.LibraryFilter;
import org.eclipse.jdt.internal.ui.packageview.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.packageview.EmptyPackageFilter;
import org.eclipse.jdt.internal.ui.packageview.JavaElementPatternFilter;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
public class PackagesView extends JavaBrowsingPart {
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
getViewer().addFilter(new EmptyInnerPackageFilter());
getViewer().addFilter(new NonJavaElementFilter());
getViewer().addFilter(new LibraryFilter());
JavaElementPatternFilter patternFilter= new JavaElementPatternFilter();
patternFilter.setPatterns(new String[] {"CVS", "*.CVS"});
getViewer().addFilter(patternFilter);
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.PACKAGES_VIEW;
}
/**
* 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) {
return element instanceof IJavaProject
|| (element instanceof IPackageFragmentRoot && ((IJavaElement)element).getElementName() != IPackageFragmentRoot.DEFAULT_PACKAGEROOT_PATH);
}
/*
* Gets suitable input.
*/
/**
* 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 IPackageFragment) {
IJavaElement parent= ((IPackageFragment)element).getParent();
if (parent != null)
return super.isValidElement(parent) || super.isValidElement(parent.getJavaProject());
}
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.PACKAGE_FRAGMENT:
return je;
case IJavaElement.COMPILATION_UNIT:
return ((ICompilationUnit)je).getParent();
case IJavaElement.CLASS_FILE:
return ((IClassFile)je).getParent();
case IJavaElement.TYPE:
return ((IType)je).getPackageFragment();
default:
return findElementToSelect(je.getParent());
}
}
}
|
11,238 |
Bug 11238 1.4 settings should not include 'assert as identifier'
|
Build 20020312 In 1.4 source mode, 'assert' is a keyword, and therefore it cannot be reported to be used as an identifier.
|
resolved fixed
|
20f8cbd
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T11:35:26Z | 2002-03-13T11:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
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.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.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
/*
* The page for setting the compiler options.
*/
public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_LOCAL_VARIABLE_ATTR= "org.eclipse.jdt.core.compiler.debug.localVariable";
private static final String PREF_LINE_NUMBER_ATTR= "org.eclipse.jdt.core.compiler.debug.lineNumber";
private static final String PREF_SOURCE_FILE_ATTR= "org.eclipse.jdt.core.compiler.debug.sourceFile";
private static final String PREF_CODEGEN_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.codegen.unusedLocal";
private static final String PREF_CODEGEN_TARGET_PLATFORM= "org.eclipse.jdt.core.compiler.codegen.targetPlatform";
private static final String PREF_PB_UNREACHABLE_CODE= "org.eclipse.jdt.core.compiler.problem.unreachableCode";
private static final String PREF_PB_INVALID_IMPORT= "org.eclipse.jdt.core.compiler.problem.invalidImport";
private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= "org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod";
private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= "org.eclipse.jdt.core.compiler.problem.methodWithConstructorName";
private static final String PREF_PB_DEPRECATION= "org.eclipse.jdt.core.compiler.problem.deprecation";
private static final String PREF_PB_HIDDEN_CATCH_BLOCK= "org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock";
private static final String PREF_PB_UNUSED_LOCAL= "org.eclipse.jdt.core.compiler.problem.unusedLocal";
private static final String PREF_PB_UNUSED_PARAMETER= "org.eclipse.jdt.core.compiler.problem.unusedParameter";
private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= "org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation";
private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= "org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral";
private static final String PREF_PB_ASSERT_AS_IDENTIFIER= "org.eclipse.jdt.core.compiler.problem.assertIdentifier";
private static final String PREF_SOURCE_COMPATIBILITY= "org.eclipse.jdt.core.compiler.source";
private static final String PREF_COMPLIANCE= "org.eclipse.jdt.core.compiler.compliance";
private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance";
// values
private static final String GENERATE= "generate";
private static final String DO_NOT_GENERATE= "do not generate";
private static final String PRESERVE= "preserve";
private static final String OPTIMIZE_OUT= "optimize out";
private static final String VERSION_1_1= "1.1";
private static final String VERSION_1_2= "1.2";
private static final String VERSION_1_3= "1.3";
private static final String VERSION_1_4= "1.4";
private static final String ERROR= "error";
private static final String WARNING= "warning";
private static final String IGNORE= "ignore";
private static final String DEFAULT= "default";
private static final String USER= "user";
private static String[] getAllKeys() {
return new String[] {
PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL,
PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, 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_SOURCE_COMPATIBILITY, PREF_COMPLIANCE
};
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("CompilerPreferencePage: value is null: " + key);
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
private 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();
}
}
private Hashtable fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fComboBoxes;
private SelectionListener fSelectionListener;
private ArrayList fComplianceControls;
public CompilerPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
fCheckBoxes= new ArrayList();
fComboBoxes= new ArrayList();
fComplianceControls= new ArrayList();
fSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
controlChanged(e.widget);
}
};
}
/**
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/**
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
// added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE);
}
/**
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
TabFolder folder= new TabFolder(parent, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
Composite warningsComposite= createWarningsTabContent(folder);
Composite codeGenComposite= createCodeGenTabContent(folder);
Composite complianceComposite= createComplianceTabContent(folder);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_WARNING));
item.setControl(warningsComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.generation.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(codeGenComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CompilerPreferencePage.compliance.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_LIBRARY));
item.setControl(complianceComposite);
validateSettings(null, null);
return folder;
}
private Composite createWarningsTabContent(Composite folder) {
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.error"),
JavaUIMessages.getString("CompilerPreferencePage.warning"),
JavaUIMessages.getString("CompilerPreferencePage.ignore")
};
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite warningsComposite= new Composite(folder, SWT.NULL);
warningsComposite.setLayout(layout);
Label description= new Label(warningsComposite, SWT.WRAP);
description.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.description")); //$NON-NLS-1$
GridData gd= new GridData();
gd.horizontalSpan= 2;
gd.widthHint= convertWidthInCharsToPixels(60);
description.setLayoutData(gd);
String label= JavaUIMessages.getString("CompilerPreferencePage.pb_unreachable_code.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_invalid_import.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_method_naming.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_hidden_catchblock.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_local.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_parameter.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_synth_access_emul.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.pb_non_externalized_strings.label"); //$NON-NLS-1$
addComboBox(warningsComposite, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0);
return warningsComposite;
}
private Composite createCodeGenTabContent(Composite folder) {
String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE };
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite codeGenComposite= new Composite(folder, SWT.NULL);
codeGenComposite.setLayout(layout);
String label= JavaUIMessages.getString("CompilerPreferencePage.variable_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.line_number_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.source_file_attr.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.codegen_unused_local.label"); //$NON-NLS-1$
addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0);
return codeGenComposite;
}
private Composite createComplianceTabContent(Composite folder) {
GridLayout layout= new GridLayout();
layout.numColumns= 2;
Composite complianceComposite= new Composite(folder, SWT.NULL);
complianceComposite.setLayout(layout);
String[] values34= new String[] { VERSION_1_3, VERSION_1_4 };
String[] values34Labels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.version13"),
JavaUIMessages.getString("CompilerPreferencePage.version14")
};
String label= JavaUIMessages.getString("CompilerPreferencePage.compiler_compliance.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_COMPLIANCE, values34, values34Labels, 0);
label= JavaUIMessages.getString("CompilerPreferencePage.default_settings.label"); //$NON-NLS-1$
addCheckBox(complianceComposite, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0);
int indent= convertWidthInCharsToPixels(2);
Control[] otherChildren= complianceComposite.getChildren();
String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 };
String[] values14Labels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.version11"),
JavaUIMessages.getString("CompilerPreferencePage.version12"),
JavaUIMessages.getString("CompilerPreferencePage.version13"),
JavaUIMessages.getString("CompilerPreferencePage.version14")
};
label= JavaUIMessages.getString("CompilerPreferencePage.codegen_targetplatform.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent);
label= JavaUIMessages.getString("CompilerPreferencePage.source_compatibility.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent);
String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE };
String[] errorWarningIgnoreLabels= new String[] {
JavaUIMessages.getString("CompilerPreferencePage.error"),
JavaUIMessages.getString("CompilerPreferencePage.warning"),
JavaUIMessages.getString("CompilerPreferencePage.ignore")
};
label= JavaUIMessages.getString("CompilerPreferencePage.pb_assert_as_identifier.label"); //$NON-NLS-1$
addComboBox(complianceComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent);
Control[] allChildren= complianceComposite.getChildren();
fComplianceControls.addAll(Arrays.asList(allChildren));
fComplianceControls.removeAll(Arrays.asList(otherChildren));
return complianceComposite;
}
private 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= 2;
gd.horizontalIndent= indent;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
checkBox.addSelectionListener(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
fCheckBoxes.add(checkBox);
}
private 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.FILL_HORIZONTAL);
gd.horizontalIndent= indent;
Label labelControl= new Label(parent, SWT.NONE);
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(fSelectionListener);
String currValue= (String)fWorkingValues.get(key);
comboBox.select(data.getSelection(currValue));
fComboBoxes.add(comboBox);
}
private 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);
}
private boolean checkValue(String key, String value) {
return value.equals(fWorkingValues.get(key));
}
/*
* Update fields and validate.
* @param changedKey Key that changed, or null, if all changed.
*/
private void validateSettings(String changedKey, String newValue) {
if (changedKey != null) {
if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) {
updateComplianceEnableState();
if (DEFAULT.equals(newValue)) {
updateComplianceDefaultSettings();
}
} else if (PREF_COMPLIANCE.equals(changedKey)) {
if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) {
updateComplianceDefaultSettings();
}
} else if (!PREF_SOURCE_COMPATIBILITY.equals(changedKey) &&
!PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey)) {
return;
}
} else {
updateComplianceEnableState();
}
StatusInfo status= new StatusInfo();
if (checkValue(PREF_COMPLIANCE, VERSION_1_4) && checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3)) {
status.setError(JavaUIMessages.getString("CompilerPreferencePage.validation14.error"));
} else if (checkValue(PREF_COMPLIANCE, VERSION_1_3) && checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) {
status.setError(JavaUIMessages.getString("CompilerPreferencePage.validation13.error"));
}
updateStatus(status);
}
/*
* 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 String getCurrentCompliance() {
Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE);
if ((VERSION_1_3.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1))
|| (VERSION_1_4.equals(complianceLevel)
&& checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)
&& checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)
&& checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4))) {
return DEFAULT;
}
return USER;
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
String oldVal= (String) actualOptions.get(key);
hasChanges= hasChanges | !val.equals(oldVal);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
if (hasChanges) {
String title= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.title");
String message= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.message");
if (MessageDialog.openQuestion(getShell(), title, message)) {
doFullBuild();
}
}
return super.performOk();
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("CompilerPreferencePage.builderror.title");
String message= JavaUIMessages.getString("CompilerPreferencePage.builderror.message");
ExceptionHandler.handle(e, getShell(), title, message);
}
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance());
updateControls();
validateSettings(null, null);
super.performDefaults();
}
private void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= 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));
}
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
}
|
11,903 |
Bug 11903 'add javadoc comment' adds non-java doc comments
|
1. (default code-generation preference settings) 2. select the method and 'add javadoc comment' package p; class A{ public String toString() { return super.toString(); } } it adds /* * @see Object#toString() */ which is not a javadoc comment
|
resolved fixed
|
bbe211a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T11:45:02Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui/core
| |
11,903 |
Bug 11903 'add javadoc comment' adds non-java doc comments
|
1. (default code-generation preference settings) 2. select the method and 'add javadoc comment' package p; class A{ public String toString() { return super.toString(); } } it adds /* * @see Object#toString() */ which is not a javadoc comment
|
resolved fixed
|
bbe211a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T11:45:02Z | 2002-03-20T16:00:00Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
11,903 |
Bug 11903 'add javadoc comment' adds non-java doc comments
|
1. (default code-generation preference settings) 2. select the method and 'add javadoc comment' package p; class A{ public String toString() { return super.toString(); } } it adds /* * @see Object#toString() */ which is not a javadoc comment
|
resolved fixed
|
bbe211a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T11:45:02Z | 2002-03-20T16:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeGenerationPreferencePage.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.util.StringTokenizer;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
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.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
public class CodeGenerationPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private static final String PREF_USE_GETTERSETTER_PREFIX= JavaUI.ID_PLUGIN + ".gettersetter.prefix.enable"; //$NON-NLS-1$
private static final String PREF_GETTERSETTER_PREFIX= JavaUI.ID_PLUGIN + ".gettersetter.prefix.list"; //$NON-NLS-1$
private static final String PREF_USE_GETTERSETTER_SUFFIX= JavaUI.ID_PLUGIN + ".gettersetter.suffix.enable"; //$NON-NLS-1$
private static final String PREF_GETTERSETTER_SUFFIX= JavaUI.ID_PLUGIN + ".gettersetter.suffix.list"; //$NON-NLS-1$
private static final String PREF_JAVADOC_STUBS= JavaUI.ID_PLUGIN + ".javadoc"; //$NON-NLS-1$
private static final String PREF_SEE_COMMENTS= JavaUI.ID_PLUGIN + ".seecomments"; //$NON-NLS-1$
private static final String PREF_FILE_COMMENTS= JavaUI.ID_PLUGIN + ".filecomments"; //$NON-NLS-1$
public static String[] getGetterStetterPrefixes() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PREF_USE_GETTERSETTER_PREFIX)) {
String str= prefs.getString(PREF_GETTERSETTER_PREFIX);
if (str != null) {
return unpackOrderList(str);
}
}
return new String[0];
}
public static String[] getGetterStetterSuffixes() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
if (prefs.getBoolean(PREF_USE_GETTERSETTER_SUFFIX)) {
String str= prefs.getString(PREF_GETTERSETTER_SUFFIX);
if (str != null) {
return unpackOrderList(str);
}
}
return new String[0];
}
public static boolean doCreateComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_JAVADOC_STUBS);
}
public static boolean doNonJavaDocSeeComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_SEE_COMMENTS);
}
public static boolean doFileComments() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_FILE_COMMENTS);
}
private static String[] unpackOrderList(String str) {
StringTokenizer tok= new StringTokenizer(str, ","); //$NON-NLS-1$
int nTokens= tok.countTokens();
String[] res= new String[nTokens];
for (int i= 0; i < nTokens; i++) {
res[i]= tok.nextToken().trim();
}
return res;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_USE_GETTERSETTER_PREFIX, false);
prefs.setDefault(PREF_USE_GETTERSETTER_SUFFIX, false);
prefs.setDefault(PREF_GETTERSETTER_PREFIX, "f, fg, _, m_"); //$NON-NLS-1$
prefs.setDefault(PREF_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$
prefs.setDefault(PREF_JAVADOC_STUBS, true);
prefs.setDefault(PREF_SEE_COMMENTS, true);
prefs.setDefault(PREF_FILE_COMMENTS, true);
}
private SelectionButtonDialogField fUseGetterSetterPrefix;
private SelectionButtonDialogField fUseGetterSetterSuffix;
private StringDialogField fGetterSetterPrefix;
private StringDialogField fGetterSetterSuffix;
private SelectionButtonDialogField fCreateJavaDocComments;
private SelectionButtonDialogField fCreateSeeComments;
private SelectionButtonDialogField fCreateFileComments;
private IStatus fGetterSetterPrefixStatus;
private IStatus fGetterSetterSuffixStatus;
public CodeGenerationPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CodeGenerationPreferencePage.description")); //$NON-NLS-1$
IDialogFieldListener listener= new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doDialogFieldChanged(field);
}
};
fGetterSetterPrefixStatus= new StatusInfo();
fGetterSetterSuffixStatus= new StatusInfo();
fUseGetterSetterPrefix= new SelectionButtonDialogField(SWT.CHECK);
fUseGetterSetterPrefix.setDialogFieldListener(listener);
fUseGetterSetterPrefix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.prefix.checkbox")); //$NON-NLS-1$
fGetterSetterPrefix= new StringDialogField();
fGetterSetterPrefix.setDialogFieldListener(listener);
fGetterSetterPrefix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.prefix.list")); //$NON-NLS-1$
fUseGetterSetterSuffix= new SelectionButtonDialogField(SWT.CHECK);
fUseGetterSetterSuffix.setDialogFieldListener(listener);
fUseGetterSetterSuffix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.suffix.checkbox")); //$NON-NLS-1$
fGetterSetterSuffix= new StringDialogField();
fGetterSetterSuffix.setDialogFieldListener(listener);
fGetterSetterSuffix.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.suffix.list")); //$NON-NLS-1$
fCreateJavaDocComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateJavaDocComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.javadoc_comment.label")); //$NON-NLS-1$
fCreateSeeComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateSeeComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.see_comment.label")); //$NON-NLS-1$
fCreateFileComments= new SelectionButtonDialogField(SWT.CHECK);
fCreateFileComments.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.file_comment.label")); //$NON-NLS-1$
}
private void initFields() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fUseGetterSetterSuffix.setSelection(prefs.getBoolean(PREF_USE_GETTERSETTER_SUFFIX));
String str= prefs.getString(PREF_GETTERSETTER_SUFFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterSuffix.setText(str);
fUseGetterSetterPrefix.setSelection(prefs.getBoolean(PREF_USE_GETTERSETTER_PREFIX));
str= prefs.getString(PREF_GETTERSETTER_PREFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterPrefix.setText(str);
fCreateJavaDocComments.setSelection(prefs.getBoolean(PREF_JAVADOC_STUBS));
fCreateSeeComments.setSelection(prefs.getBoolean(PREF_SEE_COMMENTS));
fCreateFileComments.setSelection(prefs.getBoolean(PREF_FILE_COMMENTS));
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
int horizontalIndent= convertWidthInCharsToPixels(4);
(new Separator()).doFillIntoGrid(composite, 2, 4);
DialogField javaDocLabel= new DialogField();
javaDocLabel.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.comments.label")); //$NON-NLS-1$
javaDocLabel.doFillIntoGrid(composite, 2);
fCreateJavaDocComments.doFillIntoGrid(composite, 2);
fCreateSeeComments.doFillIntoGrid(composite, 2);
fCreateFileComments.doFillIntoGrid(composite, 2);
(new Separator()).doFillIntoGrid(composite, 2, 4);
DialogField getterSetterLabel= new DialogField();
getterSetterLabel.setLabelText(JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.label")); //$NON-NLS-1$
getterSetterLabel.doFillIntoGrid(composite, 2);
fUseGetterSetterPrefix.doFillIntoGrid(composite, 2);
fGetterSetterPrefix.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalIndent(fGetterSetterPrefix.getLabelControl(null), horizontalIndent);
LayoutUtil.setHorizontalGrabbing(fGetterSetterPrefix.getTextControl(null));
fUseGetterSetterSuffix.doFillIntoGrid(composite, 2);
fGetterSetterSuffix.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalIndent(fGetterSetterSuffix.getLabelControl(null), horizontalIndent);
initFields();
return composite;
}
private void doDialogFieldChanged(DialogField field) {
if (field == fGetterSetterPrefix || field == fUseGetterSetterPrefix) {
fGetterSetterPrefix.setEnabled(fUseGetterSetterPrefix.isSelected());
if (fUseGetterSetterPrefix.isSelected()) {
String[] prefixes= unpackOrderList(fGetterSetterPrefix.getText());
fGetterSetterPrefixStatus= validateIdentifiers(prefixes, true);
} else {
fGetterSetterPrefixStatus= new StatusInfo();
}
}
if (field == fGetterSetterSuffix || field == fUseGetterSetterSuffix) {
fGetterSetterSuffix.setEnabled(fUseGetterSetterSuffix.isSelected());
if (fUseGetterSetterSuffix.isSelected()) {
String[] prefixes= unpackOrderList(fGetterSetterSuffix.getText());
fGetterSetterSuffixStatus= validateIdentifiers(prefixes, false);
} else {
fGetterSetterSuffixStatus= new StatusInfo();
}
}
updateStatus(StatusUtil.getMoreSevere(fGetterSetterPrefixStatus, fGetterSetterSuffixStatus));
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private IStatus validateIdentifiers(String[] values, boolean prefix) {
for (int i= 0; i < values.length; i++) {
String val= values[i];
if (val.length() == 0) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.error.emptyprefix")); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getString("CodeGenerationPreferencePage.gettersetter.error.emptysuffix")); //$NON-NLS-1$
}
}
String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$
IStatus status= JavaConventions.validateFieldName(name);
if (status.matches(IStatus.ERROR)) {
if (prefix) {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getFormattedString("CodeGenerationPreferencePage.gettersetter.error.invalidprefix", val)); //$NON-NLS-1$
} else {
return new StatusInfo(IStatus.ERROR, JavaUIMessages.getFormattedString("CodeGenerationPreferencePage.gettersetter.error.invalidsuffix", val)); //$NON-NLS-1$
}
}
}
return new StatusInfo();
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
prefs.setValue(PREF_USE_GETTERSETTER_SUFFIX, fUseGetterSetterSuffix.isSelected());
prefs.setValue(PREF_GETTERSETTER_SUFFIX, fGetterSetterSuffix.getText());
prefs.setValue(PREF_USE_GETTERSETTER_PREFIX, fUseGetterSetterPrefix.isSelected());
prefs.setValue(PREF_GETTERSETTER_PREFIX, fGetterSetterPrefix.getText());
prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected());
prefs.setValue(PREF_SEE_COMMENTS, fCreateSeeComments.isSelected());
prefs.setValue(PREF_FILE_COMMENTS, fCreateFileComments.isSelected());
return super.performOk();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fUseGetterSetterSuffix.setSelection(prefs.getDefaultBoolean(PREF_USE_GETTERSETTER_SUFFIX));
String str= prefs.getDefaultString(PREF_GETTERSETTER_SUFFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterSuffix.setText(str);
fUseGetterSetterPrefix.setSelection(prefs.getDefaultBoolean(PREF_USE_GETTERSETTER_PREFIX));
str= prefs.getDefaultString(PREF_GETTERSETTER_PREFIX);
if (str == null) {
str= ""; //$NON-NLS-1$
}
fGetterSetterPrefix.setText(str);
fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS));
fCreateSeeComments.setSelection(prefs.getDefaultBoolean(PREF_SEE_COMMENTS));
fCreateFileComments.setSelection(prefs.getDefaultBoolean(PREF_FILE_COMMENTS));
super.performDefaults();
}
}
|
11,257 |
Bug 11257 Java Templates
|
In the build 1203 i have the following problems: 1> If i edit a template of JAVA like stderr then the dialog that gets opend will display: JAVA_DOC as type. 2> Filecomment and Typecomment are there but empty is this wanted?
|
verified fixed
|
15dd0ea
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T12:36:35Z | 2002-03-13T14:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/EditTemplateDialog.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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 java.util.Vector;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
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.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.core.runtime.CoreException;
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.resource.JFaceResources;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextListener;
import org.eclipse.jface.text.ITextOperationTarget;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextEvent;
import org.eclipse.jface.text.contentassist.ContentAssistant;
import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
import org.eclipse.jface.text.contentassist.IContentAssistant;
import org.eclipse.jface.text.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.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.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.TemplateContext;
import org.eclipse.jdt.internal.corext.template.TemplateMessages;
import org.eclipse.jdt.internal.corext.template.TemplateTranslator;
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.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 IContentAssistProcessor fProcessor;
SimpleJavaSourceViewerConfiguration(JavaTextTools tools, ITextEditor editor, IContentAssistProcessor processor) {
super(tools, editor);
fProcessor= processor;
}
/*
* @see SourceViewerConfiguration#getContentAssistant(ISourceViewer)
*/
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
ContentAssistant assistant= new ContentAssistant();
assistant.setContentAssistProcessor(fProcessor, IDocument.DEFAULT_CONTENT_TYPE);
assistant.enableAutoActivation(true);
assistant.setAutoActivationDelay(500);
assistant.setProposalPopupOrientation(assistant.PROPOSAL_OVERLAY);
assistant.setContextInformationPopupOrientation(assistant.CONTEXT_INFO_ABOVE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
Color background= getColorManager().getColor(new RGB(254, 241, 233));
assistant.setContextInformationPopupBackground(background);
assistant.setContextSelectorBackground(background);
assistant.setProposalSelectorBackground(background);
return assistant;
}
}
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 Template fTemplate;
private Text fNameText;
private Text fDescriptionText;
private Combo fContextCombo;
private SourceViewer fPatternEditor;
private Button fInsertVariableButton;
private TemplateTranslator fTranslator= new TemplateTranslator();
private boolean fSuppressError= true; // #4354
private Map fGlobalActions= new HashMap(10);
private List fSelectionActions = new ArrayList(3);
private Vector fContextTypes= new Vector();
private final TemplateVariableProcessor fProcessor= new TemplateVariableProcessor();
public EditTemplateDialog(Shell parent, Template template, boolean edit) {
super(parent);
int shellStyle= getShellStyle();
setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE);
if (edit)
setTitle(TemplateMessages.getString("EditTemplateDialog.title.edit")); //$NON-NLS-1$
else
setTitle(TemplateMessages.getString("EditTemplateDialog.title.new")); //$NON-NLS-1$
fTemplate= template;
ContextTypeRegistry registry= ContextTypeRegistry.getInstance();
for (Iterator iterator= registry.iterator(); iterator.hasNext(); )
fContextTypes.add(iterator.next());
if (fContextTypes.size() > 0)
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType((String) fContextTypes.get(0)));
}
/*
* @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));
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(new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (fSuppressError && (fNameText.getText().trim().length() != 0))
fSuppressError= false;
updateButtons();
}
});
createLabel(composite, TemplateMessages.getString("EditTemplateDialog.context")); //$NON-NLS-1$
fContextCombo= new Combo(composite, SWT.READ_ONLY);
for (Iterator iterator= fContextTypes.iterator(); iterator.hasNext(); ) {
String contextName= (String) iterator.next();
if (contextName.equals("java"))
fContextCombo.add(contextName, 0);
else
fContextCombo.add(contextName);
}
fContextCombo.addModifyListener(new ModifyListener() {
public void modifyText(ModifyEvent e) {
String name= fContextCombo.getText();
fProcessor.setContextType(ContextTypeRegistry.getInstance().getContextType(name));
}
});
createLabel(parent, TemplateMessages.getString("EditTemplateDialog.description")); //$NON-NLS-1$
fDescriptionText= createText(parent);
composite= new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
composite.setLayout(layout);
createLabel(composite, TemplateMessages.getString("EditTemplateDialog.pattern")); //$NON-NLS-1$
fPatternEditor= createEditor(parent);
Label filler= new Label(composite, SWT.NONE);
filler.setLayoutData(new GridData(GridData.FILL_VERTICAL));
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.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
public void widgetDefaultSelected(SelectionEvent e) {}
});
fNameText.setText(fTemplate.getName());
fDescriptionText.setText(fTemplate.getDescription());
fContextCombo.select(getIndex(fTemplate.getContextTypeName()));
initializeActions();
return composite;
}
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();
viewer.configure(new SimpleJavaSourceViewerConfiguration(tools, null, fProcessor));
viewer.setEditable(true);
viewer.setDocument(new Document(fTemplate.getPattern()));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(60);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
viewer.addTextListener(new ITextListener() {
public void textChanged(TextEvent event) {
try {
fTranslator.translate(event.getDocumentEvent().getDocument().get());
} catch (CoreException e) {
JavaPlugin.log(e);
// XXX dialog
}
updateUndoAction();
updateButtons();
}
});
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
updateSelectionDependentActions();
}
});
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.CTRL)
return;
switch (event.character) {
case ' ':
fPatternEditor.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
break;
// XXX CTRL-Z
case (int) 'z' - (int) 'a' + 1:
fPatternEditor.doOperation(ITextOperationTarget.UNDO);
break;
}
}
private void initializeActions() {
TextViewerAction action= new TextViewerAction(fPatternEditor, fPatternEditor.UNDO);
action.setText(TemplateMessages.getString("EditTemplateDialog.undo")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.UNDO, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.CUT);
action.setText(TemplateMessages.getString("EditTemplateDialog.cut")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.CUT, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.COPY);
action.setText(TemplateMessages.getString("EditTemplateDialog.copy")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.COPY, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.PASTE);
action.setText(TemplateMessages.getString("EditTemplateDialog.paste")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.PASTE, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.SELECT_ALL);
action.setText(TemplateMessages.getString("EditTemplateDialog.select.all")); //$NON-NLS-1$
fGlobalActions.put(ITextEditorActionConstants.SELECT_ALL, action);
action= new TextViewerAction(fPatternEditor, fPatternEditor.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;
return fContextTypes.indexOf(context);
}
protected void okPressed() {
fTemplate.setName(fNameText.getText());
fTemplate.setDescription(fDescriptionText.getText());
fTemplate.setContext(fContextCombo.getText());
fTemplate.setPattern(fPatternEditor.getTextWidget().getText());
super.okPressed();
}
private void updateButtons() {
boolean valid= fNameText.getText().trim().length() != 0;
StatusInfo status= new StatusInfo();
if (!valid) {
if (fSuppressError)
status.setError(""); //$NON-NLS-1$
else
status.setError(TemplateMessages.getString("EditTemplateDialog.error.noname")); //$NON-NLS-1$
} else if (fTranslator.getErrorMessage() != null) {
status.setError(fTranslator.getErrorMessage());
}
updateStatus(status);
}
}
|
11,257 |
Bug 11257 Java Templates
|
In the build 1203 i have the following problems: 1> If i edit a template of JAVA like stderr then the dialog that gets opend will display: JAVA_DOC as type. 2> Filecomment and Typecomment are there but empty is this wanted?
|
verified fixed
|
15dd0ea
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T12:36:35Z | 2002-03-13T14:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TemplatePreferencePage.java
|
package org.eclipse.jdt.internal.ui.preferences;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
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.core.runtime.CoreException;
import org.eclipse.jface.dialogs.ErrorDialog;
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.source.SourceViewer;
import org.eclipse.jface.viewers.CheckStateChangedEvent;
import org.eclipse.jface.viewers.CheckboxTableViewer;
import org.eclipse.jface.viewers.ColumnWeightData;
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.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.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.ui.JavaUI;
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.TemplateContext;
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.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.text.template.TemplateContentProvider;
import org.eclipse.jdt.internal.ui.text.template.TemplateLabelProvider;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
public class TemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// preference store keys
private static final String PREF_FORMAT_TEMPLATES= JavaUI.ID_PLUGIN + ".template.format"; //$NON-NLS-1$
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();
}
/**
* @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);
Table table= new Table(parent, SWT.CHECK | SWT.BORDER | SWT.MULTI | SWT.FULL_SELECTION);
GridData data= new GridData(GridData.FILL_BOTH);
data.widthHint= convertWidthInCharsToPixels(80);
data.heightHint= convertHeightInCharsToPixels(10);
table.setLayoutData(data);
table.setHeaderVisible(true);
table.setLinesVisible(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$
tableLayout.addColumnData(new ColumnWeightData(30));
tableLayout.addColumnData(new ColumnWeightData(20));
tableLayout.addColumnData(new ColumnWeightData(70));
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(parent, SWT.NULL);
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.setLayoutData(getButtonGridData(fAddButton));
fAddButton.setText(TemplateMessages.getString("TemplatePreferencePage.new")); //$NON-NLS-1$
fAddButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
add();
}
});
fEditButton= new Button(buttons, SWT.PUSH);
fEditButton.setLayoutData(getButtonGridData(fEditButton));
fEditButton.setText(TemplateMessages.getString("TemplatePreferencePage.edit")); //$NON-NLS-1$
fEditButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
edit();
}
});
fRemoveButton= new Button(buttons, SWT.PUSH);
fRemoveButton.setLayoutData(getButtonGridData(fRemoveButton));
fRemoveButton.setText(TemplateMessages.getString("TemplatePreferencePage.remove")); //$NON-NLS-1$
fRemoveButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
remove();
}
});
createSpacer(buttons);
fImportButton= new Button(buttons, SWT.PUSH);
fImportButton.setLayoutData(getButtonGridData(fImportButton));
fImportButton.setText(TemplateMessages.getString("TemplatePreferencePage.import")); //$NON-NLS-1$
fImportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
import_();
}
});
fExportButton= new Button(buttons, SWT.PUSH);
fExportButton.setLayoutData(getButtonGridData(fExportButton));
fExportButton.setText(TemplateMessages.getString("TemplatePreferencePage.export")); //$NON-NLS-1$
fExportButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
export();
}
});
fExportAllButton= new Button(buttons, SWT.PUSH);
fExportAllButton.setLayoutData(getButtonGridData(fExportAllButton));
fExportAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.export.all")); //$NON-NLS-1$
fExportAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
exportAll();
}
});
createSpacer(buttons);
fEnableAllButton= new Button(buttons, SWT.PUSH);
fEnableAllButton.setLayoutData(getButtonGridData(fEnableAllButton));
fEnableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.enable.all")); //$NON-NLS-1$
fEnableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(true);
}
});
fDisableAllButton= new Button(buttons, SWT.PUSH);
fDisableAllButton.setLayoutData(getButtonGridData(fDisableAllButton));
fDisableAllButton.setText(TemplateMessages.getString("TemplatePreferencePage.disable.all")); //$NON-NLS-1$
fDisableAllButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
enableAll(false);
}
});
fPatternViewer= createViewer(parent);
createSpacer(parent);
fFormatButton= new Button(parent, SWT.CHECK);
fFormatButton.setText(TemplateMessages.getString("TemplatePreferencePage.use.code.formatter")); //$NON-NLS-1$
fTableViewer.setInput(fTemplates);
fTableViewer.setAllChecked(false);
fTableViewer.setCheckedElements(getEnabledTemplates());
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
fFormatButton.setSelection(prefs.getBoolean(PREF_FORMAT_TEMPLATES));
updateButtons();
WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.TEMPLATE_PREFERENCE_PAGE);
return parent;
}
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("Preview:");
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();
viewer.configure(new JavaSourceViewerConfiguration(tools, null));
viewer.setEditable(false);
viewer.setDocument(new Document());
viewer.getTextWidget().setBackground(getShell().getDisplay().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
Font font= JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT);
viewer.getTextWidget().setFont(font);
Control control= viewer.getControl();
data= new GridData(GridData.FILL_BOTH);
data.heightHint= convertHeightInCharsToPixels(5);
control.setLayoutData(data);
return viewer;
}
public void createSpacer(Composite parent) {
Label spacer= new Label(parent, SWT.NONE);
GridData data= new GridData();
data.horizontalAlignment= GridData.FILL;
data.verticalAlignment= GridData.BEGINNING;
data.heightHint= 4;
spacer.setLayoutData(data);
}
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.getTextWidget().setText(template.getPattern());
} else {
fPatternViewer.getTextWidget().setText(""); //$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();
ContextTypeRegistry registry=ContextTypeRegistry.getInstance();
Iterator iterator= registry.iterator();
String contextTypeName= (String) iterator.next();
template.setContext(contextTypeName); //$NON-NLS-1$
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, false);
if (dialog.open() == dialog.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) {
EditTemplateDialog dialog= new EditTemplateDialog(getShell(), template, true);
if (dialog.open() == dialog.OK) {
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));
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();
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;
try {
templateSet.saveToFile(new File(path));
} catch (CoreException e) {
JavaPlugin.log(e);
openWriteErrorDialog(e);
}
}
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) {
JavaPlugin.log(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);
}
return super.performOk();
}
/*
* @see PreferencePage#performCancel()
*/
public boolean performCancel() {
try {
fTemplates.reset();
} catch (CoreException e) {
JavaPlugin.log(e);
openReadErrorDialog(e);
}
return super.performCancel();
}
/**
* Initializes the default values of this page in the preference bundle.
* Will be called on startup of the JavaPlugin
*/
public static void initDefaults(IPreferenceStore prefs) {
prefs.setDefault(PREF_FORMAT_TEMPLATES, true);
}
public static boolean useCodeFormatter() {
IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore();
return prefs.getBoolean(PREF_FORMAT_TEMPLATES);
}
private void openReadErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.read.title"), //$NON-NLS-1$
null, e.getStatus());
}
private void openWriteErrorDialog(CoreException e) {
ErrorDialog.openError(getShell(),
TemplateMessages.getString("TemplatePreferencePage.error.write.title"), //$NON-NLS-1$
null, e.getStatus());
}
}
|
11,814 |
Bug 11814 OpenExternalJavadoc action should not call findElement on JAR
|
This causes an exception: Java Model Exception: Java Model Status [Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.] at org.eclipse.jdt.internal.core.JavaProject.findElement(JavaProject.java:435) at org.eclipse.jdt.internal.ui.actions.OpenExternalJavadocAction.run(OpenExternalJavadocAction.java:102) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52) 4 org.eclipse.jdt.core 979 Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.
|
resolved fixed
|
a05d335
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T15:30:34Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/core
| |
11,814 |
Bug 11814 OpenExternalJavadoc action should not call findElement on JAR
|
This causes an exception: Java Model Exception: Java Model Status [Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.] at org.eclipse.jdt.internal.core.JavaProject.findElement(JavaProject.java:435) at org.eclipse.jdt.internal.ui.actions.OpenExternalJavadocAction.run(OpenExternalJavadocAction.java:102) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52) 4 org.eclipse.jdt.core 979 Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.
|
resolved fixed
|
a05d335
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T15:30:34Z | 2002-03-20T10:26:40Z |
extension/org/eclipse/jdt/internal/corext/javadoc/JavaDocLocations.java
| |
11,814 |
Bug 11814 OpenExternalJavadoc action should not call findElement on JAR
|
This causes an exception: Java Model Exception: Java Model Status [Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.] at org.eclipse.jdt.internal.core.JavaProject.findElement(JavaProject.java:435) at org.eclipse.jdt.internal.ui.actions.OpenExternalJavadocAction.run(OpenExternalJavadocAction.java:102) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52) 4 org.eclipse.jdt.core 979 Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.
|
resolved fixed
|
a05d335
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T15:30:34Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/OpenExternalJavadocAction.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.actions;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.MessageFormat;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.program.Program;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* On a selected member; opens the Javadoc in an external browser (if existing)
*/
public class OpenExternalJavadocAction extends Action implements IUpdate, IObjectActionDelegate {
private StructuredSelectionProvider fSelectionProvider;
/**
* Use only for IWorkbenchWindowActionDelegates!
*/
public OpenExternalJavadocAction() {
this(null);
}
public OpenExternalJavadocAction(StructuredSelectionProvider provider) {
super();
setText("Open E&xternal Javadoc@Shift+F2");
setDescription("Opens the Javadoc of the selected element in an external browser");
setToolTipText("Opens the Javadoc of the selected element in an external browser");
fSelectionProvider= provider;
}
public void update() {
setEnabled(canOperateOn());
}
private boolean canOperateOn() {
if (fSelectionProvider != null) {
IStructuredSelection selection= fSelectionProvider.getSelection(StructuredSelectionProvider.FLAGS_GET_EDITOR_INPUT);
return selection.size() == 1;
}
return false;
}
private Object getSelectedElement() {
if (fSelectionProvider == null) {
return null;
}
IStructuredSelection selection= fSelectionProvider.getSelection(StructuredSelectionProvider.FLAGS_DO_CODERESOLVE | StructuredSelectionProvider.FLAGS_GET_EDITOR_INPUT);
if (selection.size() != 1)
return null;
return selection.getFirstElement();
}
public void run() {
Object selected= getSelectedElement();
if (!(selected instanceof IJavaElement)) {
return;
}
IJavaElement jelem= (IJavaElement) selected;
Shell shell= JavaPlugin.getActiveWorkbenchShell();
try {
String labelName= JavaElementLabels.getElementLabel(jelem, JavaElementLabels.M_PARAMETER_TYPES);
IPath annotatedPath= JavaDocLocations.getAnnotatedPath(jelem);
if (annotatedPath == null) {
String message= "No Javadoc available for element ''{0}''";
showError(shell, MessageFormat.format(message, new String[] { labelName }));
return;
}
URL baseURL= JavaDocLocations.getJavadocLocation(annotatedPath);
if (baseURL == null) {
IJavaElement annotatedElement= jelem.getJavaProject().findElement(annotatedPath);
if (annotatedElement.getElementType() == IJavaElement.JAVA_PROJECT) {
String message= "The documentation location for ''{0}'' has not been configured. For elements from source specify the Javadoc location URL on the property page of the parent project (''{1}'').";
showError(shell, MessageFormat.format(message, new String[] { labelName, annotatedElement.getElementName() }));
return;
} else {
String message= "The documentation location for ''{0}'' has not been configured. For elements from libraries specify the Javadoc location URL on the property page of the parent JAR (''{1}'').";
showError(shell, MessageFormat.format(message, new String[] { labelName, annotatedElement.getElementName() }));
return;
}
}
if ("file".equals(baseURL.getProtocol())) {
URL noRefURL= JavaDocLocations.getJavaDocLocation(jelem, false);
if (!(new File(noRefURL.getFile())).isFile()) {
String message= "No documentation available for ''{0}'' in ''{1}''.";
showError(shell, MessageFormat.format(message, new String[] { labelName, baseURL.toExternalForm() }));
return;
}
}
URL url= JavaDocLocations.getJavaDocLocation(jelem, true);
if (url != null) {
openInBrowser(url, shell);
}
} catch (CoreException e) {
JavaPlugin.log(e);
showError(shell, "Opening Javadoc failed. See log for details.");
}
}
/*
* @see IActionDelegate#run(IAction)
*/
public void run(IAction action) {
run();
}
/*
* @see IActionDelegate#selectionChanged(IAction, ISelection)
*/
public void selectionChanged(IAction action, ISelection selection) {
}
/*
* @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
*/
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
fSelectionProvider= StructuredSelectionProvider.createFrom(targetPart.getSite().getWorkbenchWindow().getSelectionService());
}
private static boolean webBrowserOpened = false;
/**
* Copied from AboutPluginsDialog.openMoreInfo
*/
public static void openInBrowser(final URL url, final Shell shell) {
//System.out.println("Opening " + url.toExternalForm());
if (SWT.getPlatform().equals("win32")) { //$NON-NLS-1$
if (!Program.launch(url.toString())) {
showError(shell, "Opening '" + url.toString() + "' with external editor failed.");
}
} else {
Thread launcher = new Thread("External Javadoc Launcher") { //$NON-NLS-1$
public void run() {
try {
if (webBrowserOpened) {
Runtime.getRuntime().exec("netscape -remote openURL(" + url.toString() + ")"); //$NON-NLS-1$
} else {
Process p = Runtime.getRuntime().exec("netscape " + url.toString()); //$NON-NLS-1$
webBrowserOpened = true;
try {
if (p != null)
p.waitFor();
} catch (InterruptedException e) {
JavaPlugin.log(e);
showError(shell, "Opening cancelled.");
} finally {
webBrowserOpened = false;
}
}
} catch (IOException e) {
JavaPlugin.log(e);
showError(shell, "Opening failed. See log for details");
}
}
};
launcher.start();
}
}
private static void showError(final Shell shell, final String message) {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
MessageDialog.openError(shell, "Open External Javadoc", message);
}
});
}
}
|
11,814 |
Bug 11814 OpenExternalJavadoc action should not call findElement on JAR
|
This causes an exception: Java Model Exception: Java Model Status [Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.] at org.eclipse.jdt.internal.core.JavaProject.findElement(JavaProject.java:435) at org.eclipse.jdt.internal.ui.actions.OpenExternalJavadocAction.run(OpenExternalJavadocAction.java:102) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52) 4 org.eclipse.jdt.core 979 Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.
|
resolved fixed
|
a05d335
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T15:30:34Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
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.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage;
import org.eclipse.jdt.internal.ui.util.CoreUtility;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer;
import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
public class BuildPathsBlock {
private IWorkspaceRoot fWorkspaceRoot;
private CheckedListDialogField fClassPathList;
private StringDialogField fBuildPathDialogField;
private StatusInfo fClassPathStatus;
private StatusInfo fBuildPathStatus;
private IJavaProject fCurrJProject;
private IPath fOutputLocationPath;
private IStatusChangeListener fContext;
private Control fSWTWidget;
private boolean fIsNewProject;
private SourceContainerWorkbookPage fSourceContainerPage;
private ProjectsWorkbookPage fProjectsPage;
private LibrariesWorkbookPage fLibrariesPage;
private BuildPathBasePage fCurrPage;
public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean isNewProject) {
fWorkspaceRoot= root;
fContext= context;
fIsNewProject= isNewProject;
fSourceContainerPage= null;
fLibrariesPage= null;
fProjectsPage= null;
fCurrPage= null;
BuildPathAdapter adapter= new BuildPathAdapter();
String[] buttonLabels= new String[] {
/* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$
/* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$
/* 2 */ null,
/* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$
/* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$
};
fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider());
fClassPathList.setDialogFieldListener(adapter);
fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label"));
fClassPathList.setUpButtonIndex(0);
fClassPathList.setDownButtonIndex(1);
fClassPathList.setCheckAllButtonIndex(3);
fClassPathList.setUncheckAllButtonIndex(4);
if (isNewProject) {
fBuildPathDialogField= new StringDialogField();
} else {
StringButtonDialogField dialogField= new StringButtonDialogField(adapter);
dialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$
fBuildPathDialogField= dialogField;
}
fBuildPathDialogField.setDialogFieldListener(adapter);
fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$
fBuildPathStatus= new StatusInfo();
fClassPathStatus= new StatusInfo();
fCurrJProject= null;
}
// -------- UI creation ---------
public Control createControl(Composite parent) {
fSWTWidget= parent;
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.numColumns= 1;
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
folder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
tabChanged(e.item);
}
});
ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry();
TabItem item;
fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField, fIsNewProject);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT));
item.setData(fSourceContainerPage);
item.setControl(fSourceContainerPage.getControl(folder));
IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT);
fProjectsPage= new ProjectsWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$
item.setImage(projectImage);
item.setData(fProjectsPage);
item.setControl(fProjectsPage.getControl(folder));
fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$
item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY));
item.setData(fLibrariesPage);
item.setControl(fLibrariesPage.getControl(folder));
// a non shared image
Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage();
composite.addDisposeListener(new ImageDisposer(cpoImage));
ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList);
item= new TabItem(folder, SWT.NONE);
item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$
item.setImage(cpoImage);
item.setData(ordpage);
item.setControl(ordpage.getControl(folder));
if (fCurrJProject != null) {
fSourceContainerPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
}
Composite editorcomp= new Composite(composite, SWT.NONE);
DialogField[] editors= new DialogField[] { fBuildPathDialogField };
LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0);
int maxFieldWidth= converter.convertWidthInCharsToPixels(40);
LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth);
LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null));
editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (fIsNewProject) {
folder.setSelection(0);
fCurrPage= fSourceContainerPage;
} else {
folder.setSelection(3);
fCurrPage= ordpage;
fClassPathList.selectFirstElement();
}
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK);
return composite;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Initializes the classpath for the given project. Multiple calls to init are allowed,
* but all existing settings will be cleared and replace by the given or default paths.
* @param project The java project to configure. Does not have to exist.
* @param outputLocation The output location to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project - the
* output location of the existing project
* @param classpathEntries The classpath entries to be set in the page. If <code>null</code>
* is passed, jdt default settings are used, or - if the project is an existing Java project - the
* classpath entries of the existing project
*/
public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) {
fCurrJProject= jproject;
boolean projExists= false;
try {
IProject project= fCurrJProject.getProject();
projExists= (project.exists() && project.hasNature(JavaCore.NATURE_ID));
if (projExists) {
if (outputLocation == null) {
outputLocation= fCurrJProject.getOutputLocation();
}
if (classpathEntries == null) {
classpathEntries= fCurrJProject.getRawClasspath();
}
}
} catch (CoreException e) {
JavaPlugin.log(e.getStatus());
}
if (outputLocation == null) {
outputLocation= getDefaultBuildPath(jproject);
}
List newClassPath;
if (classpathEntries == null) {
newClassPath= getDefaultClassPath(jproject);
} else {
newClassPath= new ArrayList();
for (int i= 0; i < classpathEntries.length; i++) {
IClasspathEntry curr= classpathEntries[i];
int entryKind= curr.getEntryKind();
IPath path= curr.getPath();
boolean isExported= curr.isExported();
// get the resource
IResource res= null;
boolean isMissing= false;
if (entryKind != IClasspathEntry.CPE_VARIABLE) {
res= fWorkspaceRoot.findMember(path);
if (res == null) {
isMissing= (entryKind != IClasspathEntry.CPE_LIBRARY || !path.toFile().isFile());
}
} else {
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
isMissing= (resolvedPath == null) || !resolvedPath.toFile().isFile();
}
CPListElement elem= new CPListElement(entryKind, path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported);
if (projExists) {
elem.setIsMissing(isMissing);
}
newClassPath.add(elem);
}
}
List exportedEntries = new ArrayList();
for (int i= 0; i < newClassPath.size(); i++) {
CPListElement curr= (CPListElement) newClassPath.get(i);
if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
exportedEntries.add(curr);
}
}
// inits the dialog field
fBuildPathDialogField.setText(outputLocation.makeRelative().toString());
fClassPathList.setElements(newClassPath);
fClassPathList.setCheckedElements(exportedEntries);
if (fSourceContainerPage != null) {
fSourceContainerPage.init(fCurrJProject);
fProjectsPage.init(fCurrJProject);
fLibrariesPage.init(fCurrJProject);
}
doStatusLineUpdate();
}
// -------- public api --------
/**
* Returns the Java project. Can return <code>null<code> if the page has not
* been initialized.
*/
public IJavaProject getJavaProject() {
return fCurrJProject;
}
/**
* Returns the current output location. Note that the path returned must not be valid.
*/
public IPath getOutputLocation() {
return new Path(fBuildPathDialogField.getText()).makeAbsolute();
}
/**
* Returns the current class path (raw). Note that the entries returned must not be valid.
*/
public IClasspathEntry[] getRawClassPath() {
List elements= fClassPathList.getElements();
int nElements= elements.size();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= 0; i < nElements; i++) {
CPListElement currElement= (CPListElement) elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
return entries;
}
// -------- evaluate default settings --------
private List getDefaultClassPath(IJavaProject jproj) {
List list= new ArrayList();
IResource srcFolder;
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String sourceFolderName= JavaBasePreferencePage.getSourceFolderName();
srcFolder= jproj.getProject().getFolder(sourceFolderName);
} else {
srcFolder= jproj.getProject();
}
list.add(new CPListElement(IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder));
IPath libPath= new Path(JavaRuntime.JRELIB_VARIABLE);
IPath attachPath= new Path(JavaRuntime.JRESRC_VARIABLE);
IPath attachRoot= new Path(JavaRuntime.JRESRCROOT_VARIABLE);
CPListElement elem= new CPListElement(IClasspathEntry.CPE_VARIABLE, libPath, null, attachPath, attachRoot, false);
list.add(elem);
return list;
}
private IPath getDefaultBuildPath(IJavaProject jproj) {
if (JavaBasePreferencePage.useSrcAndBinFolders()) {
String outputLocationName= JavaBasePreferencePage.getOutputLocationName();
return jproj.getProject().getFullPath().append(outputLocationName);
} else {
return jproj.getProject().getFullPath();
}
}
private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
buildPathChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
buildPathDialogFieldChanged(field);
}
}
private void buildPathChangeControlPressed(DialogField field) {
if (field == fBuildPathDialogField) {
IContainer container= chooseContainer();
if (container != null) {
fBuildPathDialogField.setText(container.getFullPath().toString());
}
}
}
private void buildPathDialogFieldChanged(DialogField field) {
if (field == fClassPathList) {
updateClassPathStatus();
updateBuildPathStatus();
} else if (field == fBuildPathDialogField) {
updateBuildPathStatus();
}
doStatusLineUpdate();
}
// -------- verification -------------------------------
private void doStatusLineUpdate() {
IStatus res= findMostSevereStatus();
fContext.statusChanged(res);
}
private IStatus findMostSevereStatus() {
return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus);
}
/**
* Validates the build path.
*/
private void updateClassPathStatus() {
fClassPathStatus.setOK();
List elements= fClassPathList.getElements();
boolean entryMissing= false;
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
boolean isChecked= fClassPathList.isChecked(currElement);
if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
if (!isChecked) {
fClassPathList.setCheckedWithoutUpdate(currElement, true);
}
} else {
currElement.setExported(isChecked);
}
entries[i]= currElement.getClasspathEntry();
entryMissing= entryMissing || currElement.isMissing();
}
if (entryMissing) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$
}
if (fCurrJProject.hasClasspathCycle(entries)) {
fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$
}
}
/**
* Validates output location & build path.
*/
private void updateBuildPathStatus() {
fOutputLocationPath= null;
String text= fBuildPathDialogField.getText();
if ("".equals(text)) { //$NON-NLS-1$
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$
return;
}
IPath path= getOutputLocation();
IResource res= fWorkspaceRoot.findMember(path);
if (res != null) {
// if exists, must be a folder or project
if (res.getType() == IResource.FILE) {
fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$
return;
}
}
fOutputLocationPath= path;
List elements= fClassPathList.getElements();
IClasspathEntry[] entries= new IClasspathEntry[elements.size()];
for (int i= elements.size()-1 ; i >= 0 ; i--) {
CPListElement currElement= (CPListElement)elements.get(i);
entries[i]= currElement.getClasspathEntry();
}
IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path);
if (!status.isOK()) {
fBuildPathStatus.setError(status.getMessage());
return;
}
fBuildPathStatus.setOK();
}
// -------- creation -------------------------------
/**
* Creates a runnable that sets the configured build paths.
*/
public IRunnableWithProgress getRunnable() {
final List classPathEntries= fClassPathList.getElements();
final IPath path= getOutputLocation();
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$
try {
createJavaProject(classPathEntries, path, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
}
}
};
}
/**
* Creates the Java project and sets the configured build path and output location.
* If the project already exists only build paths are updated.
*/
private void createJavaProject(List classPathEntries, IPath buildPath, IProgressMonitor monitor) throws CoreException {
// 10 monitor steps to go
IProject project= fCurrJProject.getProject();
if (!project.exists()) {
project.create(null);
}
if (!project.isOpen()) {
project.open(null);
}
// create java nature
if (!project.hasNature(JavaCore.NATURE_ID)) {
addNatureToProject(project, JavaCore.NATURE_ID, null);
}
monitor.worked(1);
String[] prevRequiredProjects= fCurrJProject.getRequiredProjectNames();
// create and set the output path first
if (!fWorkspaceRoot.exists(buildPath)) {
IFolder folder= fWorkspaceRoot.getFolder(buildPath);
CoreUtility.createFolder(folder, true, true, null);
}
monitor.worked(1);
int nEntries= classPathEntries.size();
IClasspathEntry[] classpath= new IClasspathEntry[nEntries];
// create and set the class path
for (int i= 0; i < nEntries; i++) {
CPListElement entry= ((CPListElement)classPathEntries.get(i));
IResource res= entry.getResource();
if ((res instanceof IFolder) && !res.exists()) {
CoreUtility.createFolder((IFolder)res, true, true, null);
}
classpath[i]= entry.getClasspathEntry();
// set javadoc location
URL javadocLocation= entry.getJavadocLocation();
if (javadocLocation != null) {
IPath path= entry.getPath();
if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
path= JavaCore.getClasspathVariable(path.segment(0));
}
if (path != null) {
JavaDocLocations.setJavadocLocation(entry.getPath(), javadocLocation);
}
}
}
monitor.worked(1);
fCurrJProject.setRawClasspath(classpath, buildPath, new SubProgressMonitor(monitor, 7));
}
/**
* Adds a nature to a project
*/
private static void addNatureToProject(IProject proj, String natureId, IProgressMonitor monitor) throws CoreException {
IProjectDescription description = proj.getDescription();
String[] prevNatures= description.getNatureIds();
String[] newNatures= new String[prevNatures.length + 1];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
newNatures[prevNatures.length]= natureId;
description.setNatureIds(newNatures);
proj.setDescription(description, monitor);
}
// ---------- util method ------------
private IContainer chooseContainer() {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
IProject[] allProjects= fWorkspaceRoot.getProjects();
ArrayList rejectedElements= new ArrayList(allProjects.length);
IProject currProject= fCurrJProject.getProject();
for (int i= 0; i < allProjects.length; i++) {
if (!allProjects[i].equals(currProject)) {
rejectedElements.add(allProjects[i]);
}
}
ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray());
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSelection= null;
if (fOutputLocationPath != null) {
initSelection= fWorkspaceRoot.findMember(fOutputLocationPath);
}
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$
dialog.setValidator(validator);
dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$
dialog.addFilter(filter);
dialog.setInput(fWorkspaceRoot);
dialog.setInitialSelection(initSelection);
if (dialog.open() == dialog.OK) {
return (IContainer)dialog.getFirstResult();
}
return null;
}
// -------- tab switching ----------
private void tabChanged(Widget widget) {
if (widget instanceof TabItem) {
BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData();
if (fCurrPage != null) {
List selection= fCurrPage.getSelection();
if (!selection.isEmpty()) {
newPage.setSelection(selection);
}
}
fCurrPage= newPage;
}
}
}
|
11,814 |
Bug 11814 OpenExternalJavadoc action should not call findElement on JAR
|
This causes an exception: Java Model Exception: Java Model Status [Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.] at org.eclipse.jdt.internal.core.JavaProject.findElement(JavaProject.java:435) at org.eclipse.jdt.internal.ui.actions.OpenExternalJavadocAction.run(OpenExternalJavadocAction.java:102) at org.eclipse.ui.texteditor.RetargetTextEditorAction.run(RetargetTextEditorAction.java:103) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java(Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:698) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.UIMain.main(UIMain.java:52) 4 org.eclipse.jdt.core 979 Invalid path: C:/Java/IBM1.3/jre/lib/rt.jar.
|
resolved fixed
|
a05d335
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T15:30:34Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.ZipFile;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ISelectionValidator;
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.wizards.IStatusChangeListener;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.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;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
/**
* UI to set the source attachment archive and root.
* Same implementation for both setting attachments for libraries from
* variable entries and for normal (internal or external) jar.
*/
public class SourceAttachmentBlock {
private IStatusChangeListener fContext;
private StringButtonDialogField fFileNameField;
private SelectionButtonDialogField fInternalButtonField;
private StringButtonDialogField fPrefixField;
private StringButtonDialogField fJavaDocField;
private boolean fIsVariableEntry;
private IStatus fNameStatus;
private IStatus fPrefixStatus;
private IStatus fJavaDocStatus;
private IPath fJARPath;
/**
* The file to which the archive path points to.
* Only set when the file exists.
*/
private File fResolvedFile;
/**
* The path to which the archive variable points.
* Null if invalid path or not resolvable. Must not exist.
*/
private IPath fFileVariablePath;
private URL fJavaDocLocation;
private IWorkspaceRoot fRoot;
private Control fSWTWidget;
private CLabel fFullPathResolvedLabel;
private CLabel fPrefixResolvedLabel;
private IClasspathEntry fOldEntry;
public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) {
fContext= context;
fRoot= root;
fOldEntry= oldEntry;
// fIsVariableEntry specifies if the UI is for a variable entry
fIsVariableEntry= (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE);
fNameStatus= new StatusInfo();
fPrefixStatus= new StatusInfo();
fJavaDocStatus= new StatusInfo();
fJARPath= (oldEntry != null) ? oldEntry.getPath() : Path.EMPTY;
SourceAttachmentAdapter adapter= new SourceAttachmentAdapter();
// create the dialog fields (no widgets yet)
if (fIsVariableEntry) {
fFileNameField= new VariablePathDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.varlabel")); //$NON-NLS-1$
fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.varbutton")); //$NON-NLS-1$
((VariablePathDialogField)fFileNameField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.variable.button")); //$NON-NLS-1$
fPrefixField= new VariablePathDialogField(adapter);
fPrefixField.setDialogFieldListener(adapter);
fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varlabel")); //$NON-NLS-1$
fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varbutton")); //$NON-NLS-1$
((VariablePathDialogField)fPrefixField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.variable.button")); //$NON-NLS-1$
} else {
fFileNameField= new StringButtonDialogField(adapter);
fFileNameField.setDialogFieldListener(adapter);
fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.label")); //$NON-NLS-1$
fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.button")); //$NON-NLS-1$
fInternalButtonField= new SelectionButtonDialogField(SWT.PUSH);
fInternalButtonField.setDialogFieldListener(adapter);
fInternalButtonField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.internal.button")); //$NON-NLS-1$
fPrefixField= new StringButtonDialogField(adapter);
fPrefixField.setDialogFieldListener(adapter);
fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.label")); //$NON-NLS-1$
fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.button")); //$NON-NLS-1$
}
fJavaDocField= new StringButtonDialogField(adapter);
fJavaDocField.setDialogFieldListener(adapter);
fJavaDocField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.label")); //$NON-NLS-1$
fJavaDocField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.button")); //$NON-NLS-1$
// set the old settings
setDefaults();
}
public void setDefaults() {
if (fOldEntry != null && fOldEntry.getSourceAttachmentPath() != null) {
fFileNameField.setText(fOldEntry.getSourceAttachmentPath().toString());
} else {
fFileNameField.setText(""); //$NON-NLS-1$
}
if (fOldEntry != null && fOldEntry.getSourceAttachmentRootPath() != null) {
fPrefixField.setText(fOldEntry.getSourceAttachmentRootPath().toString());
} else {
fPrefixField.setText(""); //$NON-NLS-1$
}
String jdocText= "";
if (fOldEntry != null) {
IPath path= fJARPath;
if (path != null && fIsVariableEntry) {
path= getResolvedPath(path);
}
if (path != null) {
URL jdocLocation= JavaDocLocations.getJavadocLocation(path);
if (jdocLocation != null) {
jdocText= jdocLocation.toExternalForm();
}
}
}
fJavaDocField.setText(jdocText);
}
/**
* Gets the source attachment path chosen by the user
*/
public IPath getSourceAttachmentPath() {
if (fFileNameField.getText().length() == 0) {
return null;
}
return new Path(fFileNameField.getText());
}
/**
* Gets the source attachment root chosen by the user
*/
public IPath getSourceAttachmentRootPath() {
if (getSourceAttachmentPath() == null) {
return null;
} else {
return new Path(fPrefixField.getText());
}
}
/**
* Gets the Javadoc location chosen by the user
*/
public URL getJavadocLocation() {
return fJavaDocLocation;
}
/**
* Creates the control
*/
public Control createControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
fSWTWidget= parent;
Composite composite= new Composite(parent, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 4;
composite.setLayout(layout);
int widthHint= converter.convertWidthInCharsToPixels(fIsVariableEntry ? 50 : 60);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= 4;
Label message= new Label(composite, SWT.LEFT);
message.setLayoutData(gd);
message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fJARPath.lastSegment()));
if (fIsVariableEntry) {
DialogField.createEmptySpace(composite, 1);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= widthHint;
gd.horizontalSpan= 2;
Label desc= new Label(composite, SWT.LEFT + SWT.WRAP);
desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description"));
desc.setLayoutData(gd);
DialogField.createEmptySpace(composite, 1);
}
// archive name field
fFileNameField.doFillIntoGrid(composite, 4);
gd= (GridData)fFileNameField.getTextControl(null).getLayoutData();
gd.widthHint= widthHint;
if (!fIsVariableEntry) {
// aditional 'browse workspace' button for normal jars
DialogField.createEmptySpace(composite, 3);
fInternalButtonField.doFillIntoGrid(composite, 1);
} else {
// label that shows the resolved path for variable jars
DialogField.createEmptySpace(composite, 1);
fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT);
fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true));
fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(composite, 2);
}
// prefix description
DialogField.createEmptySpace(composite, 1);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= widthHint;
gd.horizontalSpan= 2;
Label desc= new Label(composite, SWT.LEFT + SWT.WRAP);
desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.description"));
desc.setLayoutData(gd);
DialogField.createEmptySpace(composite, 1);
// root path field
fPrefixField.doFillIntoGrid(composite, 4);
gd= (GridData)fPrefixField.getTextControl(null).getLayoutData();
gd.widthHint= widthHint;
if (fIsVariableEntry) {
// label that shows the resolved path for variable jars
DialogField.createEmptySpace(composite, 1);
fPrefixResolvedLabel= new CLabel(composite, SWT.LEFT);
fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false));
fPrefixResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
DialogField.createEmptySpace(composite, 2);
}
fFileNameField.postSetFocusOnDialogField(parent.getDisplay());
// if (!fIsVariableEntry) {
DialogField.createEmptySpace(composite, 1);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.widthHint= widthHint;
gd.horizontalSpan= 2;
desc= new Label(composite, SWT.LEFT + SWT.WRAP);
desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.description"));
desc.setLayoutData(gd);
DialogField.createEmptySpace(composite, 1);
fJavaDocField.doFillIntoGrid(composite, 4);
// }
WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK);
return composite;
}
private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener {
// -------- IStringButtonAdapter --------
public void changeControlPressed(DialogField field) {
attachmentChangeControlPressed(field);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
attachmentDialogFieldChanged(field);
}
}
private void attachmentChangeControlPressed(DialogField field) {
if (field == fFileNameField) {
IPath jarFilePath= chooseExtJarFile();
if (jarFilePath != null) {
fFileNameField.setText(jarFilePath.toString());
}
} else if (field == fPrefixField) {
IPath prefixPath= choosePrefix();
if (prefixPath != null) {
fPrefixField.setText(prefixPath.toString());
}
} else if (field == fJavaDocField) {
URL jdocURL= chooseJavaDocLocation();
if (jdocURL != null) {
fJavaDocField.setText(jdocURL.toExternalForm());
}
}
}
// ---------- IDialogFieldListener --------
private void attachmentDialogFieldChanged(DialogField field) {
if (field == fFileNameField) {
fNameStatus= updateFileNameStatus();
} else if (field == fInternalButtonField) {
IPath jarFilePath= chooseInternalJarFile(fFileNameField.getText());
if (jarFilePath != null) {
fFileNameField.setText(jarFilePath.toString());
}
return;
} else if (field == fPrefixField) {
fPrefixStatus= updatePrefixStatus();
} else if (field == fJavaDocField) {
fJavaDocStatus= updateJavaDocLocationStatus();
}
doStatusLineUpdate();
}
private void doStatusLineUpdate() {
fPrefixField.enableButton(canBrowsePrefix());
fFileNameField.enableButton(canBrowseFileName());
// set the resolved path for variable jars
if (fFullPathResolvedLabel != null) {
fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true));
}
if (fPrefixResolvedLabel != null) {
fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false));
}
IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus, fPrefixStatus, fJavaDocStatus });
fContext.statusChanged(status);
}
private boolean canBrowseFileName() {
if (!fIsVariableEntry) {
return true;
}
// to browse with a variable JAR, the variable name must point to a directory
if (fFileVariablePath != null) {
return fFileVariablePath.toFile().isDirectory();
}
return false;
}
private boolean canBrowsePrefix() {
// can browse when the archive name is poiting to a existing file
// and (if variable) the prefix variable name is existing
if (fResolvedFile != null) {
if (fIsVariableEntry) {
// prefix has valid format, is resolvable and not empty
return fPrefixStatus.isOK() && fPrefixField.getText().length() > 0;
}
return true;
}
return false;
}
private String getResolvedLabelString(String path, boolean osPath) {
IPath resolvedPath= getResolvedPath(new Path(path));
if (resolvedPath != null) {
if (osPath) {
return resolvedPath.toOSString();
} else {
return resolvedPath.toString();
}
}
return ""; //$NON-NLS-1$
}
private IPath getResolvedPath(IPath path) {
if (path != null) {
String varName= path.segment(0);
if (varName != null) {
IPath varPath= JavaCore.getClasspathVariable(varName);
if (varPath != null) {
return varPath.append(path.removeFirstSegments(1));
}
}
}
return null;
}
private IStatus updatePrefixStatus() {
StatusInfo status= new StatusInfo();
String prefix= fPrefixField.getText();
if (prefix.length() == 0) {
// no source attachment path
return status;
} else {
if (!Path.EMPTY.isValidPath(prefix)) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.notvalid")); //$NON-NLS-1$
return status;
}
IPath path= new Path(prefix);
if (fIsVariableEntry) {
IPath resolvedPath= getResolvedPath(path);
if (resolvedPath == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.varnotexists")); //$NON-NLS-1$
return status;
}
if (resolvedPath.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinvar")); //$NON-NLS-1$
return status;
}
} else {
if (path.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinpath")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
private IStatus updateFileNameStatus() {
StatusInfo status= new StatusInfo();
fResolvedFile= null;
fFileVariablePath= null;
String fileName= fFileNameField.getText();
if (fileName.length() == 0) {
// no source attachment
return status;
} else {
if (!Path.EMPTY.isValidPath(fileName)) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$
return status;
}
IPath filePath= new Path(fileName);
IPath resolvedPath;
if (fIsVariableEntry) {
if (filePath.getDevice() != null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.deviceinpath")); //$NON-NLS-1$
return status;
}
String varName= filePath.segment(0);
if (varName == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$
return status;
}
fFileVariablePath= JavaCore.getClasspathVariable(varName);
if (fFileVariablePath == null) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.varnotexists")); //$NON-NLS-1$
return status;
}
resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1));
if (resolvedPath.isEmpty()) {
status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.filename.warning.varempty")); //$NON-NLS-1$
return status;
}
File file= resolvedPath.toFile();
if (!file.isFile()) {
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$
status.setWarning(message);
return status;
}
fResolvedFile= file;
} else {
File file= filePath.toFile();
IResource res= fRoot.findMember(filePath);
if (res != null) {
file= res.getLocation().toFile();
}
if (!file.isFile()) {
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$
status.setError(message);
return status;
}
fResolvedFile= file;
}
}
return status;
}
private IStatus updateJavaDocLocationStatus() {
StatusInfo status= new StatusInfo();
fJavaDocLocation= null;
String jdocLocation= fJavaDocField.getText();
if (!"".equals(jdocLocation)) { //$NON-NLS-1$
try {
URL url= new URL(jdocLocation);
if ("file".equals(url.getProtocol())) { //$NON-NLS-1$
File dir= new File(url.getFile());
if (!dir.isDirectory()) {
status.setError(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.error.notafolder")); //$NON-NLS-1$
return status;
} else {
File packagesFile= new File(dir, "package-list");
if (!packagesFile.exists()) {
status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.javadoc.warning.packagelist"));
// only a warning, go on
}
}
}
fJavaDocLocation= url;
} catch (MalformedURLException e) {
status.setError(NewWizardMessages.getFormattedString("SourceAttachmentBlock.javadoc.error.malformed", e.getLocalizedMessage())); //$NON-NLS-1$
return status;
}
}
return status;
}
/*
* Opens a dialog to choose a jar from the file system.
*/
private IPath chooseExtJarFile() {
IPath currPath= new Path(fFileNameField.getText());
if (currPath.isEmpty()) {
currPath= fJARPath;
}
IPath resolvedPath= currPath;
if (fIsVariableEntry) {
resolvedPath= getResolvedPath(currPath);
if (resolvedPath == null) {
resolvedPath= Path.EMPTY;
}
}
if (ArchiveFileFilter.isArchivePath(resolvedPath)) {
resolvedPath= resolvedPath.removeLastSegments(1);
}
FileDialog dialog= new FileDialog(getShell());
dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extjardialog.text")); //$NON-NLS-1$
dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$
dialog.setFilterPath(resolvedPath.toOSString());
String res= dialog.open();
if (res != null) {
IPath returnPath= new Path(res).makeAbsolute();
if (fIsVariableEntry) {
returnPath= modifyPath(returnPath, currPath.segment(0));
}
return returnPath;
}
return null;
}
/*
* Opens a dialog to choose an internal jar.
*/
private IPath chooseInternalJarFile(String initSelection) {
Class[] acceptedClasses= new Class[] { IFile.class };
ISelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false);
ViewerFilter filter= new ArchiveFileFilter(null);
ILabelProvider lp= new WorkbenchLabelProvider();
ITreeContentProvider cp= new WorkbenchContentProvider();
IResource initSel= fRoot.findMember(new Path(initSelection));
if (initSel == null) {
initSel= fRoot.findMember(fJARPath);
}
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp);
dialog.setAllowMultiple(false);
dialog.setValidator(validator);
dialog.addFilter(filter);
dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.message")); //$NON-NLS-1$
dialog.setInput(fRoot);
dialog.setInitialSelection(initSel);
if (dialog.open() == dialog.OK) {
IFile file= (IFile) dialog.getFirstResult();
return file.getFullPath();
}
return null;
}
/*
* Opens a dialog to choose path in a zip file.
*/
private IPath choosePrefix() {
if (fResolvedFile != null) {
IPath currPath= new Path(fPrefixField.getText());
String initSelection= null;
if (fIsVariableEntry) {
IPath resolvedPath= getResolvedPath(currPath);
if (resolvedPath != null) {
initSelection= resolvedPath.toString();
}
} else {
initSelection= currPath.toString();
}
try {
ZipFile zipFile= new ZipFile(fResolvedFile);
ZipContentProvider contentProvider= new ZipContentProvider();
contentProvider.setInitialInput(zipFile);
ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), new ZipLabelProvider(), contentProvider);
dialog.setAllowMultiple(false);
dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.message")); //$NON-NLS-1$
dialog.setInput(zipFile);
dialog.setInitialSelection(contentProvider.getSelectedNode(initSelection));
if (dialog.open() == dialog.OK) {
Object obj= dialog.getFirstResult();
IPath path= new Path(obj.toString());
if (fIsVariableEntry) {
path= modifyPath(path, currPath.segment(0));
}
return path;
}
} catch (IOException e) {
String title= NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.prefixdialog.error.message", fResolvedFile.getPath()); //$NON-NLS-1$
MessageDialog.openError(getShell(), title, message);
JavaPlugin.log(e);
}
}
return null;
}
/*
* Opens a dialog to choose a root in the file system.
*/
private URL chooseJavaDocLocation() {
String initPath= ""; //$NON-NLS-1$
if (fJavaDocLocation != null && "file".equals(fJavaDocLocation.getProtocol())) { //$NON-NLS-1$
initPath= (new File(fJavaDocLocation.getFile())).getPath();
}
DirectoryDialog dialog= new DirectoryDialog(getShell());
dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.jdocdialog.text")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.jdocdialog.message")); //$NON-NLS-1$
dialog.setFilterPath(initPath);
String res= dialog.open();
if (res != null) {
try {
return (new File(res)).toURL();
} catch (MalformedURLException e) {
// should not happen
JavaPlugin.log(e);
}
}
return null;
}
private Shell getShell() {
if (fSWTWidget != null) {
return fSWTWidget.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
/**
* Takes a path and replaces the beginning with a variable name
* (if the beginning matches with the variables value)
*/
private IPath modifyPath(IPath path, String varName) {
if (varName == null || path == null) {
return null;
}
if (path.isEmpty()) {
return new Path(varName);
}
IPath varPath= JavaCore.getClasspathVariable(varName);
if (varPath != null) {
if (varPath.isPrefixOf(path)) {
path= path.removeFirstSegments(varPath.segmentCount());
} else {
path= new Path(path.lastSegment());
}
} else {
path= new Path(path.lastSegment());
}
return new Path(varName).append(path);
}
/**
* Creates a runnable that sets the source attachment by modifying the project's classpath.
*/
public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
boolean isExported= fOldEntry != null ? fOldEntry.isExported() : false;
IClasspathEntry newEntry;
if (fIsVariableEntry) {
newEntry= JavaCore.newVariableEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported);
} else {
newEntry= JavaCore.newLibraryEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported);
}
IClasspathEntry[] entries= modifyClasspath(jproject, newEntry, shell);
if (entries != null) {
jproject.setRawClasspath(entries, monitor);
}
IPath path= fJARPath;
if (path != null && fIsVariableEntry) {
path= getResolvedPath(path);
}
if (path != null) {
JavaDocLocations.setJavadocLocation(path, getJavadocLocation());
}
} catch (JavaModelException e) {
throw new InvocationTargetException(e);
}
}
};
}
private IClasspathEntry[] modifyClasspath(IJavaProject jproject, IClasspathEntry newEntry, Shell shell) throws JavaModelException{
IClasspathEntry[] oldClasspath= jproject.getRawClasspath();
int nEntries= oldClasspath.length;
ArrayList newEntries= new ArrayList(nEntries + 1);
int entryKind= newEntry.getEntryKind();
IPath jarPath= newEntry.getPath();
boolean found= false;
for (int i= 0; i < nEntries; i++) {
IClasspathEntry curr= oldClasspath[i];
if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) {
// add modified entry
newEntries.add(newEntry);
found= true;
} else {
newEntries.add(curr);
}
}
if (!found) {
if (newEntry.getSourceAttachmentPath() == null || !putJarOnClasspathDialog(shell)) {
return null;
}
// add new
newEntries.add(newEntry);
}
return (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]);
}
private boolean putJarOnClasspathDialog(Shell shell) {
final boolean[] result= new boolean[1];
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.message"); //$NON-NLS-1$
result[0]= MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
});
return result[0];
}
}
|
11,763 |
Bug 11763 Renaming a project automatically updates the build class paths
|
Updatig the build class path is goodness but it should not always happen automatically. We should offer the user an option to not do the update. Same is true when renaming folders.
|
resolved fixed
|
db9f5e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T16:18:35Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/ui
| |
11,763 |
Bug 11763 Renaming a project automatically updates the build class paths
|
Updatig the build class path is goodness but it should not always happen automatically. We should offer the user an option to not do the update. Same is true when renaming folders.
|
resolved fixed
|
db9f5e6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-21T16:18:35Z | 2002-03-20T10:26:40Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/actions/RefactoringStarter.java
| |
12,096 |
Bug 12096 Extract local variable show preview of type and name
| null |
resolved fixed
|
4c02f7d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T12:50:29Z | 2002-03-22T09:40:00Z |
org.eclipse.jdt.ui/ui
| |
12,096 |
Bug 12096 Extract local variable show preview of type and name
| null |
resolved fixed
|
4c02f7d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T12:50:29Z | 2002-03-22T09:40:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractTempInputPage.java
| |
11,786 |
Bug 11786 clipboard based copying of java resources - bad copy of package name
|
1) Copy and paste 'junit.ui'. 2) Observe: the resulting package is named 'ui'. It should be something like 'copy.of.junit.ui' or 'junit.ui.copy.of'. Also compile errors are introduced as the CUs still expect the package name to be 'junit.ui'. 3) Paste again. There's a new folder (not package) called 'Copy of ui'. It should remain a package and have package-like names.
|
resolved fixed
|
5c263b3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:01:24Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/core
| |
11,786 |
Bug 11786 clipboard based copying of java resources - bad copy of package name
|
1) Copy and paste 'junit.ui'. 2) Observe: the resulting package is named 'ui'. It should be something like 'copy.of.junit.ui' or 'junit.ui.copy.of'. Also compile errors are introduced as the CUs still expect the package name to be 'junit.ui'. 3) Paste again. There's a new folder (not package) called 'Copy of ui'. It should remain a package and have package-like names.
|
resolved fixed
|
5c263b3
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:01:24Z | 2002-03-20T10:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/CopyRefactoring.java
| |
12,104 |
Bug 12104 modify parameters: not allowed on some constructors
|
public class A extends Error{ A(String s){} }
|
resolved fixed
|
60755fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:37:49Z | 2002-03-22T12:26:40Z |
org.eclipse.jdt.ui/core
| |
12,104 |
Bug 12104 modify parameters: not allowed on some constructors
|
public class A extends Error{ A(String s){} }
|
resolved fixed
|
60755fb
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:37:49Z | 2002-03-22T12:26:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ReorderParametersRefactoring.java
| |
11,795 |
Bug 11795 java browsing: members type shows imports strangely
|
give this code: package p; import java.util.List; public class A { class D{ } } i see the import container as a child of both A and D strange
|
resolved fixed
|
7ec8f37
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:53:28Z | 2002-03-20T10:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaElementContentProvider.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.viewers.AbstractTreeViewer;
import org.eclipse.jface.viewers.IBasicPropertyConstants;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
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.IImportContainer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaElementDelta;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IParent;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.IWorkingCopy;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
class JavaElementContentProvider extends BaseJavaElementContentProvider implements IElementChangedListener {
private StructuredViewer fViewer;
private Object fInput;
private JavaBrowsingPart fBrowsingPart;
public JavaElementContentProvider(boolean provideMembers, JavaBrowsingPart browsingPart) {
super(provideMembers, false);
fBrowsingPart= browsingPart;
fViewer= fBrowsingPart.getViewer();
JavaCore.addElementChangedListener(this);
}
public Object[] getChildren(Object element) {
if (!exists(element))
return NO_CHILDREN;
try {
if (element instanceof Collection) {
Collection elements= (Collection)element;
if (elements.isEmpty())
return NO_CHILDREN;
Object[] result= new Object[0];
Iterator iter= ((Collection)element).iterator();
while (iter.hasNext()) {
Object[] children= getChildren(iter.next());
if (children != NO_CHILDREN)
result= concatenate(result, children);
}
return result;
}
if (element instanceof IPackageFragment)
return getPackageContents((IPackageFragment)element);
if (fProvideMembers && element instanceof IType)
return withImportAndPackageDeclarations((IType)element);
if (fProvideMembers && element instanceof ISourceReference && element instanceof IParent)
return removeImportAndPackageDeclarations(super.getChildren(element));
if (element instanceof IJavaProject)
return getPackageFragmentRoots((IJavaProject)element);
return super.getChildren(element);
} catch (JavaModelException e) {
return NO_CHILDREN;
}
}
private Object[] getPackageContents(IPackageFragment fragment) throws JavaModelException {
ISourceReference[] sourceRefs;
if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
sourceRefs= fragment.getCompilationUnits();
if (getProvideWorkingCopy()) {
for (int i= 0; i < sourceRefs.length; i++) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)sourceRefs[i]);
if (wc != null)
sourceRefs[i]= (ICompilationUnit)wc;
}
}
}
else {
IClassFile[] classFiles= fragment.getClassFiles();
List topLevelClassFile= new ArrayList();
for (int i= 0; i < classFiles.length; i++) {
IType type= classFiles[i].getType();
if (type != null && type.getDeclaringType() == null)
topLevelClassFile.add(classFiles[i]);
}
sourceRefs= (ISourceReference[])topLevelClassFile.toArray(new ISourceReference[topLevelClassFile.size()]);
}
Object[] result= new Object[0];
for (int i= 0; i < sourceRefs.length; i++)
result= concatenate(result, removeImportAndPackageDeclarations(getChildren(sourceRefs[i])));
return concatenate(result, fragment.getNonJavaResources());
}
private Object[] removeImportAndPackageDeclarations(Object[] members) {
ArrayList tempResult= new ArrayList(members.length);
for (int i= 0; i < members.length; i++)
if (!(members[i] instanceof IImportContainer) && !(members[i] instanceof IPackageDeclaration))
tempResult.add(members[i]);
return tempResult.toArray();
}
private Object[] withImportAndPackageDeclarations(IType type) throws JavaModelException{
IParent parent;
if (type.isBinary())
parent= type.getClassFile();
else {
parent= type.getCompilationUnit();
if (getProvideWorkingCopy()) {
IWorkingCopy wc= EditorUtility.getWorkingCopy((ICompilationUnit)parent);
if (wc != null) {
parent= (IParent)wc;
IMember wcType= EditorUtility.getWorkingCopy(type);
if (wcType != null)
type= (IType)wcType;
}
}
}
IJavaElement[] members= parent.getChildren();
ArrayList tempResult= new ArrayList(members.length);
for (int i= 0; i < members.length; i++)
if ((members[i] instanceof IImportContainer))
tempResult.add(members[i]);
tempResult.addAll(Arrays.asList(type.getChildren()));
return tempResult.toArray();
}
private Object[] getPackageFragmentRoots(IJavaProject project) throws JavaModelException {
if (!project.getProject().isOpen())
return NO_CHILDREN;
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
List list= new ArrayList(roots.length);
// filter out package fragments that correspond to projects and
// replace them with the package fragments directly
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= (IPackageFragmentRoot)roots[i];
if (!root.isExternal()) {
Object[] children= root.getChildren();
for (int k= 0; k < children.length; k++)
list.add(children[k]);
}
else if (hasChildren(root)) {
list.add(root);
}
}
return concatenate(list.toArray(), project.getNonJavaResources());
}
// ---------------- Element change handling
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
super.inputChanged(viewer, oldInput, newInput);
if (newInput instanceof Collection) {
// Get a template object from the collection
Collection col= (Collection)newInput;
if (!col.isEmpty())
newInput= col.iterator().next();
else
newInput= null;
}
fInput= newInput;
}
/* (non-Javadoc)
* Method declared on IContentProvider.
*/
public void dispose() {
super.dispose();
JavaCore.removeElementChangedListener(this);
}
/* (non-Javadoc)
* Method declared on IElementChangedListener.
*/
public void elementChanged(final ElementChangedEvent event) {
try {
processDelta(event.getDelta());
} catch(JavaModelException e) {
JavaPlugin.getDefault().log(e.getStatus()); //$NON-NLS-1$
}
}
/**
* Processes a delta recursively. When more than two children are affected the
* tree is fully refreshed starting at this node. The delta is processed in the
* current thread but the viewer updates are posted to the UI thread.
*/
protected void processDelta(IJavaElementDelta delta) throws JavaModelException {
int kind= delta.getKind();
int flags= delta.getFlags();
IJavaElement element= delta.getElement();
if (!getProvideWorkingCopy() && element instanceof IWorkingCopy && ((IWorkingCopy)element).isWorkingCopy()) {
return;
}
// handle open and closing of a solution or project
if (((flags & IJavaElementDelta.F_CLOSED) != 0) || ((flags & IJavaElementDelta.F_OPENED) != 0)) {
postRefresh(element);
return;
}
if (kind == IJavaElementDelta.REMOVED) {
Object parent= internalGetParent(element);
if (fBrowsingPart.isValidElement(element)) {
if (element instanceof IClassFile) {
postRemove(((IClassFile)element).getType());
} else if (element instanceof ICompilationUnit && !((ICompilationUnit)element).isWorkingCopy()) {
if (!getProvideWorkingCopy())
postRefresh(null);
} else if (parent instanceof ICompilationUnit && getProvideWorkingCopy() && !((ICompilationUnit)parent).isWorkingCopy()) {
// do nothing
} else
postRemove(element);
}
if (fBrowsingPart.isAncestorOf(element, fInput))
postAdjustInputAndSetSelection(null);
return;
}
if (kind == IJavaElementDelta.ADDED) {
if (fBrowsingPart.isValidElement(element)) {
Object parent= internalGetParent(element);
if (element instanceof IClassFile) {
postAdd(parent, ((IClassFile)element).getType());
} else if (element instanceof ICompilationUnit && !((ICompilationUnit)element).isWorkingCopy()) {
if (!getProvideWorkingCopy())
postAdd(parent, ((ICompilationUnit)element).getAllTypes());
} else if (parent instanceof ICompilationUnit && getProvideWorkingCopy() && !((ICompilationUnit)parent).isWorkingCopy()) {
// do nothing
} else
postAdd(parent, element);
} else if (fInput == null) {
IJavaElement newInput= fBrowsingPart.findInputForJavaElement(element);
if (newInput != null)
postAdjustInputAndSetSelection(element);
}
return;
}
if (element instanceof IType && fBrowsingPart.isValidInput(element))
postRefresh(null);
if (isClassPathChange(delta))
// throw the towel and do a full refresh
postRefresh(null);
IJavaElementDelta[] affectedChildren= delta.getAffectedChildren();
if (affectedChildren.length > 1) {
// a package fragment might become non empty refresh from the parent
if (element instanceof IPackageFragment) {
IJavaElement parent= (IJavaElement)internalGetParent(element);
// avoid posting a refresh to an unvisible parent
if (element.equals(fInput)) {
postRefresh(element);
} else {
postRefresh(parent);
}
}
// more than one child changed, refresh from here downwards
if (element instanceof IPackageFragmentRoot && fBrowsingPart.isValidElement(element)) {
postRefresh(skipProjectPackageFragmentRoot((IPackageFragmentRoot)element));
return;
}
}
for (int i= 0; i < affectedChildren.length; i++) {
processDelta(affectedChildren[i]);
}
}
/**
* Updates the package icon
*/
private void updatePackageIcon(final IJavaElement element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.update(element, new String[]{IBasicPropertyConstants.P_IMAGE});
}
});
}
private void postRefresh(final Object root) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed())
fViewer.refresh(root);
}
});
}
private void postAdd(final Object parent, final Object element) {
postAdd(parent, new Object[] {element});
}
private void postAdd(final Object parent, final Object[] elements) {
if (elements.length <= 0)
return;
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
if (fViewer instanceof AbstractTreeViewer) {
if (fViewer.testFindItem(parent) == null) {
Object root= ((AbstractTreeViewer)fViewer).getInput();
if (root != null)
((AbstractTreeViewer)fViewer).add(root, elements);
}
else
((AbstractTreeViewer)fViewer).add(parent, elements);
}
else if (fViewer instanceof ListViewer)
((ListViewer)fViewer).add(elements);
else if (fViewer instanceof TableViewer)
((TableViewer)fViewer).add(elements);
if (fViewer.testFindItem(elements[0]) != null)
fBrowsingPart.adjustInputAndSetSelection((IJavaElement)elements[0]);
ctrl.setRedraw(true);
}
}
});
}
private void postRemove(final Object element) {
postRemove(new Object[] {element});
}
private void postRemove(final Object[] elements) {
if (elements.length <= 0)
return;
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
if (fViewer instanceof AbstractTreeViewer)
((AbstractTreeViewer)fViewer).remove(elements);
else if (fViewer instanceof ListViewer)
((ListViewer)fViewer).remove(elements);
else if (fViewer instanceof TableViewer)
((TableViewer)fViewer).remove(elements);
ctrl.setRedraw(true);
}
}
});
}
private void postAdjustInputAndSetSelection(final Object element) {
postRunnable(new Runnable() {
public void run() {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.setRedraw(false);
fBrowsingPart.adjustInputAndSetSelection((IJavaElement)element);
ctrl.setRedraw(true);
}
}
});
}
private void postRunnable(final Runnable r) {
Control ctrl= fViewer.getControl();
if (ctrl != null && !ctrl.isDisposed()) {
ctrl.getDisplay().asyncExec(r);
}
}
}
|
12,053 |
Bug 12053 Allow mutli selection for all browsers
|
This should clear downstream
|
resolved fixed
|
740a438
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:59:40Z | 2002-03-21T17:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.Collection;
import java.util.Comparator;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
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.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.NewWizardMenu;
import org.eclipse.ui.actions.OpenPerspectiveMenu;
import org.eclipse.ui.actions.OpenWithMenu;
import org.eclipse.ui.actions.RefreshAction;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.views.internal.framelist.BackAction;
import org.eclipse.ui.views.internal.framelist.ForwardAction;
import org.eclipse.ui.views.internal.framelist.GoIntoAction;
import org.eclipse.ui.views.internal.framelist.UpAction;
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.IWorkingCopy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.core.JavaElement;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ContextMenuGroup;
import org.eclipse.jdt.internal.ui.actions.GenerateGroup;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
import org.eclipse.jdt.internal.ui.packageview.BuildGroup;
import org.eclipse.jdt.internal.ui.packageview.OpenResourceAction;
import org.eclipse.jdt.internal.ui.packageview.PackagesMessages;
import org.eclipse.jdt.internal.ui.packageview.ShowInNavigatorAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.IRefactoringAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringGroup;
import org.eclipse.jdt.internal.ui.reorg.ReorgGroup;
import org.eclipse.jdt.internal.ui.search.JavaSearchGroup;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.util.OpenTypeHierarchyUtil;
import org.eclipse.jdt.internal.ui.viewsupport.BaseJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.viewsupport.IProblemChangedListener;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StandardJavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener {
private ILabelProvider fLabelProvider;
private ILabelProvider fTitleProvider;
private StructuredViewer fViewer;
private IMemento fMemento;
private JavaElementTypeComparator fTypeComparator;
// Actions
private ContextMenuGroup[] fStandardGroups;
private Menu fContextMenu;
private OpenResourceAction fOpenCUAction;
private Action fOpenToAction;
private Action fShowNavigatorAction;
private PropertyDialogAction fPropertyDialogAction;
private IRefactoringAction fDeleteAction;
private RefreshAction fRefreshAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private GoIntoAction fZoomInAction;
private UpAction fUpAction;
// private GotoTypeAction fGotoTypeAction;
// private GotoPackageAction fGotoPackageAction;
private IWorkbenchPart fPreviousSelectionProvider;
private Image fOriginalTitleImage;
/*
* Ensure selection changed events being processed only if
* initiated by user interaction with this part.
*/
private boolean fProcessSelectionEvents= true;
private IPartListener fPartListener= new IPartListener() {
public void partActivated(IWorkbenchPart part) {
setSelectionFromEditor(part);
}
public void partBroughtToTop(IWorkbenchPart part) {
}
public void partClosed(IWorkbenchPart part) {
}
public void partDeactivated(IWorkbenchPart part) {
}
public void partOpened(IWorkbenchPart part) {
}
};
/*
* Implements method from IViewPart.
*/
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
fMemento= memento;
}
/*
* Implements method from IViewPart.
*/
public void saveState(IMemento memento) {
if (fViewer == null) {
// part has not been created
if (fMemento != null) //Keep the old state;
memento.putMemento(fMemento);
return;
}
// XXX: need to save state here
// fViewer.saveState(memento);
}
/**
* Creates the search list inner viewer.
*/
public void createPartControl(Composite parent) {
Assert.isTrue(fViewer == null);
if (fMemento != null)
// XXX: Restore state here
// fViewer.restoreState(fMemento);
fMemento= null;
fTypeComparator= new JavaElementTypeComparator();
// Setup viewer
fViewer= createViewer(parent);
fLabelProvider= createLabelProvider();
ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager();
fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr));
fViewer.setSorter(new JavaElementSorter());
fViewer.setUseHashlookup(true);
JavaPlugin.getDefault().getProblemMarkerManager().addListener((IProblemChangedListener)fViewer);
fTitleProvider= createTitleProvider();
MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
menuMgr.addMenuListener(this);
fContextMenu= menuMgr.createContextMenu(fViewer.getControl());
fViewer.getControl().setMenu(fContextMenu);
getSite().registerContextMenu(menuMgr, fViewer);
createActions(); // call before registering for selection changes
addKeyListener();
getSite().setSelectionProvider(fViewer);
// Status line
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager));
hookViewerListeners();
// Initialize viewer input
fViewer.setContentProvider(createContentProvider());
setInitialInput();
// Initialize selecton
setInitialSelection();
// Filters
addFilters();
fillToolBar(getViewSite().getActionBars().getToolBarManager());
// Listen to workbench window changes
getViewSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this);
getViewSite().getPage().addPartListener(fPartListener);
setHelp();
}
//---- IWorkbenchPart ------------------------------------------------------
public void setFocus() {
fViewer.getControl().setFocus();
}
public void dispose() {
if (fViewer != null) {
JavaPlugin.getDefault().getProblemMarkerManager().removeListener((IProblemChangedListener)fViewer);
getViewSite().getWorkbenchWindow().getSelectionService().removeSelectionListener(this);
getViewSite().getPage().removePartListener(fPartListener);
fViewer= null;
}
super.dispose();
}
/**
* Adds the KeyListener
*/
protected void addKeyListener() {
fViewer.getControl().addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent event) {
handleKeyReleased(event);
}
});
}
protected void handleKeyReleased(KeyEvent event) {
if (event.stateMask != 0)
return;
int key= event.keyCode;
if (key == SWT.F5) {
fRefreshAction.selectionChanged(
(IStructuredSelection) fViewer.getSelection());
if (fRefreshAction.isEnabled())
fRefreshAction.run();
} else if (key == SWT.F4) {
OpenTypeHierarchyUtil.open(getSelectionProvider().getSelection(), getSite().getWorkbenchWindow());
} else if (key == SWT.F3) {
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
fOpenCUAction.run();
}
else if (event.character == SWT.DEL) {
fDeleteAction.update();
if (fDeleteAction.isEnabled())
fDeleteAction.run();
}
}
//---- Adding Action to Toolbar -------------------------------------------
protected void fillToolBar(IToolBarManager tbm) {
// fViewer.fillToolBar(tbm);
}
// protected void setContextMenuContributor(final IContextMenuContributor contributor) {
// // Make sure we are doing it in the right thread.
// getDisplay().syncExec(new Runnable() {
// public void run() {
//// getViewer().setContextMenuTarget(contributor);
// }
// });
// }
/**
* Called when the context menu is about to open.
* Override to add your own context dependent menu contributions.
*/
public void menuAboutToShow(IMenuManager menu) {
JavaPlugin.createStandardGroups(menu);
IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection();
fPropertyDialogAction.selectionChanged(selection);
MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$
menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu);
new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false);
// updateActions(selection);
// Object element= selection.getFirstElement();
// if (selection.size() == 1 && fViewer.isExpandable(element))
// menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
// addGotoMenu(menu);
//
// Open menus
fOpenCUAction.update();
if (fOpenCUAction.isEnabled())
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, fOpenCUAction);
addOpenWithMenu(menu, selection);
addOpenToMenu(menu, selection);
addRefactoring(menu);
ContextMenuGroup.add(menu, fStandardGroups, fViewer);
menu.appendToGroup(IContextMenuConstants.GROUP_BUILD, fRefreshAction);
fRefreshAction.selectionChanged(selection);
menu.add(new Separator());
if (fPropertyDialogAction.isApplicableForSelection())
menu.appendToGroup(IContextMenuConstants.GROUP_PROPERTIES, fPropertyDialogAction);
}
private void addRefactoring(IMenuManager menu){
MenuManager refactoring= new MenuManager(PackagesMessages.getString("PackageExplorer.refactoringTitle")); //$NON-NLS-1$
ContextMenuGroup.add(refactoring, new ContextMenuGroup[] { new RefactoringGroup() }, fViewer);
if (!refactoring.isEmpty())
menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, refactoring);
}
private void createActions() {
ISelectionProvider provider= getSelectionProvider();
fOpenCUAction= new OpenResourceAction(provider);
fPropertyDialogAction= new PropertyDialogAction(getShell(), provider);
fShowNavigatorAction= new ShowInNavigatorAction(provider);
fStandardGroups= new ContextMenuGroup[] {
new BuildGroup(),
new ReorgGroup(),
new GenerateGroup(),
new JavaSearchGroup()
};
fDeleteAction= ReorgGroup.createDeleteAction(provider);
fRefreshAction= new RefreshAction(getShell());
// fFilterAction = new FilterSelectionAction(getShell(), this, PackagesMessages.getString("PackageExplorer.filters")); //$NON-NLS-1$
// fShowLibrariesAction = new ShowLibrariesAction(this, PackagesMessages.getString("PackageExplorer.referencedLibs")); //$NON-NLS-1$
// fShowBinariesAction = new ShowBinariesAction(getShell(), this, PackagesMessages.getString("PackageExplorer.binaryProjects")); //$NON-NLS-1$
// fFilterWorkingSetAction = new FilterWorkingSetAction(getShell(), this, "Filter Working Set..."); //$NON-NLS-1$
// fRemoveWorkingSetAction = new RemoveWorkingSetFilterAction(getShell(), this, "Remove Working Set Filter"); //$NON-NLS-1$
// fBackAction= new BackAction(fFrameList);
// fForwardAction= new ForwardAction(fFrameList);
// fZoomInAction= new GoIntoAction(fFrameList);
// fUpAction= new UpAction(fFrameList);
// fGotoTypeAction= new GotoTypeAction(this);
// fGotoPackageAction= new GotoPackageAction(this);
IActionBars actionService= getViewSite().getActionBars();
actionService.setGlobalActionHandler(IWorkbenchActionConstants.DELETE, fDeleteAction);
ReorgGroup.addGlobalReorgActions(actionService, provider);
}
private void addOpenToMenu(IMenuManager menu, IStructuredSelection selection) {
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable) selection.getFirstElement();
IResource resource= (IResource)element.getAdapter(IResource.class);
if ((resource instanceof IContainer)) {
// Create a menu flyout.
MenuManager submenu = new MenuManager(PackagesMessages.getString("PackageExplorer.openPerspective")); //$NON-NLS-1$
submenu.add(new OpenPerspectiveMenu(getSite().getWorkbenchWindow(), resource));
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
OpenTypeHierarchyUtil.addToMenu(getSite().getWorkbenchWindow(), menu, element);
}
private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) {
// If one file is selected get it.
// Otherwise, do not show the "open with" menu.
if (selection.size() != 1)
return;
IAdaptable element= (IAdaptable)selection.getFirstElement();
Object resource= element.getAdapter(IResource.class);
if (!(resource instanceof IFile))
return;
// Create a menu flyout.
MenuManager submenu= new MenuManager(PackagesMessages.getString("PackageExplorer.openWith")); //$NON-NLS-1$
submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource));
// Add the submenu.
menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
private Shell getShell() {
return fViewer.getControl().getShell();
}
protected final Display getDisplay() {
return fViewer.getControl().getDisplay();
}
/**
* Returns the selection provider.
*/
private ISelectionProvider getSelectionProvider() {
return fViewer;
}
/**
* 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
*/
abstract protected boolean isValidInput(Object element);
/**
* 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 == null)
return false;
element= getSuitableJavaElement(element);
if (element == null)
return false;
Object input= getViewer().getInput();
if (input == null)
return false;
if (input instanceof Collection)
return ((Collection)input).contains(element);
else
return input.equals(element);
}
private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) {
if (newInput == null)
return part == fPreviousSelectionProvider;
if (input instanceof IJavaElement && newInput instanceof IJavaElement)
return getTypeComparator().compare(newInput, input) > 0;
else
return false;
}
protected boolean isAncestorOf(Object ancestor, Object element) {
if (element instanceof IJavaElement && ancestor instanceof IJavaElement)
return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element);
return false;
}
private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) {
if (element != null)
return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent());
else
return false;
}
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (!fProcessSelectionEvents || part == this || !(selection instanceof IStructuredSelection))
return;
if (selection.isEmpty() && part instanceof JavaBrowsingPart && !(part instanceof ProjectsView))
return;
// Set input
Object newInput= getElementFromSingleSelection(selection);
Object currentInput= (IJavaElement)getViewer().getInput();
if (newInput != null && newInput.equals(currentInput)) {
IJavaElement elementToSelect= findElementToSelect(getElementFromSingleSelection(selection));
if (elementToSelect != null && getTypeComparator().compare(newInput, elementToSelect) < 0)
setSelection(new StructuredSelection(elementToSelect), true);
fPreviousSelectionProvider= part;
return;
}
// Clear input if needed
if (part != fPreviousSelectionProvider && newInput != null && !newInput.equals(currentInput) && isInputResetBy(newInput, currentInput, part)) {
if (!isAncestorOf(newInput, currentInput))
setInput(null);
fPreviousSelectionProvider= part;
return;
} else if (newInput == null && part == fPreviousSelectionProvider) {
setInput(null);
fPreviousSelectionProvider= part;
return;
}
fPreviousSelectionProvider= part;
// Set selection
if (newInput instanceof IJavaElement)
adjustInputAndSetSelection((IJavaElement)newInput);
else
setSelection(StructuredSelection.EMPTY, true);
}
protected void setInput(Object input) {
if (input == null)
setTitleImage(fOriginalTitleImage);
else if (input instanceof Collection) {
if (((Collection)input).isEmpty())
setTitleImage(fOriginalTitleImage);
else {
Object firstElement= ((Collection)input).iterator().next();
setTitleImage(fTitleProvider.getImage(firstElement));
}
} else
setTitleImage(fTitleProvider.getImage(input));
setViewerInput(input);
}
private void setViewerInput(Object input) {
fProcessSelectionEvents= false;
fViewer.setInput(input);
fProcessSelectionEvents= true;
}
/**
* Sets or clears the title image of this part and
* store the orignal image on the first call.
*/
protected void setTitleImage(Image titleImage) {
if (fOriginalTitleImage == null)
fOriginalTitleImage= getTitleImage();
if (titleImage == null)
titleImage= fOriginalTitleImage;
super.setTitleImage(titleImage);
}
protected final StructuredViewer getViewer() {
return fViewer;
}
protected ILabelProvider createLabelProvider() {
return new StandardJavaUILabelProvider(
StandardJavaUILabelProvider.DEFAULT_TEXTFLAGS,
StandardJavaUILabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS,
StandardJavaUILabelProvider.getAdornmentProviders(true, null)
);
}
protected ILabelProvider createTitleProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS);
}
protected final ILabelProvider getLabelProvider() {
return fLabelProvider;
}
protected final ILabelProvider getTitleProvider() {
return fTitleProvider;
}
/**
* Creates the the viewer of this part.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
return new ProblemTableViewer(parent, SWT.SINGLE);
}
protected int getLabelProviderFlags() {
return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS |
JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS;
}
/**
* Adds filters the viewer of this part.
*/
protected void addFilters() {
// default is to have no filters
}
/**
* Creates the the content provider of this part.
*/
protected BaseJavaElementContentProvider createContentProvider() {
return new JavaElementContentProvider(true, this); //
}
protected void setInitialInput() {
// Use the selection, if any
ISelection selection= getSite().getPage().getSelection();
Object input= getElementFromSingleSelection(selection);
if (!(input instanceof IJavaElement)) {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement) && input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
}
setInput(findInputForJavaElement((JavaElement)input));
}
protected void setInitialSelection() {
// Use the selection, if any
Object input;
ISelection selection= getSite().getPage().getSelection();
if (selection != null && !selection.isEmpty())
input= getElementFromSingleSelection(selection);
else {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement) && input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
else
return;
}
if (findElementToSelect((IJavaElement)input) != null)
adjustInputAndSetSelection((IJavaElement)input);
}
final protected void setHelp() {
JavaUIHelp.setHelp(fViewer, getHelpContextId());
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
abstract protected String getHelpContextId();
/**
* Adds additional listeners to this view.
*/
protected void hookViewerListeners() {
fViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
if (!fProcessSelectionEvents)
return;
if (JavaBrowsingPreferencePage.openEditorOnSingleClick())
new ShowInEditorAction().run(event.getSelection(), getSite().getPage());
else
linkToEditor((IStructuredSelection)event.getSelection());
}
});
fViewer.addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
if (fProcessSelectionEvents && !JavaBrowsingPreferencePage.openEditorOnSingleClick())
new ShowInEditorAction().run(event.getSelection(), getSite().getPage());
}
});
}
void adjustInputAndSetSelection(IJavaElement je) {
je= getSuitableJavaElement(je);
IJavaElement elementToSelect= findElementToSelect(je);
IJavaElement newInput= findInputForJavaElement(je);
if (elementToSelect == null && !isValidInput(newInput))
// Clear input
setInput(null);
else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null)
// Adjust input to selection
setInput(findInputForJavaElement(je));
if (elementToSelect != null)
setSelection(new StructuredSelection(elementToSelect), true);
else
setSelection(StructuredSelection.EMPTY, true);
}
/**
* 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)
return null;
if (isValidInput(je))
return je;
return findInputForJavaElement(je.getParent());
}
final protected IJavaElement findElementToSelect(Object obj) {
if (obj instanceof IJavaElement)
return findElementToSelect((IJavaElement)obj);
return null;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
abstract protected IJavaElement findElementToSelect(IJavaElement je);
private Object getElementFromSingleSelection(ISelection selection) {
if (selection instanceof StructuredSelection
&& ((StructuredSelection)selection).size() == 1)
return ((StructuredSelection)selection).getFirstElement();
return null;
}
/**
* Gets the typeComparator.
* @return Returns a JavaElementTypeComparator
*/
protected Comparator getTypeComparator() {
return fTypeComparator;
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
if (selection == null || selection.isEmpty())
return;
Object obj= selection.getFirstElement();
Object element= null;
if (selection.size() == 1) {
if (obj instanceof IJavaElement) {
IJavaElement cu= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.COMPILATION_UNIT);
if (cu != null)
element= getResourceFor(cu);
if (element == null)
element= JavaModelUtil.findElementOfKind((IJavaElement)obj, IJavaElement.CLASS_FILE);
}
else if (obj instanceof IFile)
element= obj;
if (element == null)
return;
IWorkbenchPage page= getSite().getPage();
IEditorPart editorArray[]= page.getEditors();
for (int i= 0; i < editorArray.length; ++i) {
IEditorPart editor= editorArray[i];
Object input= getElementOfInput(editor.getEditorInput());
if (input != null && input.equals(element)) {
page.bringToTop(editor);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(editor, (IJavaElement) obj);
return;
}
}
}
}
private void setSelectionFromEditor(IWorkbenchPart part) {
if (part == null)
return;
IWorkbenchPartSite site= part.getSite();
if (site == null)
return;
ISelectionProvider provider= site.getSelectionProvider();
if (provider != null)
setSelectionFromEditor(part, provider.getSelection());
}
private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) {
if (part instanceof IEditorPart && JavaBrowsingPreferencePage.linkViewSelectionToEditor()) {
IEditorInput ei= ((IEditorPart)part).getEditorInput();
if (selection instanceof ITextSelection) {
int offset= ((ITextSelection)selection).getOffset();
IJavaElement element= getElementForInputAt(ei, offset);
if (element != null) {
adjustInputAndSetSelection(element);
return;
}
}
if (ei instanceof IFileEditorInput) {
IFile file= ((IFileEditorInput)ei).getFile();
IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class);
if (je == null) {
setSelection(null, false);
return;
}
adjustInputAndSetSelection(je);
} else if (ei instanceof IClassFileEditorInput) {
IClassFile cf= ((IClassFileEditorInput)ei).getClassFile();
adjustInputAndSetSelection(cf);
}
return;
}
}
/**
* Returns the element contained in the EditorInput
*/
Object getElementOfInput(IEditorInput input) {
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
else if (input instanceof IFileEditorInput)
return ((IFileEditorInput)input).getFile();
else if (input instanceof JarEntryEditorInput)
return ((JarEntryEditorInput)input).getStorage();
return null;
}
private IResource getResourceFor(Object element) {
if (element instanceof IJavaElement) {
if (element instanceof IWorkingCopy) {
IWorkingCopy wc= (IWorkingCopy)element;
IJavaElement original= wc.getOriginalElement();
if (original != null)
element= original;
}
try {
element= ((IJavaElement)element).getUnderlyingResource();
} catch (JavaModelException e) {
return null;
}
}
if (!(element instanceof IResource) || ((IResource)element).isPhantom()) {
return null;
}
return (IResource)element;
}
private void setSelection(ISelection selection, boolean reveal) {
if (selection != null && selection.equals(fViewer.getSelection()))
return;
fProcessSelectionEvents= false;
fViewer.setSelection(selection, reveal);
fProcessSelectionEvents= true;
}
/**
* Tries to find the given element in a workingcopy.
*/
protected static IJavaElement getWorkingCopy(IJavaElement input) {
try {
if (input instanceof ICompilationUnit)
return EditorUtility.getWorkingCopy((ICompilationUnit)input);
else
return EditorUtility.getWorkingCopy(input, true);
} catch (JavaModelException ex) {
}
return null;
}
/**
* Returns the original element from which the specified working copy
* element was created from. This is a handle only method, the
* returned element may or may not exist.
*
* @param workingCopy the element for which to get the original
* @return the original Java element or <code>null</code> if this is not a working copy element
*/
protected static IJavaElement getOriginal(IJavaElement workingCopy) {
ICompilationUnit cu= getCompilationUnit(workingCopy);
if (cu != null)
return ((IWorkingCopy)cu).getOriginal(workingCopy);
return null;
}
/**
* Returns the compilation unit for the given java element.
*
* @param element the java element whose compilation unit is searched for
* @return the compilation unit of the given java element
*/
protected static ICompilationUnit getCompilationUnit(IJavaElement element) {
if (element == null)
return null;
if (element instanceof IMember)
return ((IMember) element).getCompilationUnit();
int type= element.getElementType();
if (IJavaElement.COMPILATION_UNIT == type)
return (ICompilationUnit) element;
if (IJavaElement.CLASS_FILE == type)
return null;
return getCompilationUnit(element.getParent());
}
/**
* Converts the given Java element to one which is suitable for this
* view. It takes into account wether the view shows working copies or not.
*
* @param element the Java element to be converted
* @return an element suitable for this view
*/
protected IJavaElement getSuitableJavaElement(Object obj) {
if (!(obj instanceof IJavaElement))
return null;
IJavaElement element= (IJavaElement)obj;
if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0)
return element;
if (element.getElementType() == IJavaElement.CLASS_FILE)
return element;
if (((BaseJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy()) {
IJavaElement wc= getWorkingCopy(element);
if (wc != null)
element= wc;
return element;
}
else {
ICompilationUnit cu= getCompilationUnit(element);
if (cu != null && ((IWorkingCopy)cu).isWorkingCopy())
return ((IWorkingCopy)cu).getOriginal(element);
else
return element;
}
}
/**
* @see JavaEditor#getElementAt(int)
*/
protected IJavaElement getElementForInputAt(IEditorInput input, int offset) {
if (input instanceof IClassFileEditorInput) {
try {
return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset);
} catch (JavaModelException ex) {
return null;
}
}
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(input);
if (unit != null)
synchronized (unit) {
try {
unit.reconcile(null);
return unit.getElementAt(offset);
} catch (JavaModelException x) {
}
}
return null;
}
protected IType getTypeForCU(ICompilationUnit cu) {
cu= (ICompilationUnit)getSuitableJavaElement(cu);
// Use primary type if possible
IType primaryType= JavaModelUtil.findPrimaryType(cu);
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;
}
}
}
|
12,102 |
Bug 12102 AddImport in editor does not work for empty selection
|
Code resolve now works in that case and all actions must be adjusted
|
resolved fixed
|
0c19239
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T14:59:41Z | 2002-03-22T12:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
|
package org.eclipse.jdt.internal.ui.javaeditor;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.ErrorDialog;
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.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.ICompilationUnit;
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.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.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
public class AddImportOnSelectionAction extends Action implements IUpdate {
private ITextEditor fEditor;
public AddImportOnSelectionAction(ITextEditor 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);
}
public AddImportOnSelectionAction() {
this(null);
}
public void setContentEditor(ITextEditor editor) {
fEditor= editor;
}
public void update() {
boolean isEnabled= false;
ISelection selection= fEditor.getSelectionProvider().getSelection();
if (selection instanceof ITextSelection) {
isEnabled= (((ITextSelection)selection).getLength() > 0);
}
setEnabled(isEnabled);
}
private ICompilationUnit getCompilationUnit () {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(fEditor.getEditorInput());
}
/**
* @see IAction#actionPerformed
*/
public void run() {
ICompilationUnit cu= getCompilationUnit();
if (cu != null) {
ISelection s= fEditor.getSelectionProvider().getSelection();
IDocument doc= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
ITextSelection selection= (ITextSelection) s;
if (selection.getLength() > 0 && doc != null) {
try {
int selStart= selection.getOffset();
int nameStart= getNameStart(doc, selStart);
int len= selStart - nameStart + selection.getLength();
String name= doc.get(nameStart, len).trim();
String simpleName= Signature.getSimpleName(name);
String containerName= Signature.getQualifier(name);
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());
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) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getTargetException().getMessage()); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled.
}
return;
} catch (CoreException e) {
JavaPlugin.log(e);
ErrorDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null, e.getStatus()); //$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 {
if (pos > 0 && doc.getChar(pos - 1) == '.') {
pos--;
while (pos > 0) {
char ch= doc.getChar(pos - 1);
if (!Character.isJavaIdentifierPart(ch) && 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();
if (containerLen > 0) {
for (int k= 0; k < containerLen; k++) {
if (doc.getChar(nameStart + k) != containerName.charAt(k)) {
return;
}
}
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= (TypeInfo) 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() == dialog.OK) {
return (TypeInfo) dialog.getFirstResult();
}
return null;
}
}
|
12,108 |
Bug 12108 NewTypeWizardPage hard to use in non-existing java project
|
I use the NewTypeWizardPage to create a type in a java project that does not exist. To achieve this, I override methods containerChanged() and packageChanged() with implementations that only return new Status(). Note that hthis class is in an internal package. I would like to validate the package name that the user enters, but for non-existing java projects, packageChanged() always logs the following exception: 4 org.eclipse.jdt.ui 1 Internal Error Java Model Exception: Java Model Status [B does not exist.] Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V org/eclipse/core/runtime/CoreException.<init>(Lorg/eclipse/core/runtime/IStatus;)V org/eclipse/jdt/core/JavaModelException.<init>(Lorg/eclipse/jdt/core/IJavaModelStatus;)V org/eclipse/jdt/internal/core/JavaElement.newNotPresentException()Lorg/eclipse/jdt/core/JavaModelException; org/eclipse/jdt/internal/core/JavaProject.openWhenClosed(Lorg/eclipse/core/runtime/IProgressMonitor;Lorg/eclipse/jdt/core/IBuffer;)V org/eclipse/jdt/internal/core/JavaElement.openHierarchy()V org/eclipse/jdt/internal/core/JavaElement.getElementInfo()Lorg/eclipse/jdt/internal/core/JavaElementInfo; org/eclipse/jdt/internal/core/JavaProject.getJavaProjectElementInfo()Lorg/eclipse/jdt/internal/core/JavaProjectElementInfo; org/eclipse/jdt/internal/core/JavaProject.getOutputLocation()Lorg/eclipse/core/runtime/IPath; org/eclipse/jdt/ui/wizards/NewTypeWizardPage.packageChanged()Lorg/eclipse/core/runtime/IStatus; org/eclipse/jdt/ui/wizards/NewTypeWizardPage.handleFieldChanged(Ljava/lang/String;)V org/eclipse/jdt/ui/wizards/NewContainerWizardPage.containerDialogFieldChanged(Lorg/eclipse/jdt/internal/ui/wizards/dialogfields/DialogField;)V org/eclipse/jdt/ui/wizards/NewContainerWizardPage.access$1(Lorg/eclipse/jdt/ui/wizards/NewContainerWizardPage;Lorg/eclipse/jdt/internal/ui/wizards/dialogfields/DialogField;)V org/eclipse/jdt/ui/wizards/NewContainerWizardPage$ContainerFieldAdapter.dialogFieldChanged(Lorg/eclipse/jdt/internal/ui/wizards/dialogfields/DialogField;)V org/eclipse/jdt/internal/ui/wizards/dialogfields/DialogField.dialogFieldChanged()V org/eclipse/jdt/internal/ui/wizards/dialogfields/StringDialogField.setText(Ljava/lang/String;)V org/eclipse/jdt/ui/wizards/NewContainerWizardPage.setPackageFragmentRoot(Lorg/eclipse/jdt/core/IPackageFragmentRoot;Z)V com/ibm/ive/jxe/newwizards/InnerClassCreationPage.setProject(Lorg/eclipse/jdt/core/IJavaProject;)V com/ibm/ive/midp/wizard/MIDletSuitePage.projectUpdated()V com/ibm/ive/midp/wizard/MIDletSuitePage.access$0(Lcom/ibm/ive/midp/wizard/MIDletSuitePage;)V com/ibm/ive/midp/wizard/MIDletSuitePage$1.modifyText(Lorg/eclipse/swt/events/ModifyEvent;)V org/eclipse/swt/widgets/TypedListener.handleEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/EventTable.sendEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Widget.sendEvent(ILorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Widget.sendEvent(I)V org/eclipse/swt/widgets/Text.wmCommandChild(II)Lorg/eclipse/swt/internal/win32/LRESULT; org/eclipse/swt/widgets/Control.WM_COMMAND(II)Lorg/eclipse/swt/internal/win32/LRESULT; org/eclipse/swt/widgets/Control.windowProc(III)I org/eclipse/swt/widgets/Display.windowProc(IIII)I org/eclipse/swt/internal/win32/OS.CallWindowProcW(IIIII)I org/eclipse/swt/internal/win32/OS.CallWindowProc(IIIII)I org/eclipse/swt/widgets/Text.callWindowProc(III)I org/eclipse/swt/widgets/Control.windowProc(III)I org/eclipse/swt/widgets/Display.windowProc(IIII)I org/eclipse/swt/internal/win32/OS.DispatchMessageW(Lorg/eclipse/swt/internal/win32/MSG;)I org/eclipse/swt/internal/win32/OS.DispatchMessage(Lorg/eclipse/swt/internal/win32/MSG;)I org/eclipse/swt/widgets/Display.readAndDispatch()Z org/eclipse/jface/window/Window.runEventLoop(Lorg/eclipse/swt/widgets/Shell;)V org/eclipse/jface/window/Window.open()I org/eclipse/ui/actions/NewWizardAction.run()V org/eclipse/ui/internal/NewWizardDropDownAction.run()V org/eclipse/jface/action/Action.runWithEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/jface/action/ActionContributionItem.handleWidgetSelection(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/jface/action/ActionContributionItem.handleWidgetEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/jface/action/ActionContributionItem.access$0(Lorg/eclipse/jface/action/ActionContributionItem;Lorg/eclipse/swt/widgets/Event;)V org/eclipse/jface/action/ActionContributionItem$ActionListener.handleEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/EventTable.sendEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Widget.notifyListeners(ILorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Display.runDeferredEvents()Z org/eclipse/swt/widgets/Display.readAndDispatch()Z org/eclipse/ui/internal/Workbench.runEventLoop()V org/eclipse/ui/internal/Workbench.run(Ljava/lang/Object;)Ljava/lang/Object; org/eclipse/core/internal/boot/InternalBootLoader.run(Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run(Ljava/lang/String;Ljava/net/URL;Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/Object; EclipseRuntimeLauncher.main([Ljava/lang/String;)V 4 org.eclipse.jdt.core 969 B does not exist.
|
resolved fixed
|
24b70db
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T16:27:53Z | 2002-03-22T15:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
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.viewers.LabelProvider;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IBuffer;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaModelException;
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.SearchEngine;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.compiler.env.IConstants;
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.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.ElementListSelectionDialog;
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.CodeGenerationPreferencePage;
import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage;
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.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter;
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.ListDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
/**
* <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.
* Applets, Servlets, Classes, Interfaces...
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of NewTypeWizardPage.
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
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;
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 type page with a given
* Java element as selection. To implement a different selection strategy do not call this
* method or overwrite it.
* @param elem The initial selection of this page or null if no
* selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) JavaModelUtil.findElementOfKind(elem, IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) JavaModelUtil.findElementOfKind(elem, IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) JavaModelUtil.findElementOfKind(elem, IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= JavaModelUtil.findPrimaryType(cu);
}
}
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 GridLayout with at least 1 column.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a GridLayout with at least 4 columns.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null));
}
/**
* Creates the controls for the enclosing type name field. Expects a GridLayout with at least 4 columns.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
}
/**
* Creates the controls for the type name field. Expects a GridLayout with at least 2 columns.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons. Expects a GridLayout with at least 3 columns.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field. Expects a GridLayout with at least 3 columns.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the superclass name field. Expects a GridLayout with at least 3 columns.
* @param composite The parent composite
* @param nColumns Number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name.
*/
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(DialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(DialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/**
* Called whenever a content of a field has changed.
* Implementors of NewTypeWizardPage can hook in.
* @see ContainerPage#handleFieldChanged
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Gets the text of package field.
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Gets the text of enclosing type field.
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
* @return Returns <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.
* This will update model and the text of the control.
* @param canBeModified Selects if the package fragment can be changed by the user
*/
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 Returns <code>null</code> if 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.
* This will update model and the text of the control.
* @param canBeModified Selects if the enclosing type can be changed by the user
*/
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 <code>true</code> if the enclosing type selection check box is enabled.
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type selection checkbox.
* @param canBeModified Selects if the enclosing type selection can be changed by the user
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Gets the type name.
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name.
* @param canBeModified Selects if the type name can be changed by the user
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Gets the selected modifiers.
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= IConstants.AccPublic;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= IConstants.AccPrivate;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= IConstants.AccProtected;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= IConstants.AccAbstract;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= IConstants.AccFinal;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= IConstants.AccStatic;
}
return mdf;
}
/**
* Sets the modifiers.
* @param canBeModified Selects if the modifiers can be changed by the user
* @see IConstants
*/
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);
}
/**
* Gets the content of the super class text field.
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
* @param canBeModified Selects if the super class can be changed by the user
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Gets the currently chosen super interfaces.
* @return returns a list of String
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
* @param canBeModified Selects if the modifiers can be changed by the user.
* @param interfacesNames a list of String
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
// ----------- validation ----------
/**
* Called when the package field has changed.
* The method validates the package name and returns the status of the validation
* This also updates the package fragment model.
* Can be extended to add more 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) {
IPackageFragment pack= root.getPackageFragment(packName);
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= pack.getUnderlyingResource().getFullPath();
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= pack;
} 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);
}
/**
* Called when the enclosing type name has changed.
* The method validates the enclosing type and returns the status of the validation
* This also updates the enclosing type model.
* Can be extended to add more 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= JavaModelUtil.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;
}
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;
}
}
/**
* Called when the type name has changed.
* The method validates the type name and returns the status of the validation.
* Can be extended to add more 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.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;
}
/**
* Called when the superclass name has changed.
* The method validates the superclass name and returns the status of the validation.
* Can be extended to add more 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 {
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= JavaModelUtil.findType(jproject, 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= JavaModelUtil.findType(jproject, packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= JavaModelUtil.findType(jproject, "java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= JavaModelUtil.findType(jproject, sclassName);
}
}
return type;
}
/**
* Called when the list of super interface has changed.
* The method validates the superinterfaces and returns the status of the validation.
* Can be extended to add more 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= JavaModelUtil.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;
}
/**
* Called when the modifiers have changed.
* The method validates the modifiers and returns the status of the validation.
* Can be extended to add more 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) {
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);
if (fCurrPackage != null) {
dialog.setInitialSelections(new Object[] { fCurrPackage });
}
if (dialog.open() == dialog.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$
if (fCurrEnclosingType != null) {
dialog.setInitialSelections(new Object[] { fCurrEnclosingType });
dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1));
}
if (dialog.open() == dialog.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$
if (fSuperClass != null) {
dialog.setFilter(fSuperClass.getElementName());
}
if (dialog.open() == dialog.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"));
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates a type using the current field values.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
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;
String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference();
int threshold= ImportOrganizePreferencePage.getImportNumberThreshold();
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n");
String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter;
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", packStatement, false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$
imports= new ImportsStructure(parentCU, prefOrder, threshold, false);
String content= constructTypeStub(imports, lineDelimiter, parentCU);
createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 3));
} 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);
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
String content= constructTypeStub(imports, lineDelimiter, parentCU);
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1));
createTypeMembers(createdType, imports, new SubProgressMonitor(monitor, 1));
// add imports
imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1));
ICompilationUnit cu= createdType.getCompilationUnit();
ISourceRange range;
if (isInnerClass) {
synchronized(cu) {
cu.reconcile(null);
}
range= createdType.getSourceRange();
} else {
range= cu.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);
}
buf.save(new SubProgressMonitor(monitor, 1), false);
} else {
monitor.worked(1);
}
fCreatedType= createdType;
monitor.done();
}
/**
* Returns the created type. Only valid after createType has been invoked
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, IImportsStructure imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
buf.append(Signature.getSimpleName(typename));
if (fSuperClass != null) {
imports.addImport(JavaModelUtil.getFullyQualifiedName(fSuperClass));
} else {
imports.addImport(typename);
}
}
}
private void writeSuperInterfaces(StringBuffer buf, IImportsStructure 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);
imports.addImport(typename);
buf.append(Signature.getSimpleName(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(IImportsStructure imports, String lineDelimiter, ICompilationUnit parentCU) {
StringBuffer buf= new StringBuffer();
String typeComment= getTypeComment(parentCU);
if (typeComment != null && typeComment.length() > 0) {
buf.append(typeComment);
buf.append(lineDelimiter);
}
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();
}
/**
* Called from createType to allow adding methods, fielse, inner types ect for the newly created type.
* Implementors can use the create methods on the new type.
* Formatting will be applied to the content by the createType
* @param newType The new type to add members to
* @param imports To add the needed imports to.
* @param monitor Progress monitor
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
// default implementation does nothing
// example would be
// String mainMathod= "public static void main(String[]) {}"
// createdType.createMethod(main, null, false, null);
}
/**
* Called from createType to get a file comment. By default the content of template
* 'filecomment' is taken.
* Returns source or null, if no file comment should be added
*/
protected String getFileComment(ICompilationUnit parentCU) {
if (CodeGenerationPreferencePage.doFileComments()) {
return getTemplate("filecomment", parentCU);
}
return null;
}
/**
* Called from createType to get a type comment.
* Returns source or null, if no type comment should be added
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (CodeGenerationPreferencePage.doCreateComments()) {
return getTemplate("typecomment", parentCU);
}
return null;
}
/**
* Gets the template of the given name, evaluated in the context of a CU.
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
Template[] templates= Templates.getInstance().getTemplates();
try {
for (int i= 0; i < templates.length; i++) {
if (name.equals(templates[i].getName())) {
return JavaContext.evaluateTemplate(templates[i], parentCU);
}
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* Creates the bodies of all unimplemented methods or/and all constructors and adds them to the type
* Can be used by implementors of NewTypeWizardPage to add method stub checkboxes.
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
List newMethods= new ArrayList();
ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
if (doConstructors) {
IType superclass= hierarchy.getSuperclass(type);
if (superclass != null) {
String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports);
if (constructors != null) {
for (int i= 0; i < constructors.length; i++) {
newMethods.add(constructors[i]);
}
}
}
}
if (doUnimplementedMethods) {
String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports);
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++) {
createdMethods[i]= type.createMethod((String) newMethods.get(i), null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns a runnable that creates a type using the current settings.
*/
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);
}
}
};
}
}
|
8,166 |
Bug 8166 nls: 'find string' dialog needs a button to open nls wizard
|
The compilation units which have no strings to externalize are of no interest. They should be removed from the table. Otherwise, the action should be called 'Count Strings to Externalize...'.
|
verified fixed
|
761427a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T18:31:55Z | 2002-01-23T15:33:20Z |
org.eclipse.jdt.ui/ui
| |
8,166 |
Bug 8166 nls: 'find string' dialog needs a button to open nls wizard
|
The compilation units which have no strings to externalize are of no interest. They should be removed from the table. Otherwise, the action should be called 'Count Strings to Externalize...'.
|
verified fixed
|
761427a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T18:31:55Z | 2002-01-23T15:33:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/FindStringsAction.java
| |
11,833 |
Bug 11833 NegativeArraySizeException in code formatter/style pref page
|
20020319 enter -1 as number of spaces representing a tab java.lang.NegativeArraySizeException at java.lang.StringBuffer.<init>(StringBuffer.java(Compiled Code)) at org.eclipse.swt.custom.StyledText.calculateTabWidth (StyledText.java:1386) at org.eclipse.swt.custom.StyledText.setTabs(StyledText.java:7293) at org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage.textChanged (CodeFormatterPreferencePage.java:408) at org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage.access$1 (CodeFormatterPreferencePage.java:400) at org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage$2.modifyText (CodeFormatterPreferencePage.java:218) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:179) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Text.wmCommandChild(Text.java:1751) at org.eclipse.swt.widgets.Control.WM_COMMAND(Control.java:2786) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.CallWindowProcW(Native Method) at org.eclipse.swt.internal.win32.OS.CallWindowProc(OS.java(Compiled Code)) at org.eclipse.swt.widgets.Text.callWindowProc(Text.java:85) at org.eclipse.swt.widgets.Control.windowProc(Control.java(Compiled Code)) at org.eclipse.swt.widgets.Display.windowProc(Display.java(Compiled Code)) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java(Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.jface.window.Window.runEventLoop(Window.java(Compiled Code)) at org.eclipse.jface.window.Window.open(Window.java:525) at org.eclipse.ui.internal.OpenPreferencesAction.run (OpenPreferencesAction.java:47) at org.eclipse.jface.action.Action.runWithEvent(Action.java:473) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:361) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:352) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:47) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:698) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:777) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:319) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:196) at org.eclipse.core.launcher.Main.run(Main.java:555) at org.eclipse.core.launcher.Main.main(Main.java:396)
|
resolved fixed
|
255c5b9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T19:26:01Z | 2002-03-20T13:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CodeFormatterPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
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.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.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.core.runtime.IStatus;
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.source.SourceViewer;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.ui.help.DialogPageContextComputer;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.formatter.CodeFormatter;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.TabFolderLayout;
/*
* The page for setting code formatter options
*/
public class CodeFormatterPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
// Preference store keys, see JavaCore.getOptions
private static final String PREF_NEWLINE_OPENING_BRACES= "org.eclipse.jdt.core.formatter.newline.openingBrace";
private static final String PREF_NEWLINE_CONTROL_STATEMENT= "org.eclipse.jdt.core.formatter.newline.controlStatement";
private static final String PREF_NEWLINE_CLEAR_ALL= "org.eclipse.jdt.core.formatter.newline.clearAll";
private static final String PREF_NEWLINE_ELSE_IF= "org.eclipse.jdt.core.formatter.newline.elseIf";
private static final String PREF_NEWLINE_EMPTY_BLOCK= "org.eclipse.jdt.core.formatter.newline.emptyBlock";
private static final String PREF_LINE_SPLIT= "org.eclipse.jdt.core.formatter.lineSplit";
private static final String PREF_STYLE_COMPACT_ASSIGNEMENT= "org.eclipse.jdt.core.formatter.style.assignment";
private static final String PREF_TAB_CHAR= "org.eclipse.jdt.core.formatter.tabulation.char";
private static final String PREF_TAB_SIZE= "org.eclipse.jdt.core.formatter.tabulation.size";
// values
private static final String INSERT= "insert";
private static final String DO_NOT_INSERT= "do not insert";
private static final String COMPACT= "compact";
private static final String NORMAL= "normal";
private static final String TAB= "tab";
private static final String SPACE= "space";
private static final String CLEAR_ALL= "clear all";
private static final String PRESERVE_ONE= "preserve one";
private static String[] getAllKeys() {
return new String[] {
PREF_NEWLINE_OPENING_BRACES, PREF_NEWLINE_CONTROL_STATEMENT, PREF_NEWLINE_CLEAR_ALL,
PREF_NEWLINE_ELSE_IF, PREF_NEWLINE_EMPTY_BLOCK, PREF_LINE_SPLIT,
PREF_STYLE_COMPACT_ASSIGNEMENT, PREF_TAB_CHAR, PREF_TAB_SIZE
};
}
/**
* Gets the currently configured tab size
*/
public static int getTabSize() {
String string= (String) JavaCore.getOptions().get(PREF_TAB_SIZE);
return getIntValue(string, 4);
}
/**
* Gets the current compating assignement configuration
*/
public static boolean isCompactingAssignment() {
return COMPACT.equals(JavaCore.getOptions().get(PREF_STYLE_COMPACT_ASSIGNEMENT));
}
/**
* Gets the current compating assignement configuration
*/
public static boolean useSpaces() {
return SPACE.equals(JavaCore.getOptions().get(PREF_TAB_CHAR));
}
private static int getIntValue(String string, int dflt) {
try {
return Integer.parseInt(string);
} catch (NumberFormatException e) {
}
return dflt;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("CodeFormatterPreferencePage: value is null: " + key);
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
private 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();
}
}
private Hashtable fWorkingValues;
private ArrayList fCheckBoxes;
private ArrayList fTextBoxes;
private SelectionListener fButtonSelectionListener;
private ModifyListener fTextModifyListener;
private String fPreviewText;
private IDocument fPreviewDocument;
private Text fTabSizeTextBox;
private SourceViewer fSourceViewer;
public CodeFormatterPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("CodeFormatterPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
fCheckBoxes= new ArrayList();
fTextBoxes= new ArrayList();
fButtonSelectionListener= new SelectionListener() {
public void widgetDefaultSelected(SelectionEvent e) {}
public void widgetSelected(SelectionEvent e) {
if (!e.widget.isDisposed()) {
controlChanged((Button) e.widget);
}
}
};
fTextModifyListener= new ModifyListener() {
public void modifyText(ModifyEvent e) {
if (!e.widget.isDisposed()) {
textChanged((Text) e.widget);
}
}
};
fPreviewDocument= new Document();
fPreviewText= loadPreviewFile("CodeFormatterPreviewCode.txt"); //$NON-NLS-1$
}
/*
* @see IWorkbenchPreferencePage#init()
*/
public void init(IWorkbench workbench) {
}
/*
* @see PreferencePage#createControl(Composite)
*/
public void createControl(Composite parent) {
super.createControl(parent);
WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CODEFORMATTER_PREFERENCE_PAGE);
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
TabFolder folder= new TabFolder(composite, SWT.NONE);
folder.setLayout(new TabFolderLayout());
folder.setLayoutData(new GridData(GridData.FILL_BOTH));
String[] insertNotInsert= new String[] { INSERT, DO_NOT_INSERT };
layout= new GridLayout();
layout.numColumns= 2;
Composite newlineComposite= new Composite(folder, SWT.NULL);
newlineComposite.setLayout(layout);
String label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_opening_braces.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_OPENING_BRACES, insertNotInsert);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_control_statement.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_CONTROL_STATEMENT, insertNotInsert);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_clear_lines"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_CLEAR_ALL, new String[] { CLEAR_ALL, PRESERVE_ONE } );
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_else_if.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_ELSE_IF, insertNotInsert);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.newline_empty_block.label"); //$NON-NLS-1$
addCheckBox(newlineComposite, label, PREF_NEWLINE_EMPTY_BLOCK, insertNotInsert);
layout= new GridLayout();
layout.numColumns= 2;
Composite lineSplittingComposite= new Composite(folder, SWT.NULL);
lineSplittingComposite.setLayout(layout);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.split_line.label"); //$NON-NLS-1$
addTextField(lineSplittingComposite, label, PREF_LINE_SPLIT);
layout= new GridLayout();
layout.numColumns= 2;
Composite styleComposite= new Composite(folder, SWT.NULL);
styleComposite.setLayout(layout);
label= JavaUIMessages.getString("CodeFormatterPreferencePage.style_compact_assignement.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_STYLE_COMPACT_ASSIGNEMENT, new String[] { COMPACT, NORMAL } );
label= JavaUIMessages.getString("CodeFormatterPreferencePage.tab_char.label"); //$NON-NLS-1$
addCheckBox(styleComposite, label, PREF_TAB_CHAR, new String[] { TAB, SPACE } );
label= JavaUIMessages.getString("CodeFormatterPreferencePage.tab_size.label"); //$NON-NLS-1$
fTabSizeTextBox= addTextField(styleComposite, label, PREF_TAB_SIZE);
TabItem item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.newline.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
item.setControl(newlineComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.linesplit.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_CFILE));
item.setControl(lineSplittingComposite);
item= new TabItem(folder, SWT.NONE);
item.setText(JavaUIMessages.getString("CodeFormatterPreferencePage.tab.style.tabtitle")); //$NON-NLS-1$
item.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_SEARCH_REF));
item.setControl(styleComposite);
fSourceViewer= createPreview(parent);
updatePreview();
return composite;
}
private SourceViewer createPreview(Composite parent) {
SourceViewer previewViewer= new SourceViewer(parent, null, SWT.V_SCROLL | SWT.H_SCROLL);
JavaTextTools tools= JavaPlugin.getDefault().getJavaTextTools();
previewViewer.configure(new JavaSourceViewerConfiguration(tools, null));
previewViewer.getTextWidget().setFont(JFaceResources.getFontRegistry().get(JFaceResources.TEXT_FONT));
previewViewer.getTextWidget().setTabs(getIntValue((String) fWorkingValues.get(PREF_TAB_SIZE), 0));
previewViewer.setEditable(false);
previewViewer.setDocument(fPreviewDocument);
Control control= previewViewer.getControl();
GridData gdata= new GridData(GridData.FILL_BOTH);
gdata.widthHint= convertWidthInCharsToPixels(80);
gdata.heightHint= convertHeightInCharsToPixels(15);
control.setLayoutData(gdata);
return previewViewer;
}
private Button addCheckBox(Composite parent, String label, String key, String[] values) {
ControlData data= new ControlData(key, values);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.horizontalSpan= 2;
Button checkBox= new Button(parent, SWT.CHECK);
checkBox.setText(label);
checkBox.setData(data);
checkBox.setLayoutData(gd);
String currValue= (String)fWorkingValues.get(key);
checkBox.setSelection(data.getSelection(currValue) == 0);
checkBox.addSelectionListener(fButtonSelectionListener);
fCheckBoxes.add(checkBox);
return checkBox;
}
private Text addTextField(Composite parent, String label, String key) {
Label labelControl= new Label(parent, SWT.NONE);
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(String.valueOf(getIntValue(currValue, 1)));
textBox.setTextLimit(3);
textBox.addModifyListener(fTextModifyListener);
GridData gd= new GridData();
gd.widthHint= convertWidthInCharsToPixels(5);
textBox.setLayoutData(gd);
fTextBoxes.add(textBox);
return textBox;
}
private void controlChanged(Button button) {
ControlData data= (ControlData) button.getData();
boolean selection= button.getSelection();
String newValue= data.getValue(selection);
fWorkingValues.put(data.getKey(), newValue);
updatePreview();
if (PREF_TAB_CHAR.equals(data.getKey())) {
updateStatus(new StatusInfo());
if (selection) {
fTabSizeTextBox.setText((String)fWorkingValues.get(PREF_TAB_SIZE));
}
}
}
private void textChanged(Text textControl) {
String key= (String) textControl.getData();
String number= textControl.getText();
IStatus status= validatePositiveNumber(number);
if (!status.matches(IStatus.ERROR)) {
fWorkingValues.put(key, number);
}
if (PREF_TAB_SIZE.equals(key)) {
fSourceViewer.getTextWidget().setTabs(getIntValue(number, 0));
}
updateStatus(status);
updatePreview();
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
return super.performOk();
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
updateControls();
super.performDefaults();
}
private String loadPreviewFile(String filename) {
String separator= System.getProperty("line.separator"); //$NON-NLS-1$
StringBuffer btxt= new StringBuffer(512);
BufferedReader rin= null;
try {
rin= new BufferedReader(new InputStreamReader(getClass().getResourceAsStream(filename)));
String line;
while ((line= rin.readLine()) != null) {
btxt.append(line);
btxt.append(separator);
}
} catch (IOException io) {
JavaPlugin.log(io);
} finally {
if (rin != null) {
try { rin.close(); } catch (IOException e) {}
}
}
return btxt.toString();
}
private void updatePreview() {
fPreviewDocument.set(new CodeFormatter(fWorkingValues).format(fPreviewText));
}
private void updateControls() {
// update the UI
for (int i= fCheckBoxes.size() - 1; i >= 0; i--) {
Button curr= (Button) fCheckBoxes.get(i);
ControlData data= (ControlData) curr.getData();
String currValue= (String) fWorkingValues.get(data.getKey());
curr.setSelection(data.getSelection(currValue) == 0);
}
for (int i= fTextBoxes.size() - 1; i >= 0; i--) {
Text curr= (Text) fTextBoxes.get(i);
String key= (String) curr.getData();
String currValue= (String) fWorkingValues.get(key);
curr.setText(currValue);
}
}
private IStatus validatePositiveNumber(String number) {
StatusInfo status= new StatusInfo();
if (number.length() == 0) {
status.setError(JavaUIMessages.getString("CodeFormatterPreferencePage.empty_input"));
} else {
try {
int value= Integer.parseInt(number);
if (value < 0) {
status.setError(JavaUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number));
}
} catch (NumberFormatException e) {
status.setError(JavaUIMessages.getFormattedString("CodeFormatterPreferencePage.invalid_input", number));
}
}
return status;
}
private void updateStatus(IStatus status) {
if (!status.matches(IStatus.ERROR)) {
// look if there are more severe errors
for (int i= 0; i < fTextBoxes.size(); i++) {
Text curr= (Text) fTextBoxes.get(i);
if (!(curr == fTabSizeTextBox && usesTabs())) {
IStatus currStatus= validatePositiveNumber(curr.getText());
status= StatusUtil.getMoreSevere(currStatus, status);
}
}
}
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private boolean usesTabs() {
return TAB.equals(fWorkingValues.get(PREF_TAB_CHAR));
}
}
|
11,826 |
Bug 11826 Build exclusion filter should be trimmed prior to storing
| null |
resolved fixed
|
574cdab
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2002-03-22T19:42:21Z | 2002-03-20T13:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/JavaBuilderPreferencePage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.preferences;
import java.lang.reflect.InvocationTargetException;
import java.util.Hashtable;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IncrementalProjectBuilder;
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.swt.SWT;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaUIMessages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
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.LayoutUtil;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField;
public class JavaBuilderPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
private StringDialogField fResourceFilterField;
private StatusInfo fResourceFilterStatus;
private Hashtable fWorkingValues;
private static final String PREF_RESOURCE_FILTER= "org.eclipse.jdt.core.builder.resourceCopyExclusionFilter";
private static String[] getAllKeys() {
return new String[] {
PREF_RESOURCE_FILTER
};
}
public JavaBuilderPreferencePage() {
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
setDescription(JavaUIMessages.getString("JavaBuilderPreferencePage.description")); //$NON-NLS-1$
fWorkingValues= JavaCore.getOptions();
IDialogFieldListener listener= new IDialogFieldListener() {
public void dialogFieldChanged(DialogField field) {
doValidation();
}
};
fResourceFilterField= new StringDialogField();
fResourceFilterField.setDialogFieldListener(listener);
fResourceFilterField.setLabelText(JavaUIMessages.getString("JavaBuilderPreferencePage.filter.label"));
updateControls();
}
/*
* @see PreferencePage#createContents(Composite)
*/
protected Control createContents(Composite parent) {
initializeDialogUnits(parent);
GridLayout layout= new GridLayout();
layout.marginHeight= 0;
layout.marginWidth= 0;
layout.numColumns= 2;
Composite composite= new Composite(parent, SWT.NONE);
composite.setLayout(layout);
DialogField resourceFilterLabel= new DialogField();
resourceFilterLabel.setLabelText(JavaUIMessages.getString("JavaBuilderPreferencePage.filter.description"));
resourceFilterLabel.doFillIntoGrid(composite, 2);
LayoutUtil.setWidthHint(resourceFilterLabel.getLabelControl(null), convertWidthInCharsToPixels(80));
fResourceFilterField.doFillIntoGrid(composite, 2);
LayoutUtil.setHorizontalGrabbing(fResourceFilterField.getTextControl(null));
LayoutUtil.setWidthHint(fResourceFilterField.getTextControl(null), convertWidthInCharsToPixels(50));
return composite;
}
/**
* Initializes the current options (read from preference store)
*/
public static void initDefaults(IPreferenceStore store) {
Hashtable hashtable= JavaCore.getDefaultOptions();
Hashtable currOptions= JavaCore.getOptions();
String[] allKeys= getAllKeys();
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String defValue= (String) hashtable.get(key);
if (defValue != null) {
store.setDefault(key, defValue);
} else {
JavaPlugin.logErrorMessage("JavaBuilderPreferencePage: value is null: " + key);
}
// update the JavaCore options from the pref store
String val= store.getString(key);
if (val != null) {
currOptions.put(key, val);
}
}
JavaCore.setOptions(currOptions);
}
/*
* @see IWorkbenchPreferencePage#init(IWorkbench)
*/
public void init(IWorkbench workbench) {
}
/*
* @see IPreferencePage#performOk()
*/
public boolean performOk() {
String[] allKeys= getAllKeys();
// preserve other options
// store in JCore and the preferences
Hashtable actualOptions= JavaCore.getOptions();
IPreferenceStore store= getPreferenceStore();
boolean hasChanges= false;
for (int i= 0; i < allKeys.length; i++) {
String key= allKeys[i];
String val= (String) fWorkingValues.get(key);
String oldVal= (String) actualOptions.get(key);
hasChanges= hasChanges | !val.equals(oldVal);
actualOptions.put(key, val);
store.setValue(key, val);
}
JavaCore.setOptions(actualOptions);
if (hasChanges) {
String title= JavaUIMessages.getString("JavaBuilderPreferencePage.needsbuild.title");
String message= JavaUIMessages.getString("JavaBuilderPreferencePage.needsbuild.message");
if (MessageDialog.openQuestion(getShell(), title, message)) {
doFullBuild();
}
}
return super.performOk();
}
private void doValidation() {
fWorkingValues.put(PREF_RESOURCE_FILTER, fResourceFilterField.getText());
IStatus status= validateResourceFilters();
updateStatus(status);
}
private IStatus validateResourceFilters() {
IWorkspace workspace= ResourcesPlugin.getWorkspace();
String text= fResourceFilterField.getText();
StringTokenizer tok= new StringTokenizer(text, ",");
while (tok.hasMoreTokens()) {
String curr= tok.nextToken().trim();
String fileName= curr.replace('*', 'x');
IStatus status= workspace.validateName(fileName, IResource.FILE);
if (status.matches(IStatus.ERROR)) {
String message= JavaUIMessages.getFormattedString("JavaBuilderPreferencePage.filter.invalidsegment.error", status.getMessage());
return new StatusInfo(IStatus.ERROR, message);
}
}
return new StatusInfo();
}
private void updateStatus(IStatus status) {
setValid(!status.matches(IStatus.ERROR));
StatusUtil.applyToStatusLine(this, status);
}
private void doFullBuild() {
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(true, true, new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException {
try {
JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
});
} catch (InterruptedException e) {
// cancelled by user
} catch (InvocationTargetException e) {
String title= JavaUIMessages.getString("JavaBuilderPreferencePage.builderror.title");
String message= JavaUIMessages.getString("JavaBuilderPreferencePage.builderror.message");
ExceptionHandler.handle(e, getShell(), title, message);
}
}
/*
* @see PreferencePage#performDefaults()
*/
protected void performDefaults() {
fWorkingValues= JavaCore.getDefaultOptions();
updateControls();
doValidation();
super.performDefaults();
}
private void updateControls() {
// update the UI
fResourceFilterField.setText((String) fWorkingValues.get(PREF_RESOURCE_FILTER));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.