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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31,150 |
Bug 31150 filecomment template no longer used [code manipulation]
|
Build: I20030206 The "filecomment" template description says it is used by the new class and interface wizards. This template doesn't seem to be used anymore. Instead I now get the template from the code generation preference page. The catch block template is also found in two places. Having two template preference pages with some overlapping entries seems confusing.
|
resolved fixed
|
7ff0036
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:59:17Z | 2003-02-06T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/IUIConstants.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import org.eclipse.jdt.ui.JavaUI;
public interface IUIConstants {
public static final String KEY_OK= JavaUI.ID_PLUGIN + ".ok.label"; //$NON-NLS-1$
public static final String KEY_CANCEL= JavaUI.ID_PLUGIN + ".cancel.label"; //$NON-NLS-1$
public static final String P_ICON_NAME= JavaUI.ID_PLUGIN + ".icon_name"; //$NON-NLS-1$
public static final String DIALOGSTORE_LASTEXTJAR= JavaUI.ID_PLUGIN + ".lastextjar"; //$NON-NLS-1$
public static final String DIALOGSTORE_LASTJARATTACH= JavaUI.ID_PLUGIN + ".lastjarattach"; //$NON-NLS-1$
public static final String DIALOGSTORE_LASTVARIABLE= JavaUI.ID_PLUGIN + ".lastvariable"; //$NON-NLS-1$
}
|
31,150 |
Bug 31150 filecomment template no longer used [code manipulation]
|
Build: I20030206 The "filecomment" template description says it is used by the new class and interface wizards. This template doesn't seem to be used anymore. Instead I now get the template from the code generation preference page. The catch block template is also found in two places. Having two template preference pages with some overlapping entries seems confusing.
|
resolved fixed
|
7ff0036
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:59:17Z | 2003-02-06T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/OptionalMessageDialog.java
| |
31,150 |
Bug 31150 filecomment template no longer used [code manipulation]
|
Build: I20030206 The "filecomment" template description says it is used by the new class and interface wizards. This template doesn't seem to be used anymore. Instead I now get the template from the code generation preference page. The catch block template is also found in two places. Having two template preference pages with some overlapping entries seems confusing.
|
resolved fixed
|
7ff0036
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:59:17Z | 2003-02-06T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewClassCreationWizard.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class NewClassCreationWizard extends NewElementWizard {
private NewClassWizardPage fPage;
public NewClassCreationWizard() {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS);
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
setWindowTitle(NewWizardMessages.getString("NewClassCreationWizard.title")); //$NON-NLS-1$
}
/*
* @see Wizard#createPages
*/
public void addPages() {
super.addPages();
fPage= new NewClassWizardPage();
addPage(fPage);
fPage.init(getSelection());
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor)
*/
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
fPage.createType(monitor); // use the full progress monitor
ICompilationUnit cu= JavaModelUtil.toOriginal(fPage.getCreatedType().getCompilationUnit());
if (cu != null) {
IResource resource= cu.getResource();
selectAndReveal(resource);
openResource((IFile) resource);
}
}
}
|
31,150 |
Bug 31150 filecomment template no longer used [code manipulation]
|
Build: I20030206 The "filecomment" template description says it is used by the new class and interface wizards. This template doesn't seem to be used anymore. Instead I now get the template from the code generation preference page. The catch block template is also found in two places. Having two template preference pages with some overlapping entries seems confusing.
|
resolved fixed
|
7ff0036
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:59:17Z | 2003-02-06T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewElementWizard.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
public abstract class NewElementWizard extends Wizard implements INewWizard {
private IWorkbench fWorkbench;
private IStructuredSelection fSelection;
public NewElementWizard() {
setNeedsProgressMonitor(true);
}
protected void openResource(final IFile resource) {
final IWorkbenchPage activePage= JavaPlugin.getActivePage();
if (activePage != null) {
final Display display= getShell().getDisplay();
if (display != null) {
display.asyncExec(new Runnable() {
public void run() {
try {
activePage.openEditor(resource);
} catch (PartInitException e) {
JavaPlugin.log(e);
}
}
});
}
}
}
/**
* Subclasses should override to perform the actions of the wizard.
* This method is run in the wizard container's context as a workspace runnable.
*/
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
}
protected void handleFinishException(Shell shell, InvocationTargetException e) {
String title= NewWizardMessages.getString("NewElementWizard.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewElementWizard.op_error.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, shell, title, message);
}
/*
* @see Wizard#performFinish
*/
public boolean performFinish() {
IWorkspaceRunnable op= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
try {
finishPage(monitor);
} catch (InterruptedException e) {
throw new OperationCanceledException(e.getMessage());
}
}
};
try {
getContainer().run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
handleFinishException(getShell(), e);
return false;
} catch (InterruptedException e) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
*/
public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
fWorkbench= workbench;
fSelection= currentSelection;
}
public IStructuredSelection getSelection() {
return fSelection;
}
public IWorkbench getWorkbench() {
return fWorkbench;
}
protected void selectAndReveal(IResource newResource) {
BasicNewResourceWizard.selectAndReveal(newResource, fWorkbench.getActiveWorkbenchWindow());
}
}
|
31,150 |
Bug 31150 filecomment template no longer used [code manipulation]
|
Build: I20030206 The "filecomment" template description says it is used by the new class and interface wizards. This template doesn't seem to be used anymore. Instead I now get the template from the code generation preference page. The catch block template is also found in two places. Having two template preference pages with some overlapping entries seems confusing.
|
resolved fixed
|
7ff0036
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T10:59:17Z | 2003-02-06T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewInterfaceCreationWizard.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
public class NewInterfaceCreationWizard extends NewElementWizard {
private NewInterfaceWizardPage fPage;
public NewInterfaceCreationWizard() {
super();
setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWINT);
setDialogSettings(JavaPlugin.getDefault().getDialogSettings());
setWindowTitle(NewWizardMessages.getString("NewInterfaceCreationWizard.title")); //$NON-NLS-1$
}
/*
* @see Wizard#addPages
*/
public void addPages() {
super.addPages();
fPage= new NewInterfaceWizardPage();
addPage(fPage);
fPage.init(getSelection());
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.NewElementWizard#finishPage(org.eclipse.core.runtime.IProgressMonitor)
*/
protected void finishPage(IProgressMonitor monitor) throws InterruptedException, CoreException {
fPage.createType(monitor); // use the full progress monitor
ICompilationUnit cu= JavaModelUtil.toOriginal(fPage.getCreatedType().getCompilationUnit());
if (cu != null) {
IResource resource= cu.getResource();
selectAndReveal(resource);
openResource((IFile) resource);
}
}
}
|
30,191 |
Bug 30191 Navigate Goto Resource does not find certain files
|
If I open a Java perspective and then Navigate | Go to | Resource, not all files are visible only those that are under the java source directory. If I open a navigator view or perspective, all files are seen. Should the the goto resource should be the same.
|
resolved fixed
|
cece5ba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:05:57Z | 2003-01-24T17:40:00Z |
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_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 ADD_TO_CLASSPATH_ACTION= PREFIX + "addjtoclasspath_action_context"; //$NON-NLS-1$
public static final String REMOVE_FROM_CLASSPATH_ACTION= PREFIX + "removefromclasspath_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$
public static final String OPEN_CLASS_WIZARD_ACTION= PREFIX + "open_class_wizard_action"; //$NON-NLS-1$
public static final String OPEN_INTERFACE_WIZARD_ACTION= PREFIX + "open_interface_wizard_action"; //$NON-NLS-1$
public static final String SORT_MEMBERS_ACTION= PREFIX + "sort_members_action"; //$NON-NLS-1$
public static final String OPEN_PACKAGE_WIZARD_ACTION= PREFIX + "open_package_wizard_action"; //$NON-NLS-1$
public static final String OPEN_PROJECT_WIZARD_ACTION= PREFIX + "open_project_wizard_action"; //$NON-NLS-1$
public static final String OPEN_SNIPPET_WIZARD_ACTION= PREFIX + "open_snippet_wizard_action"; //$NON-NLS-1$
public static final String EDIT_WORKING_SET_ACTION= PREFIX + "edit_working_set_action"; //$NON-NLS-1$
public static final String CLEAR_WORKING_SET_ACTION= PREFIX + "clear_working_set_action"; //$NON-NLS-1$
public static final String GOTO_MARKER_ACTION= PREFIX + "goto_marker_action"; //$NON-NLS-1$
public static final String GOTO_PACKAGE_ACTION= PREFIX + "goto_package_action"; //$NON-NLS-1$
public static final String HISTORY_ACTION= PREFIX + "history_action"; //$NON-NLS-1$
public static final String HISTORY_LIST_ACTION= PREFIX + "history_list_action"; //$NON-NLS-1$
public static final String LEXICAL_SORTING_OUTLINE_ACTION= PREFIX + "lexical_sorting_outline_action"; //$NON-NLS-1$
public static final String LEXICAL_SORTING_BROWSING_ACTION= PREFIX + "lexical_sorting_browsing_action"; //$NON-NLS-1$
public static final String OPEN_JAVA_PERSPECTIVE_ACTION= PREFIX + "open_java_perspective_action"; //$NON-NLS-1$
public static final String ADD_DELEGATE_METHODS_ACTION= PREFIX + "add_delegate_methods_action"; //$NON-NLS-1$
public static final String OPEN_JAVA_BROWSING_PERSPECTIVE_ACTION= PREFIX + "open_java_browsing_perspective_action"; //$NON-NLS-1$
public static final String OPEN_PROJECT_ACTION= PREFIX + "open_project_action"; //$NON-NLS-1$
public static final String OPEN_TYPE_ACTION= PREFIX + "open_type_action"; //$NON-NLS-1$
public static final String OPEN_TYPE_IN_HIERARCHY_ACTION= PREFIX + "open_type_in_hierarchy_action"; //$NON-NLS-1$
public static final String ADD_JAVADOC_STUB_ACTION= PREFIX + "add_javadoc_stub_action"; //$NON-NLS-1$
public static final String ADD_TASK_ACTION= PREFIX + "add_task_action"; //$NON-NLS-1$
public static final String EXTERNALIZE_STRINGS_ACTION= PREFIX + "externalize_strings_action"; //$NON-NLS-1$
public static final String EXTRACT_METHOD_ACTION= PREFIX + "extract_method_action"; //$NON-NLS-1$
public static final String EXTRACT_TEMP_ACTION= PREFIX + "extract_temp_action"; //$NON-NLS-1$
public static final String PROMOTE_TEMP_TO_FIELD_ACTION= PREFIX + "promote_temp_to_field_action"; //$NON-NLS-1$
public static final String CONVERT_ANONYMOUS_TO_NESTED_ACTION= PREFIX + "convert_anonymous_to_nested_action"; //$NON-NLS-1$
public static final String EXTRACT_CONSTANT_ACTION= PREFIX + "extract_constant_action"; //$NON-NLS-1$
public static final String EXTRACT_INTERFACE_ACTION= PREFIX + "extract_interface_action"; //$NON-NLS-1$
public static final String MOVE_INNER_TO_TOP_ACTION= PREFIX + "move_inner_to_top_level_action"; //$NON-NLS-1$
public static final String USE_SUPERTYPE_ACTION= PREFIX + "use_supertype_action"; //$NON-NLS-1$
public static final String FIND_DECLARATIONS_IN_HIERARCHY_ACTION= PREFIX + "find_declarations_in_hierarchy_action"; //$NON-NLS-1$
public static final String FIND_DECLARATIONS_IN_WORKING_SET_ACTION= PREFIX + "find_declarations_in_working_set_action"; //$NON-NLS-1$
public static final String FIND_IMPLEMENTORS_IN_WORKING_SET_ACTION= PREFIX + "find_implementors_in_working_set_action"; //$NON-NLS-1$
public static final String FIND_READ_REFERENCES_ACTION= PREFIX + "find_read_references_action"; //$NON-NLS-1$
public static final String FIND_READ_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_read_references_in_hierarchy_action"; //$NON-NLS-1$
public static final String FIND_WRITE_REFERENCES_IN_HIERARCHY_ACTION= PREFIX + "find_write_references_in_hierarchy_action"; //$NON-NLS-1$
public static final String FIND_READ_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_read_references_in_working_set_action"; //$NON-NLS-1$
public static final String FIND_WRITE_REFERENCES_IN_WORKING_SET_ACTION= PREFIX + "find_write_references_in_working_set_action"; //$NON-NLS-1$
public static final String FIND_WRITE_REFERENCES_ACTION= PREFIX + "find_write_references_action"; //$NON-NLS-1$
public static final String FIND_OCCURRENCES_IN_FILE_ACTION= PREFIX + "find_occurrences_in_file_action"; //$NON-NLS-1$
public static final String WORKING_SET_FIND_ACTION= PREFIX + "working_set_find_action"; //$NON-NLS-1$
public static final String FIND_STRINGS_TO_EXTERNALIZE_ACTION= PREFIX + "find_strings_to_externalize_action"; //$NON-NLS-1$
public static final String INLINE_ACTION= PREFIX + "inline_action"; //$NON-NLS-1$
public static final String MODIFY_PARAMETERS_ACTION= PREFIX + "modify_parameters_action"; //$NON-NLS-1$
public static final String MOVE_ACTION= PREFIX + "move_action"; //$NON-NLS-1$
public static final String OPEN_ACTION= PREFIX + "open_action"; //$NON-NLS-1$
public static final String OPEN_EXTERNAL_JAVADOC_ACTION= PREFIX + "open_external_javadoc_action"; //$NON-NLS-1$
public static final String OPEN_SUPER_IMPLEMENTATION_ACTION= PREFIX + "open_super_implementation_action"; //$NON-NLS-1$
public static final String PULL_UP_ACTION= PREFIX + "pull_up_action"; //$NON-NLS-1$
public static final String PUSH_DOWN_ACTION= PREFIX + "push_down_action"; //$NON-NLS-1$
public static final String REFRESH_ACTION= PREFIX + "refresh_action"; //$NON-NLS-1$
public static final String RENAME_ACTION= PREFIX + "rename_action"; //$NON-NLS-1$
public static final String SELF_ENCAPSULATE_ACTION= PREFIX + "self_encapsulate_action"; //$NON-NLS-1$
public static final String SHOW_IN_NAVIGATOR_VIEW_ACTION= PREFIX + "show_in_navigator_action"; //$NON-NLS-1$
public static final String SURROUND_WITH_TRY_CATCH_ACTION= PREFIX + "surround_with_try_catch_action"; //$NON-NLS-1$
public static final String OPEN_RESOURCE_ACTION= PREFIX + "open_resource_action"; //$NON-NLS-1$
public static final String SELECT_WORKING_SET_ACTION= PREFIX + "select_working_set_action"; //$NON-NLS-1$
public static final String STRUCTURED_SELECTION_HISTORY_ACTION= PREFIX + "structured_selection_history_action"; //$NON-NLS-1$
public static final String STRUCTURED_SELECT_ENCLOSING_ACTION= PREFIX + "structured_select_enclosing_action"; //$NON-NLS-1$
public static final String STRUCTURED_SELECT_NEXT_ACTION= PREFIX + "structured_select_next_action"; //$NON-NLS-1$
public static final String STRUCTURED_SELECT_PREVIOUS_ACTION= PREFIX + "structured_select_previous_action"; //$NON-NLS-1$
public static final String TOGGLE_ORIENTATION_ACTION= PREFIX + "toggle_orientations_action"; //$NON-NLS-1$
public static final String CUT_ACTION= PREFIX + "cut_action"; //$NON-NLS-1$
public static final String COPY_ACTION= PREFIX + "copy_action"; //$NON-NLS-1$
public static final String PASTE_ACTION= PREFIX + "paste_action"; //$NON-NLS-1$
public static final String DELETE_ACTION= PREFIX + "delete_action"; //$NON-NLS-1$
public static final String SELECT_ALL_ACTION= PREFIX + "select_all_action"; //$NON-NLS-1$
public static final String OPEN_TYPE_HIERARCHY_ACTION= PREFIX + "open_type_hierarchy_action"; //$NON-NLS-1$
public static final String COLLAPSE_ALL_ACTION= PREFIX + "open_type_hierarchy_action"; //$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 SOURCE_ATTACHMENT_DIALOG= PREFIX + "source_attachment_dialog_context"; //$NON-NLS-1$
public static final String LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG= PREFIX + "advanced_dialog_context"; //$NON-NLS-1$
public static final String CONFIRM_SAVE_MODIFIED_RESOURCES_DIALOG= PREFIX + "confirm_save_modified_resources_dialog_context"; //$NON-NLS-1$
public static final String NEW_VARIABLE_ENTRY_DIALOG= PREFIX + "new_variable_dialog_context"; //$NON-NLS-1$
public static final String COMPARE_DIALOG= PREFIX + "compare_dialog_context"; //$NON-NLS-1$
public static final String NONNLS_DIALOG= PREFIX + "nonnls_dialog_context"; //$NON-NLS-1$
public static final String MULTI_MAIN_TYPE_SELECTION_DIALOG= PREFIX + "multi_main_type_selection_dialog_context"; //$NON-NLS-1$
public static final String MULTI_TYPE_SELECTION_DIALOG= PREFIX + "multi_type_selection_dialog_context"; //$NON-NLS-1$
public static final String SUPER_INTERFACE_SELECTION_DIALOG= PREFIX + "super_interface_selection_dialog_context"; //$NON-NLS-1$
public static final String OVERRIDE_TREE_SELECTION_DIALOG= PREFIX + "override_tree_selection_dialog_context"; //$NON-NLS-1$
public static final String MOVE_DESTINATION_DIALOG= PREFIX + "move_destination_dialog_context"; //$NON-NLS-1$
public static final String CHOOSE_VARIABLE_DIALOG= PREFIX + "choose_variable_dialog_context"; //$NON-NLS-1$
public static final String EDIT_TEMPLATE_DIALOG= PREFIX + "edit_template_dialog_context"; //$NON-NLS-1$
public static final String HISTORY_LIST_DIALOG= PREFIX + "history_list_dialog_context"; //$NON-NLS-1$
public static final String IMPORT_ORGANIZE_INPUT_DIALOG= PREFIX + "import_organize_input_dialog_context"; //$NON-NLS-1$
public static final String JAVADOC_PROPERTY_DIALOG= PREFIX + "javadoc_property_dialog_context"; //$NON-NLS-1$
public static final String NEW_CONTAINER_DIALOG= PREFIX + "new_container_dialog_context"; //$NON-NLS-1$
public static final String EXCLUSION_PATTERN_DIALOG= PREFIX + "exclusion_pattern_dialog_context"; //$NON-NLS-1$
public static final String OUTPUT_LOCATION_DIALOG= PREFIX + "output_location_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 NLS_SEARCH_PAGE= PREFIX + "nls_search_page_context"; //$NON-NLS-1$
public static final String JAVA_EDITOR= PREFIX + "java_editor_context"; //$NON-NLS-1$
// view parts
public static final String TYPE_HIERARCHY_VIEW= PREFIX + "type_hierarchy_view_context"; //$NON-NLS-1$
public static final String PACKAGES_VIEW= PREFIX + "package_view_context"; //$NON-NLS-1$
public static final String PROJECTS_VIEW= PREFIX + "projects_view_context"; //$NON-NLS-1$
public static final String PACKAGES_BROWSING_VIEW= PREFIX + "packages_browsing_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 SORT_ORDER_PREFERENCE_PAGE= PREFIX + "sort_order_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 COMPILER_PROPERTY_PAGE= PREFIX + "compiler_property_page_context"; //$NON-NLS-1$
public static final String TODOTASK_PROPERTY_PAGE= PREFIX + "tasktags_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 TODOTASK_PREFERENCE_PAGE= PREFIX + "tasktags_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 JAVADOC_PREFERENCE_PAGE= PREFIX + "javadoc_preference_page_context"; //$NON-NLS-1$
public static final String NEW_JAVA_PROJECT_PREFERENCE_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$
public static final String JAVADOC_CONFIGURATION_PROPERTY_PAGE= PREFIX + "new_java_project_preference_page_context"; //$NON-NLS-1$
public static final String JAVA_ELEMENT_INFO_PAGE= PREFIX + "java_element_info_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$
public static final String JAVA_WORKING_SET_PAGE= PREFIX + "java_working_set_page_context"; //$NON-NLS-1$
public static final String CLASSPATH_CONTAINER_DEFAULT_PAGE= PREFIX + "classpath_container_default_page_context"; //$NON-NLS-1$
public static final String JAVADOC_STANDARD_PAGE= PREFIX + "javadoc_standard_page_context"; //$NON-NLS-1$
public static final String JAVADOC_SPECIFICS_PAGE= PREFIX + "javadoc_specifics_page_context"; //$NON-NLS-1$
public static final String JAVADOC_TREE_PAGE= PREFIX + "javadoc_tree_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_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 EXTERNALIZE_WIZARD_KEYVALUE_PAGE= PREFIX + "externalize_wizard_keyvalue_page_context"; //$NON-NLS-1$
public static final String EXTERNALIZE_WIZARD_PROPERTIES_FILE_PAGE= PREFIX + "externalize_wizard_properties_file_page_context"; //$NON-NLS-1$
public static final String EXTERNALIZE_ERROR_WIZARD_PAGE= PREFIX + "externalize_error_wizard_page_context"; //$NON-NLS-1$
public static final String EXTRACT_INTERFACE_WIZARD_PAGE= PREFIX + "extract_interface_temp_page_context"; //$NON-NLS-1$
public static final String EXTRACT_INTERFACE_ERROR_WIZARD_PAGE= PREFIX + "extract_interface_error_wizard_page_context"; //$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 EXTRACT_TEMP_WIZARD_PAGE= PREFIX + "extract_temp_page_context"; //$NON-NLS-1$
public static final String EXTRACT_TEMP_ERROR_WIZARD_PAGE= PREFIX + "extract_temp_error_wizard_page_context"; //$NON-NLS-1$
public static final String EXTRACT_CONSTANT_WIZARD_PAGE= PREFIX + "extract_constant_page_context"; //$NON-NLS-1$
public static final String EXTRACT_CONSTANT_ERROR_WIZARD_PAGE= PREFIX + "extract_constant_error_wizard_page_context"; //$NON-NLS-1$
public static final String PROMOTE_TEMP_TO_FIELD_WIZARD_PAGE= PREFIX + "promote_temp_to_field_page_context"; //$NON-NLS-1$
public static final String PROMOTE_TEMP_TO_FIELD_ERROR_WIZARD_PAGE= PREFIX + "promote_temp_to_field_error_wizard_page_context"; //$NON-NLS-1$
public static final String CONVERT_ANONYMOUS_TO_NESTED_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_page_context"; //$NON-NLS-1$
public static final String CONVERT_ANONYMOUS_TO_NESTED_ERROR_WIZARD_PAGE= PREFIX + "convert_anonymous_to_nested_error_wizard_page_context"; //$NON-NLS-1$
public static final String MODIFY_PARAMETERS_WIZARD_PAGE= PREFIX + "modify_parameters_wizard_page_context"; //$NON-NLS-1$
public static final String MODIFY_PARAMETERS_ERROR_WIZARD_PAGE= PREFIX + "modify_parameters_error_wizard_page_context"; //$NON-NLS-1$
public static final String MOVE_MEMBERS_WIZARD_PAGE= PREFIX + "move_members_wizard_page_context"; //$NON-NLS-1$
public static final String MOVE_MEMBERS_ERROR_WIZARD_PAGE= PREFIX + "move_members_error_error_wizard_page_context"; //$NON-NLS-1$
public static final String MOVE_INNER_TO_TOP_WIZARD_PAGE= PREFIX + "move_inner_to_top_wizard_page_context"; //$NON-NLS-1$
public static final String MOVE_INNER_TO_TOP_ERROR_WIZARD_PAGE= PREFIX + "move_inner_to_top_error_error_wizard_page_context"; //$NON-NLS-1$
public static final String PULL_UP_WIZARD_PAGE= PREFIX + "pull_up_wizard_page_context"; //$NON-NLS-1$
public static final String PULL_UP_ERROR_WIZARD_PAGE= PREFIX + "pull_up_error_error_wizard_page_context"; //$NON-NLS-1$
public static final String PUSH_DOWN_WIZARD_PAGE= PREFIX + "push_down_wizard_page_context"; //$NON-NLS-1$
public static final String PUSH_DOWN_ERROR_WIZARD_PAGE= PREFIX + "push_down_error_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_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$
public static final String SEF_ERROR_WIZARD_PAGE= PREFIX + "self_encapsulate_field_error_wizard_page_context"; //$NON-NLS-1$
public static final String USE_SUPERTYPE_WIZARD_PAGE= PREFIX + "use_supertype_wizard_page_context"; //$NON-NLS-1$
public static final String USE_SUPERTYPE_ERROR_WIZARD_PAGE= PREFIX + "use_supertype_error_wizard_page_context"; //$NON-NLS-1$
public static final String INLINE_METHOD_WIZARD_PAGE= PREFIX + "inline_method_wizard_page_context"; //$NON-NLS-1$
public static final String INLINE_METHOD_ERROR_WIZARD_PAGE= PREFIX + "inline_method_error_wizard_page_context"; //$NON-NLS-1$
public static final String INLINE_CONSTANT_WIZARD_PAGE= PREFIX + "inline_constant_wizard_page_context"; //$NON-NLS-1$
public static final String INLINE_CONSTANT_ERROR_WIZARD_PAGE= PREFIX + "inline_constant_error_wizard_page_context"; //$NON-NLS-1$
public static final String INLINE_TEMP_ERROR_WIZARD_PAGE= PREFIX + "inline_temp_error_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$
// Custom Filters
public static final String CUSTOM_FILTERS_DIALOG= PREFIX + "open_custom_filters_dialog_context"; //$NON-NLS-1$
}
|
30,191 |
Bug 30191 Navigate Goto Resource does not find certain files
|
If I open a Java perspective and then Navigate | Go to | Resource, not all files are visible only those that are under the java source directory. If I open a navigator view or perspective, all files are seen. Should the the goto resource should be the same.
|
resolved fixed
|
cece5ba
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:05:57Z | 2003-01-24T17:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/GotoResourceAction.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.dialogs.ResourceListSelectionDialog;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.JavaCore;
public class GotoResourceAction extends Action {
private PackageExplorerPart fPackageExplorer;
private Viewer fViewer;
private int fSize;
public GotoResourceAction(PackageExplorerPart explorer) {
setText(PackagesMessages.getString("GotoResource.action.label")); //$NON-NLS-1$
fPackageExplorer= explorer;
fViewer= explorer.getViewer();
fSize= 512;
}
public void run() {
ViewerFilter[] filters= fPackageExplorer.getViewer().getFilters();
List resources= new ArrayList(fSize);
try {
collect(resources, JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()), filters);
} catch (CoreException e) {
}
IResource resourcesArray[]= (IResource[]) resources.toArray(new IResource[resources.size()]);
ResourceListSelectionDialog dialog= new ResourceListSelectionDialog(
fPackageExplorer.getViewSite().getShell(), resourcesArray);
dialog.setTitle(PackagesMessages.getString("GotoResource.dialog.title")); //$NON-NLS-1$
dialog.open();
Object[] result = dialog.getResult();
if (result == null || result.length == 0 || result[0] instanceof IResource == false)
return;
StructuredSelection selection= null;
IJavaElement element = JavaCore.create((IResource)result[0]);
if (element != null)
selection= new StructuredSelection(element);
else
selection= new StructuredSelection(result[0]);
fViewer.setSelection(selection, true);
}
private void collect(List result, IJavaModel parent, ViewerFilter[] filters) throws CoreException {
IJavaProject[] projects= parent.getJavaProjects();
for (int i = 0; i < projects.length; i++) {
IJavaProject project= projects[i];
if (isVisible(parent, project, filters)) {
collect(result, project, filters);
}
}
}
private void collect(List result, IJavaProject parent, ViewerFilter[] filters) throws CoreException {
boolean handleResources= true;
IPackageFragmentRoot[] roots= parent.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (isVisible(parent, root, filters) && !root.isArchive() && !root.isExternal()) {
if ("".equals(root.getElementName())) //$NON-NLS-1$
handleResources= false;
collect(result, root, filters);
}
}
if (handleResources)
handleResources(result, parent, parent.getNonJavaResources(), filters);
}
private void collect(List result, IPackageFragmentRoot parent, ViewerFilter[] filters) throws CoreException {
IJavaElement[] fragments= parent.getChildren();
for (int i= 0; i < fragments.length; i++) {
IJavaElement fragment= fragments[i];
if (!isVisible(parent, fragment, filters))
continue;
if (fragment.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
collect(result, (IPackageFragment)fragment, filters);
}
handleResources(result, parent, parent.getNonJavaResources(), filters);
}
private void collect(List result, IPackageFragment parent, ViewerFilter[] filters) throws CoreException {
ICompilationUnit[] units= parent.getCompilationUnits();
for (int i= 0; i < units.length; i++) {
ICompilationUnit unit= units[i];
if (isVisible(parent, unit, filters))
result.add(unit.getUnderlyingResource());
}
handleResources(result, parent, parent.getNonJavaResources(), filters);
}
private void handleResources(List result, Object parent, Object[] resources, ViewerFilter[] filters) {
for (int i= 0; i < resources.length; i++) {
Object object= resources[i];
if (isVisible(parent, object, filters) && object instanceof IResource) {
result.add(object);
}
}
}
private boolean isVisible(Object parent, Object element, ViewerFilter[] filters) {
for (int i= 0; i < filters.length; i++) {
ViewerFilter filter= filters[i];
if (!filter.select(fViewer, parent, element))
return false;
}
return true;
}
}
|
31,285 |
Bug 31285 renaming of source folder leaves "Missing source folder <new folder name>" marker
|
- autobuild is off - the folder is neither ready-only nor derived - the marker disappears on the next 'build' my guess from our discussion is that first the folder gets added to the classpath with its new name and only then the folder is renamed (instead of the other way arround)
|
resolved fixed
|
19c1137
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:09:45Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,285 |
Bug 31285 renaming of source folder leaves "Missing source folder <new folder name>" marker
|
- autobuild is off - the folder is neither ready-only nor derived - the marker disappears on the next 'build' my guess from our discussion is that first the folder gets added to the classpath with its new name and only then the folder is renamed (instead of the other way arround)
|
resolved fixed
|
19c1137
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:09:45Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/RenameSourceFolderChange.java
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
org.eclipse.jdt.ui/core
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
org.eclipse.jdt.ui/core
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
org.eclipse.jdt.ui/core
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContext.java
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
org.eclipse.jdt.ui/core
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
extension/org/eclipse/jdt/internal/corext/template/java/CodeTemplateContextType.java
| |
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/javadoc/JavaDocAutoIndentStrategy.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.text.javadoc;
import java.text.BreakIterator;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultAutoIndentStrategy;
import org.eclipse.jface.text.DocumentCommand;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.TextUtilities;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationMessages;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.Strings;
import org.eclipse.jdt.internal.corext.util.SuperTypeHierarchyCache;
import org.eclipse.jdt.internal.ui.JavaPlugin;
/**
* Auto indent strategy for java doc comments
*/
public class JavaDocAutoIndentStrategy extends DefaultAutoIndentStrategy {
public JavaDocAutoIndentStrategy() {
}
private static String getLineDelimiter(IDocument document) {
try {
if (document.getNumberOfLines() > 1)
return document.getLineDelimiter(0);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
return System.getProperty("line.separator"); //$NON-NLS-1$
}
/**
* Copies the indentation of the previous line and add a star.
* If the javadoc just started on this line add standard method tags
* and close the javadoc.
*
* @param d the document to work on
* @param c the command to deal with
*/
private void jdocIndentAfterNewLine(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
try {
// find start of line
int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset);
IRegion info= d.getLineInformationOfOffset(p);
int start= info.getOffset();
// find white spaces
int end= findEndOfWhiteSpace(d, start, c.offset);
StringBuffer buf= new StringBuffer(c.text);
if (end >= start) { // 1GEYL1R: ITPJUI:ALL - java doc edit smartness not work for class comments
// append to input
String indentation= jdocExtractLinePrefix(d, d.getLineOfOffset(c.offset));
buf.append(indentation);
if (end < c.offset) {
if (d.getChar(end) == '/') {
// javadoc started on this line
buf.append(" * "); //$NON-NLS-1$
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_CLOSE_JAVADOCS) &&
isNewComment(d, c.offset))
{
String lineDelimiter= getLineDelimiter(d);
c.doit= false;
d.replace(c.offset, 0, lineDelimiter + indentation + " */"); //$NON-NLS-1$
// evaluate method signature
ICompilationUnit unit= getCompilationUnit();
if (JavaPlugin.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS) &&
unit != null)
{
try {
unit.reconcile();
String string= createJavaDocTags(d, c, indentation, lineDelimiter, unit);
if (string != null)
d.replace(c.offset, 0, string);
} catch (CoreException e) {
// ignore
}
}
}
}
}
}
c.text= buf.toString();
} catch (BadLocationException excp) {
// stop work
}
}
private String createJavaDocTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, ICompilationUnit unit)
throws CoreException, BadLocationException
{
IJavaElement element= unit.getElementAt(command.offset);
if (element == null)
return null;
switch (element.getElementType()) {
case IJavaElement.TYPE:
return createTypeTags(document, command, indentation, lineDelimiter, (IType) element);
case IJavaElement.METHOD:
return createMethodTags(document, command, indentation, lineDelimiter, (IMethod) element);
default:
return null;
}
}
/*
* Removes start and end of a comment and corrects indentation and line delimiters.
*/
private String prepareTemplateComment(String comment, String indentation, String lineDelimiter) {
// trim comment start and end if any
if (comment.endsWith("*/")) //$NON-NLS-1$
comment= comment.substring(0, comment.length() - 2);
comment= comment.trim();
if (comment.startsWith("/*")) { //$NON-NLS-1$
if (comment.length() > 2 && comment.charAt(2) == '*') {
comment= comment.substring(3); // remove '/**'
} else {
comment= comment.substring(2); // remove '/*'
}
}
return Strings.changeIndent(comment, 0, CodeFormatterUtil.getTabWidth(), indentation, lineDelimiter);
}
private String createTypeTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IType type)
throws CoreException, BadLocationException
{
String comment= StubUtility.getTypeComment(type.getCompilationUnit(), type.getElementName());
if (comment != null) {
comment= prepareTemplateComment(comment.trim(), indentation, lineDelimiter);
}
return (comment == null || comment.length() == 0)
? CodeGenerationMessages.getString("AddJavaDocStubOperation.configure.message") //$NON-NLS-1$
: comment;
}
private String createMethodTags(IDocument document, DocumentCommand command, String indentation, String lineDelimiter, IMethod method)
throws CoreException, BadLocationException
{
IRegion partition= document.getPartition(command.offset);
ISourceRange sourceRange= method.getSourceRange();
if (sourceRange == null || sourceRange.getOffset() != partition.getOffset())
return null;
IMethod inheritedMethod= getInheritedMethod(method);
String comment= StubUtility.getMethodComment(method, inheritedMethod);
if (comment != null) {
comment= comment.trim();
boolean javadocComment= comment.startsWith("/**"); //$NON-NLS-1$
boolean isJavaDoc= partition.getLength() >= 3 && document.get(partition.getOffset(), 3).equals("/**"); //$NON-NLS-1$
if (javadocComment == isJavaDoc) {
return prepareTemplateComment(comment, indentation, lineDelimiter);
}
}
return null;
}
/**
* Returns the method inherited from, <code>null</code> if method is newly defined.
*/
private static IMethod getInheritedMethod(IMethod method) throws JavaModelException {
IType declaringType= method.getDeclaringType();
ITypeHierarchy typeHierarchy= SuperTypeHierarchyCache.getTypeHierarchy(declaringType);
return JavaModelUtil.findMethodDeclarationInHierarchy(typeHierarchy, declaringType,
method.getElementName(), method.getParameterTypes(), method.isConstructor());
}
protected void jdocIndentForCommentEnd(IDocument d, DocumentCommand c) {
if (c.offset < 2 || d.getLength() == 0) {
return;
}
try {
if ("* ".equals(d.get(c.offset - 2, 2))) { //$NON-NLS-1$
// modify document command
c.length++;
c.offset--;
}
} catch (BadLocationException excp) {
// stop work
}
}
/**
* Guesses if the command operates within a newly created javadoc comment or not.
* If in doubt, it will assume that the javadoc is new.
*/
private static boolean isNewComment(IDocument document, int commandOffset) {
try {
int lineIndex= document.getLineOfOffset(commandOffset) + 1;
if (lineIndex >= document.getNumberOfLines())
return true;
IRegion line= document.getLineInformation(lineIndex);
ITypedRegion partition= document.getPartition(commandOffset);
if (document.getLineOffset(lineIndex) >= partition.getOffset() + partition.getLength())
return true;
String string= document.get(line.getOffset(), line.getLength());
if (!string.trim().startsWith("*")) //$NON-NLS-1$
return true;
return false;
} catch (BadLocationException e) {
return false;
}
}
/*
* @see IAutoIndentStrategy#customizeDocumentCommand
*/
public void customizeDocumentCommand(IDocument document, DocumentCommand command) {
try {
if (command.text != null && command.length == 0) {
String[] lineDelimiters= document.getLegalLineDelimiters();
int index= TextUtilities.endsWith(lineDelimiters, command.text);
if (index > -1) {
// ends with line delimiter
if (lineDelimiters[index].equals(command.text))
// just the line delimiter
jdocIndentAfterNewLine(document, command);
return;
}
}
if (command.text != null && command.text.equals("/")) { //$NON-NLS-1$
jdocIndentForCommentEnd(document, command);
return;
}
ITypedRegion partition= document.getPartition(command.offset);
int partitionStart= partition.getOffset();
int partitionEnd= partition.getLength() + partitionStart;
String text= command.text;
int offset= command.offset;
int length= command.length;
// partition change
final int PREFIX_LENGTH= "/*".length(); //$NON-NLS-1$
final int POSTFIX_LENGTH= "*/".length(); //$NON-NLS-1$
if ((offset < partitionStart + PREFIX_LENGTH || offset + length > partitionEnd - POSTFIX_LENGTH) ||
text != null && text.length() >= 2 && ((text.indexOf("*/") != -1) || (document.getChar(offset) == '*' && text.startsWith("/")))) //$NON-NLS-1$ //$NON-NLS-2$
return;
if (command.text == null || command.text.length() == 0)
jdocHandleBackspaceDelete(document, command);
else if (command.text != null && command.length == 0 && command.text.length() > 0)
jdocWrapParagraphOnInsert(document, command);
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
private void flushCommand(IDocument document, DocumentCommand command) throws BadLocationException {
if (!command.doit)
return;
document.replace(command.offset, command.length, command.text);
command.doit= false;
if (command.text != null)
command.offset += command.text.length();
command.length= 0;
command.text= null;
}
protected void jdocWrapParagraphOnInsert(IDocument document, DocumentCommand command) throws BadLocationException {
// Assert.isTrue(command.length == 0);
// Assert.isTrue(command.text != null && command.text.length() == 1);
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS))
return;
int line= document.getLineOfOffset(command.offset);
IRegion region= document.getLineInformation(line);
int lineOffset= region.getOffset();
int lineLength= region.getLength();
String lineContents= document.get(lineOffset, lineLength);
StringBuffer buffer= new StringBuffer(lineContents);
int start= command.offset - lineOffset;
int end= command.length + start;
buffer.replace(start, end, command.text);
// handle whitespace
if (command.text != null && command.text.length() != 0 && command.text.trim().length() == 0) {
String endOfLine= document.get(command.offset, lineOffset + lineLength - command.offset);
// end of line
if (endOfLine.length() == 0) {
// move caret to next line
flushCommand(document, command);
if (isLineTooShort(document, line)) {
int[] caretOffset= {command.offset};
jdocWrapParagraphFromLine(document, line, caretOffset, false);
command.offset= caretOffset[0];
return;
}
// move caret to next line if possible
if (line < document.getNumberOfLines() - 1 && isJavaDocLine(document, line + 1)) {
String lineDelimiter= document.getLineDelimiter(line);
String nextLinePrefix= jdocExtractLinePrefix(document, line + 1);
command.offset += lineDelimiter.length() + nextLinePrefix.length();
}
return;
// inside whitespace at end of line
} else if (endOfLine.trim().length() == 0) {
// simply insert space
return;
}
}
// change in prefix region
String prefix= jdocExtractLinePrefix(document, line);
boolean wrapAlways= command.offset >= lineOffset && command.offset <= lineOffset + prefix.length();
// must insert the text now because it may include whitepace
flushCommand(document, command);
if (wrapAlways || calculateDisplayedWidth(buffer.toString()) > getMargin() || isLineTooShort(document, line)) {
int[] caretOffset= {command.offset};
jdocWrapParagraphFromLine(document, line, caretOffset, wrapAlways);
if (!wrapAlways)
command.offset= caretOffset[0];
}
}
/**
* Method jdocWrapParagraphFromLine.
*
* @param document
* @param line
* @param always
*/
private void jdocWrapParagraphFromLine(IDocument document, int line, int[] caretOffset, boolean always) throws BadLocationException {
String indent= jdocExtractLinePrefix(document, line);
if (!always) {
if (!indent.trim().startsWith("*")) //$NON-NLS-1$
return;
if (indent.trim().startsWith("*/")) //$NON-NLS-1$
return;
if (!isLineTooLong(document, line) && !isLineTooShort(document, line))
return;
}
boolean caretRelativeToParagraphOffset= false;
int caret= caretOffset[0];
int caretLine= document.getLineOfOffset(caret);
int lineOffset= document.getLineOffset(line);
int paragraphOffset= lineOffset + indent.length();
if (paragraphOffset < caret) {
caret -= paragraphOffset;
caretRelativeToParagraphOffset= true;
} else {
caret -= lineOffset;
}
StringBuffer buffer= new StringBuffer();
int currentLine= line;
while (line == currentLine || isJavaDocLine(document, currentLine)) {
if (buffer.length() != 0 && !Character.isWhitespace(buffer.charAt(buffer.length() - 1))) {
buffer.append(' ');
if (currentLine <= caretLine) {
// in this case caretRelativeToParagraphOffset is always true
++caret;
}
}
String string= getLineContents(document, currentLine);
buffer.append(string);
currentLine++;
}
String paragraph= buffer.toString();
if (paragraph.trim().length() == 0)
return;
caretOffset[0]= caretRelativeToParagraphOffset ? caret : 0;
String delimiter= document.getLineDelimiter(0);
String wrapped= formatParagraph(paragraph, caretOffset, indent, delimiter, getMargin());
int beginning= document.getLineOffset(line);
int end= document.getLineOffset(currentLine);
document.replace(beginning, end - beginning, wrapped.toString());
caretOffset[0]= caretRelativeToParagraphOffset ? caretOffset[0] + beginning : caret + beginning;
}
/**
* Line break iterator to handle whitespaces as first class citizens.
*/
private static class LineBreakIterator {
private final String fString;
private final BreakIterator fIterator= BreakIterator.getLineInstance();
private int fStart;
private int fEnd;
private int fBufferedEnd;
public LineBreakIterator(String string) {
fString= string;
fIterator.setText(string);
}
public int first() {
fBufferedEnd= -1;
fStart= fIterator.first();
return fStart;
}
public int next() {
if (fBufferedEnd != -1) {
fStart= fEnd;
fEnd= fBufferedEnd;
fBufferedEnd= -1;
return fEnd;
}
fStart= fEnd;
fEnd= fIterator.next();
if (fEnd == BreakIterator.DONE)
return fEnd;
final String string= fString.substring(fStart, fEnd);
// whitespace
if (string.trim().length() == 0)
return fEnd;
final String word= string.trim();
if (word.length() == string.length())
return fEnd;
// suspected whitespace
fBufferedEnd= fEnd;
return fStart + word.length();
}
};
/**
* Formats a paragraph, using break iterator.
*
* @param offset an offset within the paragraph, which will be updated with respect to formatting.
*/
private static String formatParagraph(String paragraph, int[] offset, String prefix, String lineDelimiter, int margin) {
LineBreakIterator iterator= new LineBreakIterator(paragraph);
StringBuffer paragraphBuffer= new StringBuffer();
StringBuffer lineBuffer= new StringBuffer();
StringBuffer whiteSpaceBuffer= new StringBuffer();
int index= offset[0];
int indexBuffer= -1;
for (int start= iterator.first(), end= iterator.next(); end != BreakIterator.DONE; start= end, end= iterator.next()) {
String word= paragraph.substring(start, end);
// word is whitespace
if (word.trim().length() == 0) {
whiteSpaceBuffer.append(word);
// first word of line is always appended
} else if (lineBuffer.length() == 0) {
lineBuffer.append(prefix);
lineBuffer.append(whiteSpaceBuffer.toString());
lineBuffer.append(word);
} else {
String line= lineBuffer.toString() + whiteSpaceBuffer.toString() + word.toString();
// margin exceeded
if (calculateDisplayedWidth(line) > margin) {
// flush line buffer and wrap paragraph
paragraphBuffer.append(lineBuffer.toString());
paragraphBuffer.append(lineDelimiter);
lineBuffer.setLength(0);
lineBuffer.append(prefix);
lineBuffer.append(word);
// flush index buffer
if (indexBuffer != -1) {
offset[0]= indexBuffer;
// correct for caret in whitespace at the end of line
if (whiteSpaceBuffer.length() != 0 && index < start && index >= start - whiteSpaceBuffer.length())
offset[0] -= (index - (start - whiteSpaceBuffer.length()));
indexBuffer= -1;
}
whiteSpaceBuffer.setLength(0);
// margin not exceeded
} else {
lineBuffer.append(whiteSpaceBuffer.toString());
lineBuffer.append(word);
whiteSpaceBuffer.setLength(0);
}
}
if (index >= start && index < end) {
indexBuffer= paragraphBuffer.length() + lineBuffer.length() + (index - start);
if (word.trim().length() != 0)
indexBuffer -= word.length();
}
}
// flush line buffer
paragraphBuffer.append(lineBuffer.toString());
paragraphBuffer.append(lineDelimiter);
// flush index buffer
if (indexBuffer != -1)
offset[0]= indexBuffer;
// last position is not returned by break iterator
else if (offset[0] == paragraph.length())
offset[0]= paragraphBuffer.length() - lineDelimiter.length();
return paragraphBuffer.toString();
}
private static IPreferenceStore getPreferenceStore() {
return JavaPlugin.getDefault().getPreferenceStore();
}
/**
* Returns the displayed width of a string, taking in account the displayed tab width.
* The result can be compared against the print margin.
*/
private static int calculateDisplayedWidth(String string) {
final int tabWidth= getPreferenceStore().getInt(PreferenceConstants.EDITOR_TAB_WIDTH);
int column= 0;
for (int i= 0; i < string.length(); i++)
if ('\t' == string.charAt(i))
column += tabWidth - (column % tabWidth);
else
column++;
return column;
}
private String jdocExtractLinePrefix(IDocument d, int line) throws BadLocationException {
IRegion region= d.getLineInformation(line);
int lineOffset= region.getOffset();
int index= findEndOfWhiteSpace(d, lineOffset, lineOffset + d.getLineLength(line));
if (d.getChar(index) == '*') {
index++;
if (index != lineOffset + region.getLength() &&d.getChar(index) == ' ')
index++;
}
return d.get(lineOffset, index - lineOffset);
}
private String getLineContents(IDocument d, int line) throws BadLocationException {
int offset = d.getLineOffset(line);
int length = d.getLineLength(line) - d.getLineDelimiter(line).length();
String lineContents = d.get(offset, length);
int trim = jdocExtractLinePrefix(d, line).length();
return lineContents.substring(trim);
}
private static String getLine(IDocument document, int line) throws BadLocationException {
IRegion region= document.getLineInformation(line);
return document.get(region.getOffset(), region.getLength());
}
/**
* Returns <code>true</code> if the javadoc line is too short, <code>false</code> otherwise.
*/
private boolean isLineTooShort(IDocument document, int line) throws BadLocationException {
if (!isJavaDocLine(document, line + 1))
return false;
String nextLine= getLineContents(document, line + 1);
if (nextLine.trim().length() == 0)
return false;
return true;
}
/**
* Returns <code>true</code> if the line is too long, <code>false</code> otherwise.
*/
private boolean isLineTooLong(IDocument document, int line) throws BadLocationException {
String lineContents= getLine(document, line);
return calculateDisplayedWidth(lineContents) > getMargin();
}
private static int getMargin() {
return getPreferenceStore().getInt(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN);
}
private static final String[] fgInlineTags= {
"<b>", "<i>", "<em>", "<strong>", "<code>" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
};
private boolean isInlineTag(String string) {
for (int i= 0; i < fgInlineTags.length; i++)
if (string.startsWith(fgInlineTags[i]))
return true;
return false;
}
/**
* returns true if the specified line is part of a paragraph and should be merged with
* the previous line.
*/
private boolean isJavaDocLine(IDocument document, int line) throws BadLocationException {
if (document.getNumberOfLines() < line)
return false;
int offset= document.getLineOffset(line);
int length= document.getLineLength(line);
int firstChar= findEndOfWhiteSpace(document, offset, offset + length);
length -= firstChar - offset;
String lineContents= document.get(firstChar, length);
String prefix= lineContents.trim();
if (!prefix.startsWith("*") || prefix.startsWith("*/")) //$NON-NLS-1$ //$NON-NLS-2$
return false;
lineContents= lineContents.substring(1).trim().toLowerCase();
// preserve empty lines
if (lineContents.length() == 0)
return false;
// preserve @TAGS
if (lineContents.startsWith("@")) //$NON-NLS-1$
return false;
// preserve HTML tags which are not inline
if (lineContents.startsWith("<") && !isInlineTag(lineContents)) //$NON-NLS-1$
return false;
return true;
}
protected void jdocHandleBackspaceDelete(IDocument document, DocumentCommand c) {
if (!getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_FORMAT_JAVADOCS))
return;
try {
String text= document.get(c.offset, c.length);
int line= document.getLineOfOffset(c.offset);
int lineOffset= document.getLineOffset(line);
// erase line delimiter
String lineDelimiter= document.getLineDelimiter(line);
if (lineDelimiter != null && lineDelimiter.equals(text)) {
String prefix= jdocExtractLinePrefix(document, line + 1);
// strip prefix if any
if (prefix.length() > 0) {
int length= document.getLineDelimiter(line).length() + prefix.length();
document.replace(c.offset, length, null);
c.doit= false;
c.length= 0;
return;
}
// backspace: beginning of a javadoc line
} else if (document.getChar(c.offset - 1) == '*' && jdocExtractLinePrefix(document, line).length() - 1 >= c.offset - lineOffset) {
lineDelimiter= document.getLineDelimiter(line - 1);
String prefix= jdocExtractLinePrefix(document, line);
int length= (lineDelimiter != null ? lineDelimiter.length() : 0) + prefix.length();
document.replace(c.offset - length + 1, length, null);
c.doit= false;
c.offset -= length - 1;
c.length= 0;
return;
} else {
document.replace(c.offset, c.length, null);
c.doit= false;
c.length= 0;
}
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
try {
int line= document.getLineOfOffset(c.offset);
int lineOffset= document.getLineOffset(line);
String prefix= jdocExtractLinePrefix(document, line);
boolean always= c.offset > lineOffset && c.offset <= lineOffset + prefix.length();
int[] caretOffset= {c.offset};
jdocWrapParagraphFromLine(document, document.getLineOfOffset(c.offset), caretOffset, always);
c.offset= caretOffset[0];
} catch (BadLocationException e) {
JavaPlugin.log(e);
}
}
/**
* Returns the compilation unit of the CompilationUnitEditor invoking the AutoIndentStrategy,
* might return <code>null</code> on error.
*/
private static ICompilationUnit getCompilationUnit() {
IWorkbenchWindow window= PlatformUI.getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
IWorkbenchPage page= window.getActivePage();
if (page == null)
return null;
IEditorPart editor= page.getActiveEditor();
if (editor == null)
return null;
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit unit= manager.getWorkingCopy(editor.getEditorInput());
if (unit == null)
return null;
return unit;
}
}
|
21,183 |
Bug 21183 Class javadoc created during "New Class" operation doesn't fill in variables properly [javadoc] [code manipulation]
|
If you use the enclosing_type variable in your javadoc comment template, it is not properly filled in when you make a new class (using the New Class dialog). Probably the class should be created, then after creating and saving, javadoc should be added. I suspect the variables don't have valid values yet at the time the javadoc is prepended to the class.
|
resolved fixed
|
0d95509
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:23:40Z | 2002-07-02T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
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.ToolFactory;
import org.eclipse.jdt.core.compiler.IScanner;
import org.eclipse.jdt.core.compiler.ITerminalSymbols;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.template.CodeTemplates;
import org.eclipse.jdt.internal.corext.template.Template;
import org.eclipse.jdt.internal.corext.template.Templates;
import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContext;
import org.eclipse.jdt.internal.corext.template.java.CodeTemplateContextType;
import org.eclipse.jdt.internal.corext.template.java.JavaContext;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.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;
/**
* The class <code>NewTypeWizardPage</code> contains controls and validation routines
* for a 'New Type WizardPage'. Implementors decide which components to add and to enable.
* Implementors can also customize the validation code. <code>NewTypeWizardPage</code>
* is intended to serve as base class of all wizards that create types like applets, servlets, classes,
* interfaces, etc.
* <p>
* See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an
* example usage of <code>NewTypeWizardPage</code>.
* </p>
*
* @see org.eclipse.jdt.ui.wizards.NewClassWizardPage
* @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage
*
* @since 2.0
*/
public abstract class NewTypeWizardPage extends NewContainerWizardPage {
/**
* Class used in stub creation routines to add needed imports to a
* compilation unit.
*/
public static class ImportsManager {
private IImportsStructure fImportsStructure;
/* package */ ImportsManager(IImportsStructure structure) {
fImportsStructure= structure;
}
/* package */ IImportsStructure getImportsStructure() {
return fImportsStructure;
}
/**
* Adds a new import declaration that is sorted in the existing imports.
* If an import already exists or the import would conflict with another import
* of an other type with the same simple name the import is not added.
*
* @param qualifiedTypeName The fully qualified name of the type to import
* (dot separated)
* @return Returns the simple type name that can be used in the code or the
* fully qualified type name if an import conflict prevented the import
*/
public String addImport(String qualifiedTypeName) {
return fImportsStructure.addImport(qualifiedTypeName);
}
}
/** Public access flag. See The Java Virtual Machine Specification for more details. */
public int F_PUBLIC = Flags.AccPublic;
/** Private access flag. See The Java Virtual Machine Specification for more details. */
public int F_PRIVATE = Flags.AccPrivate;
/** Protected access flag. See The Java Virtual Machine Specification for more details. */
public int F_PROTECTED = Flags.AccProtected;
/** Static access flag. See The Java Virtual Machine Specification for more details. */
public int F_STATIC = Flags.AccStatic;
/** Final access flag. See The Java Virtual Machine Specification for more details. */
public int F_FINAL = Flags.AccFinal;
/** Abstract property flag. See The Java Virtual Machine Specification for more details. */
public int F_ABSTRACT = Flags.AccAbstract;
private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$
/** Field ID of the package input field */
protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$
/** Field ID of the eclosing type input field */
protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$
/** Field ID of the enclosing type checkbox */
protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$
/** Field ID of the type name input field */
protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$
/** Field ID of the super type input field */
protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$
/** Field ID of the super interfaces input field */
protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$
/** Field ID of the modifier checkboxes */
protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$
/** Field ID of the method stubs checkboxes */
protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$
private class InterfacesListLabelProvider extends LabelProvider {
private Image fInterfaceImage;
public InterfacesListLabelProvider() {
super();
fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE);
}
public Image getImage(Object element) {
return fInterfaceImage;
}
}
private StringButtonStatusDialogField fPackageDialogField;
private SelectionButtonDialogField fEnclosingTypeSelection;
private StringButtonDialogField fEnclosingTypeDialogField;
private boolean fCanModifyPackage;
private boolean fCanModifyEnclosingType;
private IPackageFragment fCurrPackage;
private IType fCurrEnclosingType;
private StringDialogField fTypeNameDialogField;
private StringButtonDialogField fSuperClassDialogField;
private ListDialogField fSuperInterfacesDialogField;
private IType fSuperClass;
private SelectionButtonDialogFieldGroup fAccMdfButtons;
private SelectionButtonDialogFieldGroup fOtherMdfButtons;
private IType fCreatedType;
protected IStatus fEnclosingTypeStatus;
protected IStatus fPackageStatus;
protected IStatus fTypeNameStatus;
protected IStatus fSuperClassStatus;
protected IStatus fModifierStatus;
protected IStatus fSuperInterfacesStatus;
private boolean fIsClass;
private int fStaticMdfIndex;
private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3;
private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1;
/**
* Creates a new <code>NewTypeWizardPage</code>
*
* @param isClass <code>true</code> if a new class is to be created; otherwise
* an interface is to be created
* @param pageName the wizard page's name
*/
public NewTypeWizardPage(boolean isClass, String pageName) {
super(pageName);
fCreatedType= null;
fIsClass= isClass;
TypeFieldsAdapter adapter= new TypeFieldsAdapter();
fPackageDialogField= new StringButtonStatusDialogField(adapter);
fPackageDialogField.setDialogFieldListener(adapter);
fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$
fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$
fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK);
fEnclosingTypeSelection.setDialogFieldListener(adapter);
fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$
fEnclosingTypeDialogField= new StringButtonDialogField(adapter);
fEnclosingTypeDialogField.setDialogFieldListener(adapter);
fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$
fTypeNameDialogField= new StringDialogField();
fTypeNameDialogField.setDialogFieldListener(adapter);
fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$
fSuperClassDialogField= new StringButtonDialogField(adapter);
fSuperClassDialogField.setDialogFieldListener(adapter);
fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$
fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$
String[] addButtons= new String[] {
/* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$
/* 1 */ null,
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$
};
fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider());
fSuperInterfacesDialogField.setDialogFieldListener(adapter);
String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$
fSuperInterfacesDialogField.setLabelText(interfaceLabel);
fSuperInterfacesDialogField.setRemoveButtonIndex(2);
String[] buttonNames1= new String[] {
/* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$
/* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$
/* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$
/* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$
};
fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4);
fAccMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$
fAccMdfButtons.setSelection(0, true);
String[] buttonNames2;
if (fIsClass) {
buttonNames2= new String[] {
/* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$
/* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$
/* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 2; // index of the static checkbox is 2
} else {
buttonNames2= new String[] {
NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$
};
fStaticMdfIndex= 0; // index of the static checkbox is 0
}
fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4);
fOtherMdfButtons.setDialogFieldListener(adapter);
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false);
fPackageStatus= new StatusInfo();
fEnclosingTypeStatus= new StatusInfo();
fCanModifyPackage= true;
fCanModifyEnclosingType= true;
updateEnableState();
fTypeNameStatus= new StatusInfo();
fSuperClassStatus= new StatusInfo();
fSuperInterfacesStatus= new StatusInfo();
fModifierStatus= new StatusInfo();
}
/**
* Initializes all fields provided by the page with a given selection.
*
* @param elem the selection used to intialize this page or <code>
* null</code> if no selection was available
*/
protected void initTypePage(IJavaElement elem) {
String initSuperclass= "java.lang.Object"; //$NON-NLS-1$
ArrayList initSuperinterfaces= new ArrayList(5);
IPackageFragment pack= null;
IType enclosingType= null;
if (elem != null) {
// evaluate the enclosing type
pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT);
IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE);
if (typeInCU != null) {
if (typeInCU.getCompilationUnit() != null) {
enclosingType= typeInCU;
}
} else {
ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
enclosingType= cu.findPrimaryType();
}
}
try {
IType type= null;
if (elem.getElementType() == IJavaElement.TYPE) {
type= (IType)elem;
if (type.exists()) {
String superName= JavaModelUtil.getFullyQualifiedName(type);
if (type.isInterface()) {
initSuperinterfaces.add(superName);
} else {
initSuperclass= superName;
}
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// ignore this exception now
}
}
setPackageFragment(pack, true);
setEnclosingType(enclosingType, true);
setEnclosingTypeSelection(false, true);
setTypeName("", true); //$NON-NLS-1$
setSuperClass(initSuperclass, true);
setSuperInterfaces(initSuperinterfaces, true);
}
// -------- UI Creation ---------
/**
* Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSeparator(Composite composite, int nColumns) {
(new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1));
}
/**
* Creates the controls for the package name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createPackageControls(Composite composite, int nColumns) {
fPackageDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth());
LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null));
}
/**
* Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at
* least 4 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createEnclosingTypeControls(Composite composite, int nColumns) {
// #6891
Composite tabGroup= new Composite(composite, SWT.NONE);
GridLayout layout= new GridLayout();
layout.marginWidth= 0;
layout.marginHeight= 0;
tabGroup.setLayout(layout);
fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1);
Control c= fEnclosingTypeDialogField.getTextControl(composite);
GridData gd= new GridData(GridData.FILL_HORIZONTAL);
gd.widthHint= getMaxFieldWidth();
gd.horizontalSpan= 2;
c.setLayoutData(gd);
Button button= fEnclosingTypeDialogField.getChangeControl(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.heightHint = SWTUtil.getButtonHeigthHint(button);
gd.widthHint = SWTUtil.getButtonWidthHint(button);
button.setLayoutData(gd);
}
/**
* Creates the controls for the type name field. Expects a <code>GridLayout</code> with at
* least 2 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createTypeNameControls(Composite composite, int nColumns) {
fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1);
DialogField.createEmptySpace(composite);
LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the modifiers radio/ceckbox buttons. Expects a
* <code>GridLayout</code> with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createModifierControls(Composite composite, int nColumns) {
LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1);
Control control= fAccMdfButtons.getSelectionButtonsGroup(composite);
GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
DialogField.createEmptySpace(composite);
control= fOtherMdfButtons.getSelectionButtonsGroup(composite);
gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
gd.horizontalSpan= nColumns - 2;
control.setLayoutData(gd);
DialogField.createEmptySpace(composite);
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code>
* with at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperClassControls(Composite composite, int nColumns) {
fSuperClassDialogField.doFillIntoGrid(composite, nColumns);
LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth());
}
/**
* Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with
* at least 3 columns.
*
* @param composite the parent composite
* @param nColumns number of columns to span
*/
protected void createSuperInterfacesControls(Composite composite, int nColumns) {
fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns);
GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData();
if (fIsClass) {
gd.heightHint= convertHeightInCharsToPixels(3);
} else {
gd.heightHint= convertHeightInCharsToPixels(6);
}
gd.grabExcessVerticalSpace= false;
gd.widthHint= getMaxFieldWidth();
}
/**
* Sets the focus on the type name input field.
*/
protected void setFocus() {
fTypeNameDialogField.setFocus();
}
// -------- TypeFieldsAdapter --------
private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter {
// -------- IStringButtonAdapter
public void changeControlPressed(DialogField field) {
typePageChangeControlPressed(field);
}
// -------- IListAdapter
public void customButtonPressed(ListDialogField field, int index) {
typePageCustomButtonPressed(field, index);
}
public void selectionChanged(ListDialogField field) {}
// -------- IDialogFieldListener
public void dialogFieldChanged(DialogField field) {
typePageDialogFieldChanged(field);
}
public void doubleClicked(ListDialogField field) {
}
}
private void typePageChangeControlPressed(DialogField field) {
if (field == fPackageDialogField) {
IPackageFragment pack= choosePackage();
if (pack != null) {
fPackageDialogField.setText(pack.getElementName());
}
} else if (field == fEnclosingTypeDialogField) {
IType type= chooseEnclosingType();
if (type != null) {
fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
} else if (field == fSuperClassDialogField) {
IType type= chooseSuperType();
if (type != null) {
fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type));
}
}
}
private void typePageCustomButtonPressed(DialogField field, int index) {
if (field == fSuperInterfacesDialogField) {
chooseSuperInterfaces();
}
}
/*
* A field on the type has changed. The fields' status and all dependend
* status are updated.
*/
private void typePageDialogFieldChanged(DialogField field) {
String fieldName= null;
if (field == fPackageDialogField) {
fPackageStatus= packageChanged();
updatePackageStatusLabel();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= PACKAGE;
} else if (field == fEnclosingTypeDialogField) {
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSING;
} else if (field == fEnclosingTypeSelection) {
updateEnableState();
boolean isEnclosedType= isEnclosingTypeSelected();
if (!isEnclosedType) {
if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, false);
fAccMdfButtons.setSelection(PROTECTED_INDEX, false);
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, false);
}
}
fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass);
fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass);
fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType);
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fieldName= ENCLOSINGSELECTION;
} else if (field == fTypeNameDialogField) {
fTypeNameStatus= typeNameChanged();
fieldName= TYPENAME;
} else if (field == fSuperClassDialogField) {
fSuperClassStatus= superClassChanged();
fieldName= SUPER;
} else if (field == fSuperInterfacesDialogField) {
fSuperInterfacesStatus= superInterfacesChanged();
fieldName= INTERFACES;
} else if (field == fOtherMdfButtons) {
fModifierStatus= modifiersChanged();
fieldName= MODIFIERS;
} else {
fieldName= METHODS;
}
// tell all others
handleFieldChanged(fieldName);
}
// -------- update message ----------------
/*
* @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String)
*/
protected void handleFieldChanged(String fieldName) {
super.handleFieldChanged(fieldName);
if (fieldName == CONTAINER) {
fPackageStatus= packageChanged();
fEnclosingTypeStatus= enclosingTypeChanged();
fTypeNameStatus= typeNameChanged();
fSuperClassStatus= superClassChanged();
fSuperInterfacesStatus= superInterfacesChanged();
}
}
// ---- set / get ----------------
/**
* Returns the text of the package input field.
*
* @return the text of the package input field
*/
public String getPackageText() {
return fPackageDialogField.getText();
}
/**
* Returns the text of the enclosing type input field.
*
* @return the text of the enclosing type input field
*/
public String getEnclosingTypeText() {
return fEnclosingTypeDialogField.getText();
}
/**
* Returns the package fragment corresponding to the current input.
*
* @return a package fragement or <code>null</code> if the input
* could not be resolved.
*/
public IPackageFragment getPackageFragment() {
if (!isEnclosingTypeSelected()) {
return fCurrPackage;
} else {
if (fCurrEnclosingType != null) {
return fCurrEnclosingType.getPackageFragment();
}
}
return null;
}
/**
* Sets the package fragment to the given value. The method updates the model
* and the text of the control.
*
* @param pack the package fragement to be set
* @param canBeModified if <code>true</code> the package fragment is
* editable; otherwise it is read-only.
*/
public void setPackageFragment(IPackageFragment pack, boolean canBeModified) {
fCurrPackage= pack;
fCanModifyPackage= canBeModified;
String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$
fPackageDialogField.setText(str);
updateEnableState();
}
/**
* Returns the enclosing type corresponding to the current input.
*
* @return the enclosing type or <code>null</code> if the enclosing type is
* not selected or the input could not be resolved
*/
public IType getEnclosingType() {
if (isEnclosingTypeSelected()) {
return fCurrEnclosingType;
}
return null;
}
/**
* Sets the enclosing type. The method updates the underlying model
* and the text of the control.
*
* @param type the enclosing type
* @param canBeModified if <code>true</code> the enclosing type field is
* editable; otherwise it is read-only.
*/
public void setEnclosingType(IType type, boolean canBeModified) {
fCurrEnclosingType= type;
fCanModifyEnclosingType= canBeModified;
String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$
fEnclosingTypeDialogField.setText(str);
updateEnableState();
}
/**
* Returns the selection state of the enclosing type checkbox.
*
* @return the seleciton state of the enclosing type checkbox
*/
public boolean isEnclosingTypeSelected() {
return fEnclosingTypeSelection.isSelected();
}
/**
* Sets the enclosing type checkbox's selection state.
*
* @param isSelected the checkbox's selection state
* @param canBeModified if <code>true</code> the enclosing type checkbox is
* modifiable; otherwise it is read-only.
*/
public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) {
fEnclosingTypeSelection.setSelection(isSelected);
fEnclosingTypeSelection.setEnabled(canBeModified);
updateEnableState();
}
/**
* Returns the type name entered into the type input field.
*
* @return the type name
*/
public String getTypeName() {
return fTypeNameDialogField.getText();
}
/**
* Sets the type name input field's text to the given value. Method doesn't update
* the model.
*
* @param name the new type name
* @param canBeModified if <code>true</code> the enclosing type name field is
* editable; otherwise it is read-only.
*/
public void setTypeName(String name, boolean canBeModified) {
fTypeNameDialogField.setText(name);
fTypeNameDialogField.setEnabled(canBeModified);
}
/**
* Returns the selected modifiers.
*
* @return the selected modifiers
* @see Flags
*/
public int getModifiers() {
int mdf= 0;
if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) {
mdf+= F_PUBLIC;
} else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) {
mdf+= F_PRIVATE;
} else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) {
mdf+= F_PROTECTED;
}
if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) {
mdf+= F_ABSTRACT;
}
if (fOtherMdfButtons.isSelected(FINAL_INDEX)) {
mdf+= F_FINAL;
}
if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) {
mdf+= F_STATIC;
}
return mdf;
}
/**
* Sets the modifiers.
*
* @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>,
* <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code>
* or <code>F_STATIC</code> or, a valid combination.
* @param canBeModified if <code>true</code> the modifier fields are
* editable; otherwise they are read-only
* @see Flags
*/
public void setModifiers(int modifiers, boolean canBeModified) {
if (Flags.isPublic(modifiers)) {
fAccMdfButtons.setSelection(PUBLIC_INDEX, true);
} else if (Flags.isPrivate(modifiers)) {
fAccMdfButtons.setSelection(PRIVATE_INDEX, true);
} else if (Flags.isProtected(modifiers)) {
fAccMdfButtons.setSelection(PROTECTED_INDEX, true);
} else {
fAccMdfButtons.setSelection(DEFAULT_INDEX, true);
}
if (Flags.isAbstract(modifiers)) {
fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true);
}
if (Flags.isFinal(modifiers)) {
fOtherMdfButtons.setSelection(FINAL_INDEX, true);
}
if (Flags.isStatic(modifiers)) {
fOtherMdfButtons.setSelection(fStaticMdfIndex, true);
}
fAccMdfButtons.setEnabled(canBeModified);
fOtherMdfButtons.setEnabled(canBeModified);
}
/**
* Returns the content of the superclass input field.
*
* @return the superclass name
*/
public String getSuperClass() {
return fSuperClassDialogField.getText();
}
/**
* Sets the super class name.
*
* @param name the new superclass name
* @param canBeModified if <code>true</code> the superclass name field is
* editable; otherwise it is read-only.
*/
public void setSuperClass(String name, boolean canBeModified) {
fSuperClassDialogField.setText(name);
fSuperClassDialogField.setEnabled(canBeModified);
}
/**
* Returns the chosen super interfaces.
*
* @return a list of chosen super interfaces. The list's elements
* are of type <code>String</code>
*/
public List getSuperInterfaces() {
return fSuperInterfacesDialogField.getElements();
}
/**
* Sets the super interfaces.
*
* @param interfacesNames a list of super interface. The method requires that
* the list's elements are of type <code>String</code>
* @param canBeModified if <code>true</code> the super interface field is
* editable; otherwise it is read-only.
*/
public void setSuperInterfaces(List interfacesNames, boolean canBeModified) {
fSuperInterfacesDialogField.setElements(interfacesNames);
fSuperInterfacesDialogField.setEnabled(canBeModified);
}
// ----------- validation ----------
/**
* A hook method that gets called when the package field has changed. The method
* validates the package name and returns the status of the validation. The validation
* also updates the package fragment model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus packageChanged() {
StatusInfo status= new StatusInfo();
fPackageDialogField.enableButton(getPackageFragmentRoot() != null);
String packName= getPackageText();
if (packName.length() > 0) {
IStatus val= JavaConventions.validatePackageName(packName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$
// continue
}
}
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root != null) {
if (root.getJavaProject().exists() && packName.length() > 0) {
try {
IPath rootPath= root.getPath();
IPath outputPath= root.getJavaProject().getOutputLocation();
if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) {
// if the bin folder is inside of our root, dont allow to name a package
// like the bin folder
IPath packagePath= rootPath.append(packName.replace('.', '/'));
if (outputPath.isPrefixOf(packagePath)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass
}
}
fCurrPackage= root.getPackageFragment(packName);
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
/*
* Updates the 'default' label next to the package field.
*/
private void updatePackageStatusLabel() {
String packName= getPackageText();
if (packName.length() == 0) {
fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$
} else {
fPackageDialogField.setStatus(""); //$NON-NLS-1$
}
}
/*
* Updates the enable state of buttons related to the enclosing type selection checkbox.
*/
private void updateEnableState() {
boolean enclosing= isEnclosingTypeSelected();
fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing);
fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing);
}
/**
* Hook method that gets called when the enclosing type name has changed. The method
* validates the enclosing type and returns the status of the validation. It also updates the
* enclosing type model.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus enclosingTypeChanged() {
StatusInfo status= new StatusInfo();
fCurrEnclosingType= null;
IPackageFragmentRoot root= getPackageFragmentRoot();
fEnclosingTypeDialogField.enableButton(root != null);
if (root == null) {
status.setError(""); //$NON-NLS-1$
return status;
}
String enclName= getEnclosingTypeText();
if (enclName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$
return status;
}
try {
IType type= root.getJavaProject().findType(enclName);
if (type == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
return status;
}
if (type.getCompilationUnit() == null) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isEditable(type.getCompilationUnit())) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$
return status;
}
fCurrEnclosingType= type;
IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type);
if (!enclosingRoot.equals(root)) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$
}
return status;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$
JavaPlugin.log(e);
return status;
}
}
/**
* Hook method that gets called when the type name has changed. The method validates the
* type name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus typeNameChanged() {
StatusInfo status= new StatusInfo();
String typeName= getTypeName();
// must not be empty
if (typeName.length() == 0) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$
return status;
}
if (typeName.indexOf('.') != -1) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(typeName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$
return status;
} else if (val.getSeverity() == IStatus.WARNING) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$
// continue checking
}
// must not exist
if (!isEnclosingTypeSelected()) {
IPackageFragment pack= getPackageFragment();
if (pack != null) {
ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$
if (cu.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
} else {
IType type= getEnclosingType();
if (type != null) {
IType member= type.getType(typeName);
if (member.exists()) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$
return status;
}
}
}
return status;
}
/**
* Hook method that gets called when the superclass name has changed. The method
* validates the superclass name and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superClassChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperClassDialogField.enableButton(root != null);
fSuperClass= null;
String sclassName= getSuperClass();
if (sclassName.length() == 0) {
// accept the empty field (stands for java.lang.Object)
return status;
}
IStatus val= JavaConventions.validateJavaTypeName(sclassName);
if (val.getSeverity() == IStatus.ERROR) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
return status;
}
if (root != null) {
try {
IType type= resolveSuperTypeName(root.getJavaProject(), sclassName);
if (type == null) {
status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$
return status;
} else {
if (type.isInterface()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$
return status;
}
int flags= type.getFlags();
if (Flags.isFinal(flags)) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$
return status;
} else if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$
return status;
}
}
fSuperClass= type;
} catch (JavaModelException e) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$
JavaPlugin.log(e);
}
} else {
status.setError(""); //$NON-NLS-1$
}
return status;
}
private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException {
IType type= null;
if (isEnclosingTypeSelected()) {
// search in the context of the enclosing type
IType enclosingType= getEnclosingType();
if (enclosingType != null) {
String[][] res= enclosingType.resolveType(sclassName);
if (res != null && res.length > 0) {
type= jproject.findType(res[0][0], res[0][1]);
}
}
} else {
IPackageFragment currPack= getPackageFragment();
if (type == null && currPack != null) {
String packName= currPack.getElementName();
// search in own package
if (!currPack.isDefaultPackage()) {
type= jproject.findType(packName, sclassName);
}
// search in java.lang
if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$
type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$
}
}
// search fully qualified
if (type == null) {
type= jproject.findType(sclassName);
}
}
return type;
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the superinterfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= (String)elements.get(i);
try {
IType type= root.getJavaProject().findType(intfname);
if (type == null) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$
return status;
} else {
if (type.isClass()) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$
return status;
}
if (!JavaModelUtil.isVisible(type, getPackageFragment())) {
status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$
return status;
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
// let pass, checking is an extra
}
}
}
return status;
}
/**
* Hook method that gets called when the modifiers have changed. The method validates
* the modifiers and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus modifiersChanged() {
StatusInfo status= new StatusInfo();
int modifiers= getModifiers();
if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) {
status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$
}
return status;
}
// selection dialogs
private IPackageFragment choosePackage() {
IPackageFragmentRoot froot= getPackageFragmentRoot();
IJavaElement[] packages= null;
try {
if (froot != null && froot.exists()) {
packages= froot.getChildren();
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
if (packages == null) {
packages= new IJavaElement[0];
}
ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT));
dialog.setIgnoreCase(false);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$
dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$
dialog.setElements(packages);
IPackageFragment pack= getPackageFragment();
if (pack != null) {
dialog.setInitialSelections(new Object[] { pack });
}
if (dialog.open() == ElementListSelectionDialog.OK) {
return (IPackageFragment) dialog.getFirstResult();
}
return null;
}
private IType chooseEnclosingType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root });
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$
dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText()));
if (dialog.open() == TypeSelectionDialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private IType chooseSuperType() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return null;
}
IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() };
IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements);
TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope);
dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$
dialog.setFilter(getSuperClass());
if (dialog.open() == TypeSelectionDialog.OK) {
return (IType) dialog.getFirstResult();
}
return null;
}
private void chooseSuperInterfaces() {
IPackageFragmentRoot root= getPackageFragmentRoot();
if (root == null) {
return;
}
IJavaProject project= root.getJavaProject();
SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project);
dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$
dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$
dialog.open();
return;
}
// ---- creation ----------------
/**
* Creates the new type using the entered field values.
*
* @param monitor a progress monitor to report progress.
*/
public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$
ICompilationUnit createdWorkingCopy= null;
try {
IPackageFragmentRoot root= getPackageFragmentRoot();
IPackageFragment pack= getPackageFragment();
if (pack == null) {
pack= root.getPackageFragment(""); //$NON-NLS-1$
}
if (!pack.exists()) {
String packName= pack.getElementName();
pack= root.createPackageFragment(packName, true, null);
}
monitor.worked(1);
String clName= getTypeName();
boolean isInnerClass= isEnclosingTypeSelected();
IType createdType;
ImportsStructure imports;
int indent= 0;
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
String lineDelimiter= null;
if (!isInnerClass) {
lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$
ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$
createdWorkingCopy= (ICompilationUnit) parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), null);
imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false);
// add an import that will be removed again. Having this import solves 14661
imports.addImport(pack.getElementName(), getTypeName());
String typeContent= constructTypeStub(new ImportsManager(imports), lineDelimiter);
String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter);
createdWorkingCopy.getBuffer().setContents(cuContent);
createdType= createdWorkingCopy.getType(clName);
} else {
IType enclosingType= getEnclosingType();
// if we are working on a enclosed type that is open in an editor,
// then replace the enclosing type with its working copy
IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType);
if (workingCopy != null) {
enclosingType= workingCopy;
}
ICompilationUnit parentCU= enclosingType.getCompilationUnit();
imports= new ImportsStructure(parentCU, prefOrder, threshold, true);
// add imports that will be removed again. Having the imports solves 14661
IType[] topLevelTypes= parentCU.getTypes();
for (int i= 0; i < topLevelTypes.length; i++) {
imports.addImport(topLevelTypes[i].getFullyQualifiedName('.'));
}
lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType);
StringBuffer content= new StringBuffer();
String comment= getTypeComment(parentCU);
if (comment != null) {
content.append(comment);
content.append(lineDelimiter);
}
content.append(constructTypeStub(new ImportsManager(imports), lineDelimiter));
IJavaElement[] elems= enclosingType.getChildren();
IJavaElement sibling= elems.length > 0 ? elems[0] : null;
createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1));
indent= StubUtility.getIndentUsed(enclosingType) + 1;
}
// add imports for superclass/interfaces, so types can be resolved correctly
imports.create(false, new SubProgressMonitor(monitor, 1));
ICompilationUnit cu= createdType.getCompilationUnit();
synchronized(cu) {
cu.reconcile();
}
createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1));
// add imports
imports.create(false, new SubProgressMonitor(monitor, 1));
synchronized(cu) {
cu.reconcile();
}
ISourceRange range= createdType.getSourceRange();
IBuffer buf= cu.getBuffer();
String originalContent= buf.getText(range.getOffset(), range.getLength());
String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter);
buf.replace(range.getOffset(), range.getLength(), formattedContent);
if (!isInnerClass) {
String fileComment= getFileComment(cu);
if (fileComment != null && fileComment.length() > 0) {
buf.replace(0, 0, fileComment + lineDelimiter);
}
cu.commit(false, new SubProgressMonitor(monitor, 1));
} else {
monitor.worked(1);
}
fCreatedType= createdType;
} finally {
if (createdWorkingCopy != null) {
createdWorkingCopy.destroy();
}
monitor.done();
}
}
/**
* Uses the New Java file template from the code template page to generate a
* compilation unit with the given type content.
* @param cu The new created compilation unit
* @param typeContent The content of the type, including signature and type
* body.
* @param lineDelimiter The line delimiter to be used.
* @return String Returns the result of evaluating the new file template
* with the given type content.
* @throws CoreException
*/
protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException {
IPackageFragment pack= (IPackageFragment) cu.getParent();
String packDecl= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$
Template template= CodeTemplates.getCodeTemplate(CodeTemplates.NEWTYPE);
if (template == null) {
return getDefaultCUContent(packDecl, typeContent, lineDelimiter);
}
String typeComment= StubUtility.getTypeComment(cu, getTypeName());
IJavaProject project= cu.getJavaProject();
CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeName(), project, lineDelimiter, 0);
context.setCompilationUnitVariables(cu);
context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, packDecl);
context.setVariable(CodeTemplateContextType.TYPE_COMMENT, typeComment != null ? typeComment : ""); //$NON-NLS-1$
context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, typeContent);
context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, getTypeName());
String content= context.evaluate(template).getString();
if (content.length() == 0) {
return getDefaultCUContent(packDecl, typeContent, lineDelimiter);
}
CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray());
if (!pack.isDefaultPackage() && unit.getPackage() == null || unit.types().isEmpty()) {
return getDefaultCUContent(packDecl, typeContent, lineDelimiter);
}
return content;
}
private String getDefaultCUContent(String packStatement, String typeContent, String lineDelimiter) {
return packStatement + lineDelimiter + lineDelimiter + typeContent;
}
/**
* Returns the created type. The method only returns a valid type
* after <code>createType</code> has been called.
*
* @return the created type
* @see #createType(IProgressMonitor)
*/
public IType getCreatedType() {
return fCreatedType;
}
// ---- construct cu body----------------
private void writeSuperClass(StringBuffer buf, ImportsManager imports) {
String typename= getSuperClass();
if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$
buf.append(" extends "); //$NON-NLS-1$
String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename;
buf.append(imports.addImport(qualifiedName));
}
}
private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) {
List interfaces= getSuperInterfaces();
int last= interfaces.size() - 1;
if (last >= 0) {
if (fIsClass) {
buf.append(" implements "); //$NON-NLS-1$
} else {
buf.append(" extends "); //$NON-NLS-1$
}
for (int i= 0; i <= last; i++) {
String typename= (String) interfaces.get(i);
buf.append(imports.addImport(typename));
if (i < last) {
buf.append(',');
}
}
}
}
/*
* Called from createType to construct the source for this type
*/
private String constructTypeStub(ImportsManager imports, String lineDelimiter) {
StringBuffer buf= new StringBuffer();
int modifiers= getModifiers();
buf.append(Flags.toString(modifiers));
if (modifiers != 0) {
buf.append(' ');
}
buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$
buf.append(getTypeName());
writeSuperClass(buf, imports);
writeSuperInterfaces(buf, imports);
buf.append('{');
buf.append(lineDelimiter);
buf.append(lineDelimiter);
buf.append('}');
buf.append(lineDelimiter);
return buf.toString();
}
/**
* @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead
*/
protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
//deprecated
}
/**
* Hook method that gets called from <code>createType</code> to support adding of
* unanticipated methods, fields, and inner types to the created type.
* <p>
* Implementers can use any methods defined on <code>IType</code> to manipulate the
* new type.
* </p>
* <p>
* The source code of the new type will be formtted using the platform's formatter. Needed
* imports are added by the wizard at the end of the type creation process using the given
* import manager.
* </p>
*
* @param newType the new type created via <code>createType</code>
* @param imports an import manager which can be used to add new imports
* @param monitor a progress monitor to report progress. Must not be <code>null</code>
*
* @see #createType(IProgressMonitor)
*/
protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
// call for compatibility
createTypeMembers(newType, ((ImportsManager)imports).getImportsStructure(), monitor);
// default implementation does nothing
// example would be
// String mainMathod= "public void foo(Vector vec) {}"
// createdType.createMethod(main, null, false, null);
// imports.addImport("java.lang.Vector");
}
/**
* @deprecated Instead of file templates, the new type code template
* specifies the stub for a compilation unit.
*/
protected String getFileComment(ICompilationUnit parentCU) {
return null;
}
private boolean isValidComment(String template) {
IScanner scanner= ToolFactory.createScanner(true, false, false, false);
scanner.setSource(template.toCharArray());
try {
int next= scanner.getNextToken();
while (next == ITerminalSymbols.TokenNameCOMMENT_LINE || next == ITerminalSymbols.TokenNameCOMMENT_JAVADOC || next == ITerminalSymbols.TokenNameCOMMENT_BLOCK) {
next= scanner.getNextToken();
}
return next == ITerminalSymbols.TokenNameEOF;
} catch (InvalidInputException e) {
}
return false;
}
/**
* Hook method that gets called from <code>createType</code> to retrieve
* a type comment. This default implementation returns the content of the
* 'typecomment' template.
*
* @return the type comment or <code>null</code> if a type comment
* is not desired
*/
protected String getTypeComment(ICompilationUnit parentCU) {
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN__JAVADOC_STUBS)) {
try {
String comment= StubUtility.getTypeComment(parentCU, getTypeName());
if (comment != null && isValidComment(comment)) {
return comment;
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
return null;
}
/**
* @deprecated Use getTemplate(String,ICompilationUnit,int)
*/
protected String getTemplate(String name, ICompilationUnit parentCU) {
return getTemplate(name, parentCU, 0);
}
/**
* Returns the string resulting from evaluation the given template in
* the context of the given compilation unit. This accesses the normal
* template page, not the code templates. To use code templates use
* <code>constructCUContent</code> to construct a compilation unit stub or
* getTypeComment for the comment of the type.
*
* @param name the template to be evaluated
* @param parentCU the templates evaluation context
* @param pos a source offset into the parent compilation unit. The
* template is evalutated at the given source offset
*/
protected String getTemplate(String name, ICompilationUnit parentCU, int pos) {
try {
Template[] templates= Templates.getInstance().getTemplates(name);
if (templates.length > 0) {
return JavaContext.evaluateTemplate(templates[0], parentCU, pos);
}
} catch (CoreException e) {
JavaPlugin.log(e);
}
return null;
}
/**
* @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor)
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException {
return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor);
}
/**
* Creates the bodies of all unimplemented methods and constructors and adds them to the type.
* Method is typically called by implementers of <code>NewTypeWizardPage</code> to add
* needed method and constructors.
*
* @param type the type for which the new methods and constructor are to be created
* @param doConstructors if <code>true</code> unimplemented constructors are created
* @param doUnimplementedMethods if <code>true</code> unimplemented methods are created
* @param imports an import manager to add all neded import statements
* @param monitor a progress monitor to report progress
*/
protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException {
ArrayList newMethods= new ArrayList();
ITypeHierarchy hierarchy= 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.getImportsStructure());
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.getImportsStructure());
if (unimplemented != null) {
for (int i= 0; i < unimplemented.length; i++) {
newMethods.add(unimplemented[i]);
}
}
}
IMethod[] createdMethods= new IMethod[newMethods.size()];
for (int i= 0; i < newMethods.size(); i++) {
String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n
createdMethods[i]= type.createMethod(content, null, false, null);
}
return createdMethods;
}
// ---- creation ----------------
/**
* Returns the runnable that creates the type using the current settings.
* The returned runnable must be executed in the UI thread.
*
* @return the runnable to create the new type
*/
public IRunnableWithProgress getRunnable() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
createType(monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
}
|
31,288 |
Bug 31288 read-only source folder not renamed
|
- 'rename' read-only source folder - confirm renaming on read-only source folder - supply a new name -> nothing changes
|
verified fixed
|
4d3d34f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:37:02Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,288 |
Bug 31288 read-only source folder not renamed
|
- 'rename' read-only source folder - confirm renaming on read-only source folder - supply a new name -> nothing changes
|
verified fixed
|
4d3d34f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T11:37:02Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameSourceFolderRefactoring.java
| |
30,827 |
Bug 30827 cannot go pack from refactoring error dialog
|
20030129 in the wizard world i used to be able to go back to the input page from the error page - now i have to re-start my refactoring and re-type everything
|
resolved fixed
|
e2da23d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T14:02:41Z | 2003-02-03T19:20:00Z |
org.eclipse.jdt.ui/ui
| |
30,827 |
Bug 30827 cannot go pack from refactoring error dialog
|
20030129 in the wizard world i used to be able to go back to the input page from the error page - now i have to re-start my refactoring and re-type everything
|
resolved fixed
|
e2da23d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T14:02:41Z | 2003-02-03T19:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringExecutionHelper.java
| |
30,827 |
Bug 30827 cannot go pack from refactoring error dialog
|
20030129 in the wizard world i used to be able to go back to the input page from the error page - now i have to re-start my refactoring and re-type everything
|
resolved fixed
|
e2da23d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T14:02:41Z | 2003-02-03T19:20:00Z |
org.eclipse.jdt.ui/ui
| |
30,827 |
Bug 30827 cannot go pack from refactoring error dialog
|
20030129 in the wizard world i used to be able to go back to the input page from the error page - now i have to re-start my refactoring and re-type everything
|
resolved fixed
|
e2da23d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T14:02:41Z | 2003-02-03T19:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringStatusDialog.java
| |
30,827 |
Bug 30827 cannot go pack from refactoring error dialog
|
20030129 in the wizard world i used to be able to go back to the input page from the error page - now i have to re-start my refactoring and re-type everything
|
resolved fixed
|
e2da23d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T14:02:41Z | 2003-02-03T19:20:00Z |
org.eclipse.jdt.ui/ui
| |
30,827 |
Bug 30827 cannot go pack from refactoring error dialog
|
20030129 in the wizard world i used to be able to go back to the input page from the error page - now i have to re-start my refactoring and re-type everything
|
resolved fixed
|
e2da23d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T14:02:41Z | 2003-02-03T19:20:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/RefactoringWizardDialog2.java
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoring.java
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoring.java
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ComboSelectionDialog.java
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/PullUpInputPage1.java
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui
| |
31,281 |
Bug 31281 Push down refactoring: Dialog details + exception
|
20030206 Select a method and choose Refactoring->Push down - The message at the botton says '1 element(s) selected'. It should end with a dot (I would use 'member' istead of 'element' - double click should open the edit view - deselect all methods. An error icon comes up, the message says 'Select members to push down or declare abstract' As this is an error message (it has a big error icon) it should better be 'No members selected to push down' - the images in the table could be small (option of the label provider) - the edit dialog needs a title that is capitalized - the edit dialog should be initialized with the current values -deselect all elements, and press 'add required', you get an exception java.lang.reflect.InvocationTargetException: java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at java.util.ArrayList.get(ArrayList.java(Compiled Code)) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.getAdd itionalRequiredMembers(PushDownRefactoring.java:438) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.comput eAdditionalRequiredMembersToPushDown(PushDownRefactoring.java:426) at org.eclipse.jdt.internal.ui.refactoring.PushDownInputPage$6.run (PushDownInputPage.java:338) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:296) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246)
|
resolved fixed
|
081a2d2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T15:43:20Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/PushDownInputPage.java
| |
31,291 |
Bug 31291 rename of read-only package doesn't ask for confirmation on 'OK'
|
- 'rename' read-only package - leave everything unchecked except 'Update ref. to renamed element' - 'Update ref. to renamed element' can be checked or unchecked - press ok -> renames without asking for confirmation
|
resolved fixed
|
836f337
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T16:02:36Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,291 |
Bug 31291 rename of read-only package doesn't ask for confirmation on 'OK'
|
- 'rename' read-only package - leave everything unchecked except 'Update ref. to renamed element' - 'Update ref. to renamed element' can be checked or unchecked - press ok -> renames without asking for confirmation
|
resolved fixed
|
836f337
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T16:02:36Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenamePackageRefactoring.java
| |
31,134 |
Bug 31134 NPE when no default JRE [code manipulation]
|
I created a project when there were no defined JREs, and got the following NPE: !ENTRY org.eclipse.jdt.ui 4 10001 Feb 06, 2003 12:34:15.392 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException: java.lang.NullPointerException Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V java/lang/NullPointerException.<init>(Ljava/lang/String;)V org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.<init> (Lorg/eclipse/jdt/core/IJavaProject;ILorg/eclipse/core/runtime/IPath;Lorg/eclips e/core/resources/IResource;)V org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.createFromExisting (Lorg/eclipse/jdt/core/IClasspathEntry;Lorg/eclipse/jdt/core/IJavaProject;) Lorg/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement; org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.getExistingEntrie s([Lorg/eclipse/jdt/core/IClasspathEntry;)Ljava/util/ArrayList; org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.getDefaultClassPa th(Lorg/eclipse/jdt/core/IJavaProject;)Ljava/util/List; org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.init (Lorg/eclipse/jdt/core/IJavaProject;Lorg/eclipse/core/runtime/IPath; [Lorg/eclipse/jdt/core/IClasspathEntry;)V org/eclipse/jdt/ui/wizards/JavaCapabilityConfigurationPage.init (Lorg/eclipse/jdt/core/IJavaProject;Lorg/eclipse/core/runtime/IPath; [Lorg/eclipse/jdt/core/IClasspathEntry;Z)V org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizardPage.updateProject (ZLorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizardPage.performFinish (Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizard.finishPage (Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jdt/internal/ui/wizards/NewElementWizard$2.run (Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jdt/internal/core/BatchOperation.executeOperation()V org/eclipse/jdt/internal/core/JavaModelOperation.execute()V org/eclipse/jdt/internal/core/JavaModelOperation.run (Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/core/internal/resources/Workspace.run (Lorg/eclipse/core/resources/IWorkspaceRunnable;Lorg/eclipse/core/runtime/IProgr essMonitor;)V org/eclipse/jdt/core/JavaCore.run (Lorg/eclipse/core/resources/IWorkspaceRunnable;Lorg/eclipse/core/runtime/IProgr essMonitor;)V org/eclipse/jdt/internal/ui/actions/WorkbenchRunnableAdapter.run (Lorg/eclipse/core/runtime/IProgressMonitor;)V org/eclipse/jface/operation/ModalContext.runInCurrentThread (Lorg/eclipse/jface/operation/IRunnableWithProgress;Lorg/eclipse/core/runtime/IP rogressMonitor;)V org/eclipse/jface/operation/ModalContext.run (Lorg/eclipse/jface/operation/IRunnableWithProgress;ZLorg/eclipse/core/runtime/I ProgressMonitor;Lorg/eclipse/swt/widgets/Display;)V org/eclipse/jface/wizard/WizardDialog.run (ZZLorg/eclipse/jface/operation/IRunnableWithProgress;)V org/eclipse/jdt/internal/ui/wizards/NewElementWizard.performFinish()Z org/eclipse/jface/wizard/WizardDialog.finishPressed()V org/eclipse/jface/wizard/WizardDialog.buttonPressed(I)V org/eclipse/jface/dialogs/Dialog$1.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.sendEvent(Lorg/eclipse/swt/widgets/Event;)V org/eclipse/swt/widgets/Display.runDeferredEvents()Z 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/jdt/internal/ui/wizards/AbstractOpenWizardAction.run()V org/eclipse/jdt/internal/ui/wizards/AbstractOpenWizardAction.run (Lorg/eclipse/jface/action/IAction;)V org/eclipse/ui/internal/PluginAction.runWithEvent (Lorg/eclipse/swt/widgets/Event;)V org/eclipse/ui/internal/WWinPluginAction.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.sendEvent(Lorg/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 (Lorg/eclipse/jface/window/Window$IExceptionHandler;)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/Runnable;)Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String; [Ljava/lang/String;Ljava/lang/Runnable;)Ljava/lang/Object; java/lang/reflect/AccessibleObject.invokeImpl(Ljava/lang/Object; [Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; java/lang/reflect/AccessibleObject.invokeL(Ljava/lang/Object; [Ljava/lang/Object;)Ljava/lang/Object; java/lang/reflect/Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;) Ljava/lang/Object; org/eclipse/core/launcher/Main.basicRun([Ljava/lang/String;) Ljava/lang/Object; org/eclipse/core/launcher/Main.run([Ljava/lang/String;)Ljava/lang/Object; org/eclipse/core/launcher/Main.main([Ljava/lang/String;)V
|
resolved fixed
|
25362e8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T18:14:56Z | 2003-02-06T19:33:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPListElement.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.net.URL;
import java.util.ArrayList;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
public class CPListElement {
public static final String SOURCEATTACHMENT= "sourcepath"; //$NON-NLS-1$
public static final String SOURCEATTACHMENTROOT= "rootpath"; //$NON-NLS-1$
public static final String JAVADOC= "javadoc"; //$NON-NLS-1$
public static final String OUTPUT= "output"; //$NON-NLS-1$
public static final String EXCLUSION= "exclusion"; //$NON-NLS-1$
private IJavaProject fProject;
private int fEntryKind;
private IPath fPath;
private IResource fResource;
private boolean fIsExported;
private boolean fIsMissing;
private CPListElement fParentContainer;
private IClasspathEntry fCachedEntry;
private ArrayList fChildren;
public CPListElement(IJavaProject project, int entryKind, IPath path, IResource res) {
fProject= project;
fEntryKind= entryKind;
fPath= path;
fChildren= new ArrayList();
fResource= res;
fIsExported= false;
fIsMissing= false;
fCachedEntry= null;
fParentContainer= null;
switch (entryKind) {
case IClasspathEntry.CPE_SOURCE:
createAttributeElement(OUTPUT, null);
createAttributeElement(EXCLUSION, new Path[0]);
break;
case IClasspathEntry.CPE_LIBRARY:
case IClasspathEntry.CPE_VARIABLE:
createAttributeElement(SOURCEATTACHMENT, null);
createAttributeElement(JAVADOC, null);
break;
case IClasspathEntry.CPE_PROJECT:
break;
case IClasspathEntry.CPE_CONTAINER:
try {
IClasspathContainer container= JavaCore.getClasspathContainer(fPath, fProject);
IClasspathEntry[] entries= container.getClasspathEntries();
for (int i= 0; i < entries.length; i++) {
CPListElement curr= createFromExisting(entries[i], fProject);
curr.setParentContainer(this);
fChildren.add(curr);
}
} catch (JavaModelException e) {
}
break;
default:
}
}
public IClasspathEntry getClasspathEntry() {
if (fCachedEntry == null) {
fCachedEntry= newClasspathEntry();
}
return fCachedEntry;
}
private IClasspathEntry newClasspathEntry() {
switch (fEntryKind) {
case IClasspathEntry.CPE_SOURCE:
IPath outputLocation= (IPath) getAttribute(OUTPUT);
IPath[] exclusionPattern= (IPath[]) getAttribute(EXCLUSION);
return JavaCore.newSourceEntry(fPath, exclusionPattern, outputLocation);
case IClasspathEntry.CPE_LIBRARY:
IPath attach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newLibraryEntry(fPath, attach, null, isExported());
case IClasspathEntry.CPE_PROJECT:
return JavaCore.newProjectEntry(fPath, isExported());
case IClasspathEntry.CPE_CONTAINER:
return JavaCore.newContainerEntry(fPath, isExported());
case IClasspathEntry.CPE_VARIABLE:
IPath varAttach= (IPath) getAttribute(SOURCEATTACHMENT);
return JavaCore.newVariableEntry(fPath, varAttach, null, isExported());
default:
return null;
}
}
/**
* Gets the classpath entry path.
* @see IClasspathEntry#getPath()
*/
public IPath getPath() {
return fPath;
}
/**
* Gets the classpath entry kind.
* @see IClasspathEntry#getEntryKind()
*/
public int getEntryKind() {
return fEntryKind;
}
/**
* Entries without resource are either non existing or a variable entry
* External jars do not have a resource
*/
public IResource getResource() {
return fResource;
}
public CPListElementAttribute setAttribute(String key, Object value) {
CPListElementAttribute attribute= findAttributeElement(key);
if (attribute == null) {
return null;
}
attribute.setValue(value);
attributeChanged(key);
return attribute;
}
private CPListElementAttribute findAttributeElement(String key) {
for (int i= 0; i < fChildren.size(); i++) {
Object curr= fChildren.get(i);
if (curr instanceof CPListElementAttribute) {
CPListElementAttribute elem= (CPListElementAttribute) curr;
if (key.equals(elem.getKey())) {
return elem;
}
}
}
return null;
}
public Object getAttribute(String key) {
CPListElementAttribute attrib= findAttributeElement(key);
if (attrib != null) {
return attrib.getValue();
}
return null;
}
private void createAttributeElement(String key, Object value) {
fChildren.add(new CPListElementAttribute(this, key, value));
}
public Object[] getChildren(boolean hideOutputFolder) {
if (hideOutputFolder && fEntryKind == IClasspathEntry.CPE_SOURCE) {
return new Object[] { findAttributeElement(EXCLUSION) };
}
return fChildren.toArray();
}
private void setParentContainer(CPListElement element) {
fParentContainer= element;
}
public CPListElement getParentContainer() {
return fParentContainer;
}
private void attributeChanged(String key) {
fCachedEntry= null;
}
/*
* @see Object#equals(java.lang.Object)
*/
public boolean equals(Object other) {
if (other != null && other.getClass() == getClass()) {
CPListElement elem= (CPListElement)other;
return elem.fEntryKind == fEntryKind && elem.fPath.equals(fPath);
}
return false;
}
/*
* @see Object#hashCode()
*/
public int hashCode() {
return fPath.hashCode() + fEntryKind;
}
/**
* Returns if a entry is missing.
* @return Returns a boolean
*/
public boolean isMissing() {
return fIsMissing;
}
/**
* Sets the 'missing' state of the entry.
*/
public void setIsMissing(boolean isMissing) {
fIsMissing= isMissing;
}
/**
* Returns if a entry is exported (only applies to libraries)
* @return Returns a boolean
*/
public boolean isExported() {
return fIsExported;
}
/**
* Sets the export state of the entry.
*/
public void setExported(boolean isExported) {
if (isExported != fIsExported) {
fIsExported = isExported;
attributeChanged(null);
}
}
/**
* Gets the project.
* @return Returns a IJavaProject
*/
public IJavaProject getJavaProject() {
return fProject;
}
public static CPListElement createFromExisting(IClasspathEntry curr, IJavaProject project) {
IPath path= curr.getPath();
IWorkspaceRoot root= project.getProject().getWorkspace().getRoot();
// get the resource
IResource res= null;
boolean isMissing= false;
URL javaDocLocation= null;
switch (curr.getEntryKind()) {
case IClasspathEntry.CPE_CONTAINER:
res= null;
try {
isMissing= (JavaCore.getClasspathContainer(path, project) == null);
} catch (JavaModelException e) {
isMissing= true;
}
break;
case IClasspathEntry.CPE_VARIABLE:
IPath resolvedPath= JavaCore.getResolvedVariablePath(path);
res= null;
isMissing= root.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile();
javaDocLocation= JavaUI.getLibraryJavadocLocation(resolvedPath);
break;
case IClasspathEntry.CPE_LIBRARY:
res= root.findMember(path);
if (res == null) {
if (!ArchiveFileFilter.isArchivePath(path)) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
}
isMissing= !path.toFile().isFile(); // look for external JARs
}
javaDocLocation= JavaUI.getLibraryJavadocLocation(path);
break;
case IClasspathEntry.CPE_SOURCE:
res= root.findMember(path);
if (res == null) {
if (root.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) {
res= root.getFolder(path);
}
isMissing= true;
}
break;
case IClasspathEntry.CPE_PROJECT:
res= root.findMember(path);
isMissing= (res == null);
break;
}
CPListElement elem= new CPListElement(project, curr.getEntryKind(), path, res);
elem.setExported(curr.isExported());
elem.setAttribute(SOURCEATTACHMENT, curr.getSourceAttachmentPath());
elem.setAttribute(JAVADOC, javaDocLocation);
elem.setAttribute(OUTPUT, curr.getOutputLocation());
elem.setAttribute(EXCLUSION, curr.getExclusionPatterns());
if (project.exists()) {
elem.setIsMissing(isMissing);
}
return elem;
}
}
|
31,524 |
Bug 31524 Update problem in Java browsing perspective [browsing]
|
M5+plugin export: - open Java browsing perspective - switch to segmented view - drill down to any method - in segemented editor edit method name Observe: members view is updated correctly - close segmented editor and discard changes Observe: members view still shows changed name
|
resolved fixed
|
93f9637
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-11T18:41:08Z | 2003-02-11T10:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/MembersView.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IMemento;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportContainer;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer;
public class MembersView extends JavaBrowsingPart implements IPropertyChangeListener {
private MemberFilterActionGroup fMemberFilterActionGroup;
public MembersView() {
setHasWorkingSetFilter(false);
setHasCustomSetFilter(true);
JavaPlugin.getDefault().getPreferenceStore().addPropertyChangeListener(this);
}
/**
* Creates and returns the label provider for this part.
*
* @return the label provider
* @see ILabelProvider
*/
protected JavaUILabelProvider createLabelProvider() {
return new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS
);
}
/**
* Returns the context ID for the Help system
*
* @return the string used as ID for the Help context
*/
protected String getHelpContextId() {
return IJavaHelpContextIds.MEMBERS_VIEW;
}
/**
* Creates the the viewer of this part.
*
* @param parent the parent for the viewer
*/
protected StructuredViewer createViewer(Composite parent) {
ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI);
fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaUI.ID_MEMBERS_VIEW);
return viewer;
}
protected void fillToolBar(IToolBarManager tbm) {
tbm.add(new LexicalSortingAction(getViewer(), JavaUI.ID_MEMBERS_VIEW));
fMemberFilterActionGroup.contributeToToolBar(tbm);
}
/**
* Answers if the given <code>element</code> is a valid
* input for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid input
*/
protected boolean isValidInput(Object element) {
if (element instanceof IType) {
IType type= (IType)element;
return type.isBinary() || type.getDeclaringType() == null;
}
return false;
}
/**
* Answers if the given <code>element</code> is a valid
* element for this part.
*
* @param element the object to test
* @return <true> if the given element is a valid element
*/
protected boolean isValidElement(Object element) {
if (element instanceof IMember)
return super.isValidElement(((IMember)element).getDeclaringType());
else if (element instanceof IImportDeclaration)
return isValidElement(((IJavaElement)element).getParent());
else if (element instanceof IImportContainer) {
Object input= getViewer().getInput();
if (input instanceof IJavaElement) {
ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null) {
ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT);
return cu.equals(importContainerCu);
} else {
IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE);
IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE);
return cf != null && cf.equals(importContainerCf);
}
}
}
return false;
}
/**
* Finds the element which has to be selected in this part.
*
* @param je the Java element which has the focus
*/
protected IJavaElement findElementToSelect(IJavaElement je) {
if (je == null)
return null;
switch (je.getElementType()) {
case IJavaElement.TYPE:
if (((IType)je).getDeclaringType() == null)
return null;
// fall through
case IJavaElement.METHOD:
// fall through
case IJavaElement.FIELD:
// fall through
case IJavaElement.PACKAGE_DECLARATION:
// fall through
case IJavaElement.IMPORT_CONTAINER:
return getSuitableJavaElement(je);
case IJavaElement.IMPORT_DECLARATION:
je= getSuitableJavaElement(je);
if (je != null) {
ICompilationUnit cu= (ICompilationUnit)je.getParent().getParent();
try {
if (cu.getImports()[0].equals(je)) {
Object selectedElement= getSingleElementFromSelection(getViewer().getSelection());
if (selectedElement instanceof IImportContainer)
return (IImportContainer)selectedElement;
}
} catch (JavaModelException ex) {
// return je;
}
return je;
}
break;
}
return null;
}
/**
* Finds the closest Java element which can be used as input for
* this part and has the given Java element as child
*
* @param je the Java element for which to search the closest input
* @return the closest Java element used as input for this part
*/
protected IJavaElement findInputForJavaElement(IJavaElement je) {
if (je == null || !je.exists())
return null;
switch (je.getElementType()) {
case IJavaElement.TYPE:
IType type= ((IType)je).getDeclaringType();
if (type == null)
return je;
else
return findInputForJavaElement(type);
case IJavaElement.COMPILATION_UNIT:
return getTypeForCU((ICompilationUnit)je);
case IJavaElement.CLASS_FILE:
try {
return findInputForJavaElement(((IClassFile)je).getType());
} catch (JavaModelException ex) {
return null;
}
case IJavaElement.IMPORT_DECLARATION:
return findInputForJavaElement(je.getParent());
case IJavaElement.PACKAGE_DECLARATION:
case IJavaElement.IMPORT_CONTAINER:
IJavaElement parent= je.getParent();
if (parent instanceof ICompilationUnit) {
IType[] types;
try {
types= ((ICompilationUnit)parent).getAllTypes();
} catch (JavaModelException ex) {
return null;
}
if (types.length > 0)
return types[0];
else
return null;
}
else if (parent instanceof IClassFile)
return findInputForJavaElement(parent);
default:
if (je instanceof IMember)
return findInputForJavaElement(((IMember)je).getDeclaringType());
}
return null;
}
/*
* Implements method from IViewPart.
*/
public void saveState(IMemento memento) {
super.saveState(memento);
fMemberFilterActionGroup.saveState(memento);
}
protected void restoreState(IMemento memento) {
super.restoreState(memento);
fMemberFilterActionGroup.restoreState(memento);
getViewer().getControl().setRedraw(false);
getViewer().refresh();
getViewer().getControl().setRedraw(true);
}
protected void hookViewerListeners() {
super.hookViewerListeners();
getViewer().addDoubleClickListener(new IDoubleClickListener() {
public void doubleClick(DoubleClickEvent event) {
TreeViewer viewer= (TreeViewer)getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element))
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
});
}
boolean isInputAWorkingCopy() {
Object input= getViewer().getInput();
if (input instanceof IJavaElement) {
ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT);
if (cu != null)
return cu.isWorkingCopy();
}
return false;
}
protected void restoreSelection() {
IEditorPart editor= getViewSite().getPage().getActiveEditor();
if (editor != null)
setSelectionFromEditor(editor);
}
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER)) {
getViewer().refresh();
}
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart#dispose()
*/
public void dispose() {
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
super.dispose();
JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(this);
}
}
|
31,601 |
Bug 31601 JME when changing method signature
|
20030206 - JUnit setup - select Assert.assertNotNull(String, Object) in Outliner - activate Change Method Signature - swap arguments - OK You get the following exception in the log. Java Model Exception: Java Model Status [assertNull [in Assert [in [Working copy] Assert.java [in junit.framework [in [project root] [in JUnit]]]]] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:482) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy (JavaElement.java:511) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:296) at org.eclipse.jdt.internal.core.SourceMethod.getSignature (SourceMethod.java:133) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .getInitialReturnTypeName(ChangeSignatureRefactoring.java:132) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .<init>(ChangeSignatureRefactoring.java:122) at org.eclipse.jdt.ui.actions.ModifyParametersAction.shouldAcceptElement (ModifyParametersAction.java:156) at org.eclipse.jdt.ui.actions.ModifyParametersAction.canEnable (ModifyParametersAction.java:130) at org.eclipse.jdt.ui.actions.ModifyParametersAction.selectionChanged (ModifyParametersAction.java:88) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:108) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:191) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) IMO the problem is that selectionChanged is called with the original element which signature got changed.
|
resolved fixed
|
2c403da
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T10:23:19Z | 2003-02-11T21:46:40Z |
org.eclipse.jdt.ui/core
| |
31,601 |
Bug 31601 JME when changing method signature
|
20030206 - JUnit setup - select Assert.assertNotNull(String, Object) in Outliner - activate Change Method Signature - swap arguments - OK You get the following exception in the log. Java Model Exception: Java Model Status [assertNull [in Assert [in [Working copy] Assert.java [in junit.framework [in [project root] [in JUnit]]]]] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:482) at org.eclipse.jdt.internal.core.JavaElement.openHierarchy (JavaElement.java:511) at org.eclipse.jdt.internal.core.JavaElement.getElementInfo (JavaElement.java:296) at org.eclipse.jdt.internal.core.SourceMethod.getSignature (SourceMethod.java:133) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .getInitialReturnTypeName(ChangeSignatureRefactoring.java:132) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactoring .<init>(ChangeSignatureRefactoring.java:122) at org.eclipse.jdt.ui.actions.ModifyParametersAction.shouldAcceptElement (ModifyParametersAction.java:156) at org.eclipse.jdt.ui.actions.ModifyParametersAction.canEnable (ModifyParametersAction.java:130) at org.eclipse.jdt.ui.actions.ModifyParametersAction.selectionChanged (ModifyParametersAction.java:88) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:108) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:191) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0 (ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) IMO the problem is that selectionChanged is called with the original element which signature got changed.
|
resolved fixed
|
2c403da
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T10:23:19Z | 2003-02-11T21:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
31,117 |
Bug 31117 incomplete deletion of abandoned Java project [code manipulation]
|
Build M5 1. New / Project / Java Project Name "J1" Hit Next. Observe: Project J3 appears in the resource navigator. 2. On Java settings wizard page, hit Cancel. Observe: Project J3 disappears from the resource navigator. 3. Use Windows Explorer to look at <workspace>/ Observe: <workspace>/J1/.project exists and contains <?xml version="1.0" encoding="UTF-8"?> <projectDescription> <name>J2</name> <comment></comment> <projects> </projects> <buildSpec> </buildSpec> <natures> </natures> </projectDescription> Expectation: <workspace>/J1/.project should get deleted. So should <workspace>/J1/ if it had just been created.
|
resolved fixed
|
30bc688
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:03:07Z | 2003-02-06T16:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
/**
* As addition to the JavaCapabilityConfigurationPage, the wizard does an
* early project creation (so that linked folders can be defined) and, if an
* existing external location was specified, offers to do a classpath detection
*/
public class NewProjectCreationWizardPage extends JavaCapabilityConfigurationPage {
private WizardNewProjectCreationPage fMainPage;
private IPath fCurrProjectLocation;
protected IProject fCurrProject;
/**
* Constructor for NewProjectCreationWizardPage.
*/
public NewProjectCreationWizardPage(WizardNewProjectCreationPage mainPage) {
super();
fMainPage= mainPage;
fCurrProjectLocation= null;
fCurrProject= null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean)
*/
public void setVisible(boolean visible) {
if (visible) {
changeToNewProject();
} else {
removeProject();
}
super.setVisible(visible);
}
private void changeToNewProject() {
IProject newProjectHandle= fMainPage.getProjectHandle();
IPath newProjectLocation= fMainPage.getLocationPath();
final boolean initialize= !(newProjectHandle.equals(fCurrProject) && newProjectLocation.equals(fCurrProjectLocation));
IRunnableWithProgress op= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
updateProject(initialize, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
try {
getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
String title= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.desc"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
} catch (InterruptedException e) {
// cancel pressed
}
}
protected void updateProject(boolean initialize, IProgressMonitor monitor) throws CoreException, InterruptedException {
fCurrProject= fMainPage.getProjectHandle();
fCurrProjectLocation= fMainPage.getLocationPath();
boolean noProgressMonitor= !initialize && !fCurrProjectLocation.toFile().exists();
if (monitor == null || noProgressMonitor ) {
monitor= new NullProgressMonitor();
}
try {
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.desc"), 2); //$NON-NLS-1$
createProject(fCurrProject, fCurrProjectLocation, new SubProgressMonitor(monitor, 1));
if (initialize) {
IClasspathEntry[] entries= null;
IPath outputLocation= null;
if (fCurrProjectLocation.toFile().exists() && !Platform.getLocation().equals(fCurrProjectLocation)) {
// detect classpath
if (!fCurrProject.getFile(".classpath").exists()) { //$NON-NLS-1$
// if .classpath exists noneed to look for files
ClassPathDetector detector= new ClassPathDetector(fCurrProject);
entries= detector.getClasspath();
outputLocation= detector.getOutputLocation();
}
}
init(JavaCore.create(fCurrProject), outputLocation, entries, false);
}
monitor.worked(1);
} finally {
monitor.done();
}
}
/**
* Called from the wizard on finish.
*/
public void performFinish(IProgressMonitor monitor) throws CoreException, InterruptedException {
try {
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.createproject.desc"), 3); //$NON-NLS-1$
if (fCurrProject == null) {
updateProject(true, new SubProgressMonitor(monitor, 1));
}
configureJavaProject(new SubProgressMonitor(monitor, 2));
} finally {
monitor.done();
fCurrProject= null;
}
}
private void removeProject() {
if (fCurrProject == null || !fCurrProject.exists()) {
return;
}
IRunnableWithProgress op= new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
boolean noProgressMonitor= Platform.getLocation().equals(fCurrProjectLocation);
if (monitor == null || noProgressMonitor) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.removeproject.desc"), 3); //$NON-NLS-1$
try {
fCurrProject.delete(false, false, monitor);
} catch (CoreException e) {
throw new InvocationTargetException(e);
} finally {
monitor.done();
fCurrProject= null;
}
}
};
try {
getContainer().run(false, true, op);
} catch (InvocationTargetException e) {
String title= NewWizardMessages.getString("NewProjectCreationWizardPage.op_error.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("NewProjectCreationWizardPage.op_error_remove.message"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), title, message);
} catch (InterruptedException e) {
// cancel pressed
}
}
/**
* Called from the wizard on cancel.
*/
public void performCancel() {
removeProject();
}
}
|
31,284 |
Bug 31284 Push down refactoring: Exception when pressing 'preview' the second time
|
20030206 1. select a method, invoke 'push down' (e.g. ChangeCorrectionProposal.setImage) 2. press preview 3. press cancel 4. press preview again java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:130) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.setParent (TextEdit.java:367) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.internalAdd (TextEdit.java:397) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.add (TextEdit.java:112) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.fillWi thRewriteEdits(PushDownRefactoring.java:1157) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.create ChangeManager(PushDownRefactoring.java:771) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.checkI nput(PushDownRefactoring.java:500) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
|
resolved fixed
|
4e0a944
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:43:00Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,284 |
Bug 31284 Push down refactoring: Exception when pressing 'preview' the second time
|
20030206 1. select a method, invoke 'push down' (e.g. ChangeCorrectionProposal.setImage) 2. press preview 3. press cancel 4. press preview again java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:130) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.setParent (TextEdit.java:367) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.internalAdd (TextEdit.java:397) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.add (TextEdit.java:112) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.fillWi thRewriteEdits(PushDownRefactoring.java:1157) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.create ChangeManager(PushDownRefactoring.java:771) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.checkI nput(PushDownRefactoring.java:500) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
|
resolved fixed
|
4e0a944
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:43:00Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
| |
31,284 |
Bug 31284 Push down refactoring: Exception when pressing 'preview' the second time
|
20030206 1. select a method, invoke 'push down' (e.g. ChangeCorrectionProposal.setImage) 2. press preview 3. press cancel 4. press preview again java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:130) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.setParent (TextEdit.java:367) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.internalAdd (TextEdit.java:397) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.add (TextEdit.java:112) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.fillWi thRewriteEdits(PushDownRefactoring.java:1157) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.create ChangeManager(PushDownRefactoring.java:771) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.checkI nput(PushDownRefactoring.java:500) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
|
resolved fixed
|
4e0a944
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:43:00Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,284 |
Bug 31284 Push down refactoring: Exception when pressing 'preview' the second time
|
20030206 1. select a method, invoke 'push down' (e.g. ChangeCorrectionProposal.setImage) 2. press preview 3. press cancel 4. press preview again java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:130) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.setParent (TextEdit.java:367) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.internalAdd (TextEdit.java:397) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.add (TextEdit.java:112) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.fillWi thRewriteEdits(PushDownRefactoring.java:1157) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.create ChangeManager(PushDownRefactoring.java:771) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.checkI nput(PushDownRefactoring.java:500) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
|
resolved fixed
|
4e0a944
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:43:00Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PullUpRefactoring.java
| |
31,284 |
Bug 31284 Push down refactoring: Exception when pressing 'preview' the second time
|
20030206 1. select a method, invoke 'push down' (e.g. ChangeCorrectionProposal.setImage) 2. press preview 3. press cancel 4. press preview again java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:130) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.setParent (TextEdit.java:367) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.internalAdd (TextEdit.java:397) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.add (TextEdit.java:112) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.fillWi thRewriteEdits(PushDownRefactoring.java:1157) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.create ChangeManager(PushDownRefactoring.java:771) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.checkI nput(PushDownRefactoring.java:500) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
|
resolved fixed
|
4e0a944
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:43:00Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,284 |
Bug 31284 Push down refactoring: Exception when pressing 'preview' the second time
|
20030206 1. select a method, invoke 'push down' (e.g. ChangeCorrectionProposal.setImage) 2. press preview 3. press cancel 4. press preview again java.lang.reflect.InvocationTargetException: org.eclipse.jdt.internal.corext.Assert$AssertionFailedException: assertion failed; at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java:130) at org.eclipse.jdt.internal.corext.Assert.isTrue(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.setParent (TextEdit.java:367) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.internalAdd (TextEdit.java:397) at org.eclipse.jdt.internal.corext.textmanipulation.TextEdit.add (TextEdit.java:112) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.fillWi thRewriteEdits(PushDownRefactoring.java:1157) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.create ChangeManager(PushDownRefactoring.java:771) at org.eclipse.jdt.internal.corext.refactoring.structure.PushDownRefactoring.checkI nput(PushDownRefactoring.java:500) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:59) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:94) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:95)
|
resolved fixed
|
4e0a944
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:43:00Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/PushDownRefactoring.java
| |
31,081 |
Bug 31081 Double clicking in packages viewer expands/collapses tree node
|
Build I20030205 - preference double click open mode - show member of compilation unit - double click on a CU observe: tree node gets expanded
|
resolved fixed
|
5743a3a
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T11:52:58Z | 2003-02-06T11:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.packageview;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IOpenable;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.MemberFilterActionGroup;
import org.eclipse.jdt.ui.actions.NavigateActionGroup;
import org.eclipse.jdt.ui.actions.ProjectActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.OpenStrategy;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.actions.MoveResourceAction;
import org.eclipse.ui.actions.OpenInNewWindowAction;
import org.eclipse.ui.actions.RenameResourceAction;
import org.eclipse.ui.views.framelist.BackAction;
import org.eclipse.ui.views.framelist.ForwardAction;
import org.eclipse.ui.views.framelist.FrameList;
import org.eclipse.ui.views.framelist.GoIntoAction;
import org.eclipse.ui.views.framelist.UpAction;
class PackageExplorerActionGroup extends CompositeActionGroup implements ISelectionChangedListener {
private PackageExplorerPart fPart;
private GoIntoAction fZoomInAction;
private BackAction fBackAction;
private ForwardAction fForwardAction;
private UpAction fUpAction;
private GotoTypeAction fGotoTypeAction;
private GotoPackageAction fGotoPackageAction;
private GotoResourceAction fGotoResourceAction;
private CollapseAllAction fCollapseAllAction;
private RenameResourceAction fRenameResourceAction;
private MoveResourceAction fMoveResourceAction;
private NavigateActionGroup fNavigateActionGroup;
private BuildActionGroup fBuildActionGroup;
private CCPActionGroup fCCPActionGroup;
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private MemberFilterActionGroup fMemberFilterActionGroup;
private CustomFiltersActionGroup fCustomFiltersActionGroup;
private int fLastElement;
private static final int INIT= 0;
private static final int RESOURCE= 1;
private static final int REST= 2;
public PackageExplorerActionGroup(PackageExplorerPart part) {
super();
fPart= part;
IWorkbenchPartSite site = fPart.getSite();
Shell shell= site.getShell();
ISelectionProvider provider= site.getSelectionProvider();
IStructuredSelection selection= (IStructuredSelection) provider.getSelection();
setGroups(new ActionGroup[] {
new NewWizardsActionGroup(site),
fNavigateActionGroup= new NavigateActionGroup(fPart),
fCCPActionGroup= new CCPActionGroup(fPart),
new RefactorActionGroup(fPart),
new ImportActionGroup(fPart),
new GenerateActionGroup(fPart),
fBuildActionGroup= new BuildActionGroup(fPart),
new JavaSearchActionGroup(fPart),
new ProjectActionGroup(fPart),
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(part.getViewer(), JavaUI.ID_PACKAGES, shell, createTitleUpdater()),
fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, fPart.getViewer()),
new LayoutActionGroup(part)});
PackagesFrameSource frameSource= new PackagesFrameSource(fPart);
FrameList frameList= new FrameList(frameSource);
frameSource.connectTo(frameList);
fZoomInAction= new GoIntoAction(frameList);
fBackAction= new BackAction(frameList);
fForwardAction= new ForwardAction(frameList);
fUpAction= new UpAction(frameList);
fRenameResourceAction= new RenameResourceAction(shell);
fMoveResourceAction= new MoveResourceAction(shell);
fGotoTypeAction= new GotoTypeAction(fPart);
fGotoPackageAction= new GotoPackageAction(fPart);
fGotoResourceAction= new GotoResourceAction(fPart);
fCollapseAllAction= new CollapseAllAction(fPart);
fMemberFilterActionGroup= new MemberFilterActionGroup(fPart.getViewer(), "PackageView", true); //$NON-NLS-1$
provider.addSelectionChangedListener(this);
update(selection);
fLastElement= INIT;
}
public void dispose() {
if (fMemberFilterActionGroup != null) {
fMemberFilterActionGroup.dispose();
fMemberFilterActionGroup= null;
}
ISelectionProvider provider= fPart.getSite().getSelectionProvider();
provider.removeSelectionChangedListener(this);
super.dispose();
}
//---- Selection changed listener ---------------------------------------------------------
public void selectionChanged(SelectionChangedEvent event) {
fRenameResourceAction.selectionChanged(event);
fMoveResourceAction.selectionChanged(event);
IStructuredSelection selection= (IStructuredSelection)event.getSelection();
update(selection);
}
private void update(IStructuredSelection selection) {
int size= selection.size();
Object element= selection.getFirstElement();
IActionBars actionBars= fPart.getViewSite().getActionBars();
if (size == 1 && element instanceof IResource) {
if (fLastElement != RESOURCE) { // fLastAction in a work around for http://bugs.eclipse.org/bugs/show_bug.cgi?id=30508
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, fRenameResourceAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, fMoveResourceAction);
actionBars.updateActionBars();
fLastElement= RESOURCE;
}
} else {
if (fLastElement != REST) {
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, null);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, null);
actionBars.updateActionBars();
fLastElement= REST;
}
}
}
//---- Persistent state -----------------------------------------------------------------------
/* package */ void restoreFilterAndSorterState(IMemento memento) {
fMemberFilterActionGroup.restoreState(memento);
fWorkingSetFilterActionGroup.restoreState(memento);
fCustomFiltersActionGroup.restoreState(memento);
}
/* package */ void saveFilterAndSorterState(IMemento memento) {
fMemberFilterActionGroup.saveState(memento);
fWorkingSetFilterActionGroup.saveState(memento);
fCustomFiltersActionGroup.saveState(memento);
}
//---- Action Bars ----------------------------------------------------------------------------
public void fillActionBars(IActionBars actionBars) {
super.fillActionBars(actionBars);
setGlobalActionHandlers(actionBars);
fillToolBar(actionBars.getToolBarManager());
fillViewMenu(actionBars.getMenuManager());
}
/* package */ void updateActionBars(IActionBars actionBars) {
actionBars.getToolBarManager().removeAll();
actionBars.getMenuManager().removeAll();
fillActionBars(actionBars);
actionBars.updateActionBars();
}
private void setGlobalActionHandlers(IActionBars actionBars) {
// Navigate Go Into and Go To actions.
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction);
actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_TO_RESOURCE, fGotoResourceAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction);
actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction);
}
/* package */ void fillToolBar(IToolBarManager toolBar) {
toolBar.add(fBackAction);
toolBar.add(fForwardAction);
toolBar.add(fUpAction);
toolBar.add(new Separator());
toolBar.add(fCollapseAllAction);
}
/* package */ void fillViewMenu(IMenuManager menu) {
if (showCompilationUnitChildren()) {
fMemberFilterActionGroup.contributeToViewMenu(menu);
}
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$
}
/* package */ void handleSelectionChanged(SelectionChangedEvent event) {
fZoomInAction.update();
}
//---- Context menu -------------------------------------------------------------------------
public void fillContextMenu(IMenuManager menu) {
IStructuredSelection selection= (IStructuredSelection)getContext().getSelection();
int size= selection.size();
Object element= selection.getFirstElement();
addGotoMenu(menu, element, size);
addOpenNewWindowAction(menu, element);
super.fillContextMenu(menu);
}
private void addGotoMenu(IMenuManager menu, Object element, int size) {
if (size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer))
menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction);
}
private boolean isGoIntoTarget(Object element) {
if (element == null)
return false;
if (element instanceof IJavaElement) {
int type= ((IJavaElement)element).getElementType();
return type == IJavaElement.JAVA_PROJECT ||
type == IJavaElement.PACKAGE_FRAGMENT_ROOT ||
type == IJavaElement.PACKAGE_FRAGMENT;
}
return false;
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new OpenInNewWindowAction(fPart.getSite().getWorkbenchWindow(), (IContainer)element));
}
//---- Key board and mouse handling ------------------------------------------------------------
/* package*/ void handleDoubleClick(DoubleClickEvent event) {
TreeViewer viewer= fPart.getViewer();
Object element= ((IStructuredSelection)event.getSelection()).getFirstElement();
if (viewer.isExpandable(element)) {
if (doubleClickGoesInto()) {
// don't zoom into compilation units and class files
if (element instanceof IOpenable &&
!(element instanceof ICompilationUnit) &&
!(element instanceof IClassFile)) {
fZoomInAction.run();
}
} else {
if (element instanceof ICompilationUnit && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK)
return;
viewer.setExpandedState(element, !viewer.getExpandedState(element));
}
}
}
/* package */ void handleOpen(OpenEvent event) {
IAction openAction= fNavigateActionGroup.getOpenAction();
if (openAction != null && openAction.isEnabled()) {
openAction.run();
return;
}
}
/* package */ void handleKeyEvent(KeyEvent event) {
if (event.stateMask != 0)
return;
if (event.keyCode == SWT.F5) {
IAction refreshAction= fBuildActionGroup.getRefreshAction();
if (refreshAction != null && refreshAction.isEnabled())
refreshAction.run();
} else if (event.character == SWT.DEL) {
IAction delete= fCCPActionGroup.getDeleteAction();
if (delete != null && delete.isEnabled())
delete.run();
}
else if (event.keyCode == SWT.BS) {
if (fUpAction != null && fUpAction.isEnabled())
fUpAction.run();
}
}
private IPropertyChangeListener createTitleUpdater() {
return new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) {
IWorkingSet workingSet= (IWorkingSet)event.getNewValue();
String workingSetName= null;
if (workingSet != null)
workingSetName= workingSet.getName();
fPart.setWorkingSetName(workingSetName);
fPart.updateTitle();
}
}
};
}
private boolean showCompilationUnitChildren() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.SHOW_CU_CHILDREN);
}
private boolean doubleClickGoesInto() {
return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK));
}
}
|
31,202 |
Bug 31202 occurrences in file: shoul beep at me if cannot find anything
|
20030206 i should be beeped at if nothing is found (an invalid expression selected or sth) i never look at the status line status line message + beep = the way to go
|
resolved fixed
|
b26b0f2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T13:35:04Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindOccurrencesInFileAction.java
|
/*******************************************************************************
* Copyright (c) 2003 International Business Machines Corp. and others. All
* rights reserved. This program and the accompanying materials are made
* available under the terms of the Common Public License v0.5 which accompanies
* this distribution, and is available at http://www.eclipse.org/legal/cpl-v05.
* html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
/**
* Action to find all occurrences of a compilation unit member (e.g.
* fields, methods, types, and local variables) in a file.
* <p>
* Action is applicable to selections containing elements of type
* <tt>IMember</tt>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class FindOccurrencesInFileAction extends SelectionDispatchAction {
private JavaEditor fEditor;
private IActionBars fActionBars;
/**
* Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
* that the selection provided by the view part's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the part providing context information for this action
*/
public FindOccurrencesInFileAction(IViewPart part) {
this(part.getSite());
fActionBars= part.getViewSite().getActionBars();
}
/**
* Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
* that the selection provided by the page's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page providing context information for this action
*/
public FindOccurrencesInFileAction(Page page) {
this(page.getSite());
fActionBars= page.getSite().getActionBars();
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public FindOccurrencesInFileAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
private FindOccurrencesInFileAction(IWorkbenchSite site) {
super(site);
setText(SearchMessages.getString("Search.FindOccurrencesInFile.label")); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindOccurrencesInFile.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_OCCURRENCES_IN_FILE_ACTION);
}
//---- Structured Selection -------------------------------------------------------------
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(getMember(selection) != null);
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
private IMember getMember(IStructuredSelection selection) {
if (selection.size() != 1)
return null;
Object o= selection.getFirstElement();
if (o instanceof IMember) {
IMember member= (IMember)o;
IClassFile file= member.getClassFile();
if (file != null) {
try {
if (file.getSourceRange() != null)
return member;
} catch (JavaModelException e) {
return null;
}
}
return member;
}
return null;
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
IMember member= getMember(selection);
FindOccurrencesEngine engine= FindOccurrencesEngine.create(member);
try {
ISourceRange range= member.getNameRange();
String result= engine.run(range.getOffset(), range.getLength());
if (result != null)
showMessage(fActionBars, result);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private static void showMessage(IActionBars actionBars, String msg) {
IStatusLineManager statusLine= actionBars.getStatusLineManager();
if (statusLine != null)
statusLine.setMessage(msg);
}
//---- Text Selection ----------------------------------------------------------------------
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected final void run(ITextSelection ts) {
IJavaElement input= getEditorInput(fEditor);
FindOccurrencesEngine engine= FindOccurrencesEngine.create(input);
try {
String result= engine.run(ts.getOffset(), ts.getLength());
if (result != null)
showMessage(fEditor, result);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private static IJavaElement getEditorInput(JavaEditor editor) {
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
}
private static void showMessage(JavaEditor editor, String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
}
|
31,208 |
Bug 31208 occurrences in file: some names cannot be searched for
|
20030206 package dd; import java.util.List; public class A { A(List elements){ } } select List in the import - ok, finds matches select List in the constructor declaration - no matches strange, it's the same List
|
resolved fixed
|
aa096f8
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T14:45:50Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/FindOccurrencesEngine.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Common Public License v1.0 which accompanies
* this distribution, and is available at http://www.eclipse.org/legal/cpl-v10.
* html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.search;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.texteditor.MarkerUtilities;
import org.eclipse.search.ui.IGroupByKeyComputer;
import org.eclipse.search.ui.ISearchResultView;
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.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.internal.corext.dom.ASTNodes;
import org.eclipse.jdt.internal.corext.dom.NodeFinder;
import org.eclipse.jdt.internal.corext.util.WorkingCopyUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.ui.JavaUI;
public abstract class FindOccurrencesEngine {
public static final String IS_WRITEACCESS= "writeAccess"; //$NON-NLS-1$
public static final String IS_VARIABLE= "variable"; //$NON-NLS-1$
private IRunnableWithProgress fNullOperation= getNullOperation();
private static class SearchGroupByKeyComputer implements IGroupByKeyComputer {
public Object computeGroupByKey(IMarker marker) {
return marker;
}
}
private static class FindOccurencesClassFileEngine extends FindOccurrencesEngine {
private IClassFile fClassFile;
public FindOccurencesClassFileEngine(IClassFile file) {
fClassFile= file;
}
protected CompilationUnit createAST() {
return AST.parseCompilationUnit(fClassFile, true);
}
protected IJavaElement getInput() {
return fClassFile;
}
protected IResource getMarkerOwner() {
return fClassFile.getJavaProject().getProject();
}
protected void addSpecialAttributes(Map attributes) throws JavaModelException {
attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CF_EDITOR);
JavaCore.addJavaElementMarkerAttributes(attributes, fClassFile.getType());
attributes.put(IJavaSearchUIConstants.ATT_JE_HANDLE_ID, fClassFile.getType().getHandleIdentifier());
}
protected ISourceReference getSourceReference() {
return fClassFile;
}
}
private static class FindOccurencesCUEngine extends FindOccurrencesEngine {
private ICompilationUnit fCUnit;
public FindOccurencesCUEngine(ICompilationUnit unit) {
fCUnit= unit;
}
protected CompilationUnit createAST() {
return AST.parseCompilationUnit(fCUnit, true);
}
protected IJavaElement getInput() {
return fCUnit;
}
protected IResource getMarkerOwner() throws JavaModelException {
ICompilationUnit original= WorkingCopyUtil.getOriginal(fCUnit);
return original.getUnderlyingResource();
}
protected void addSpecialAttributes(Map attributes) {
// do nothing
}
protected ISourceReference getSourceReference() {
return fCUnit;
}
}
public static FindOccurrencesEngine create(IJavaElement root) {
ICompilationUnit unit= (ICompilationUnit)root.getAncestor(IJavaElement.COMPILATION_UNIT);
if (unit != null)
return new FindOccurencesCUEngine(unit);
IClassFile cf= (IClassFile)root.getAncestor(IJavaElement.CLASS_FILE);
if (cf != null)
return new FindOccurencesClassFileEngine(cf);
return null;
}
protected abstract CompilationUnit createAST();
protected abstract IJavaElement getInput();
protected abstract ISourceReference getSourceReference();
protected abstract IResource getMarkerOwner() throws JavaModelException;
protected abstract void addSpecialAttributes(Map attributes) throws JavaModelException;
public String run(int offset, int length) throws JavaModelException {
ISourceReference sr= getSourceReference();
if (sr.getSourceRange() == null) {
return SearchMessages.getString("FindOccurrencesEngine.noSource.text"); //$NON-NLS-1$
}
final CompilationUnit root= createAST();
if (root == null) {
return SearchMessages.getString("FindOccurrencesEngine.cannotParse.text"); //$NON-NLS-1$
}
ASTNode node= NodeFinder.perform(root, offset, length);
if (node instanceof VariableDeclarationFragment)
node= ((VariableDeclarationFragment)node).getName();
if (!(node instanceof Name)) {
return SearchMessages.getString("FindOccurrencesEngine.noJavaElement.text"); //$NON-NLS-1$
}
final Name name= (Name)node;
final IBinding target= name.resolveBinding();
final IDocument document= new Document(getSourceReference().getSource());
if (target == null)
return null;
final IWorkspaceRunnable runnable= new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) throws CoreException {
IJavaElement element= getInput();
ISearchResultView view= startSearch(element.getElementName(), name);
OccurrencesFinder finder= new OccurrencesFinder(target);
root.accept(finder);
List matches= finder.getUsages();
List writeMatches= finder.getWriteUsages();
IResource file= getMarkerOwner();
for (Iterator each= matches.iterator(); each.hasNext();) {
ASTNode node= (ASTNode) each.next();
addMatch(
view,
file,
createMarker(file, document, node, writeMatches.contains(node), target instanceof IVariableBinding)
);
}
searchFinished(view);
}
};
run(runnable);
return null;
}
private ISearchResultView startSearch(String fileName, final Name name) {
SearchUI.activateSearchResultView();
ISearchResultView view= SearchUI.getSearchResultView();
String elementName= ASTNodes.asString(name);
if (view != null)
view.searchStarted(
null,
getSingularLabel(elementName, fileName),
getPluralLabel(elementName, fileName),
JavaPluginImages.DESC_OBJS_SEARCH_REF,
"org.eclipse.jdt.ui.JavaFileSearch", //$NON-NLS-1$
new OccurrencesInFileLabelProvider(),
new GotoMarkerAction(),
new SearchGroupByKeyComputer(),
fNullOperation
);
return view;
}
private void addMatch(final ISearchResultView view, IResource file, IMarker marker) {
if (view != null)
view.addMatch("", getGroupByKey(marker), file, marker); //$NON-NLS-1$
}
private void searchFinished(final ISearchResultView view) {
if (view != null)
view.searchFinished();
}
private Object getGroupByKey(IMarker marker) {
try {
return marker.getAttribute(IMarker.LINE_NUMBER);
} catch (CoreException e) {
}
return marker;
}
private IMarker createMarker(IResource file, IDocument document, ASTNode element, boolean writeAccess, boolean isVariable) throws CoreException {
Map attributes= new HashMap(10);
IMarker marker= file.createMarker(SearchUI.SEARCH_MARKER);
int startPosition= element.getStartPosition();
MarkerUtilities.setCharStart(attributes, startPosition);
MarkerUtilities.setCharEnd(attributes, startPosition + element.getLength());
addSpecialAttributes(attributes);
if(writeAccess)
attributes.put(IS_WRITEACCESS, new Boolean(true));
if(isVariable)
attributes.put(IS_VARIABLE, new Boolean(true));
try {
int line= document.getLineOfOffset(startPosition);
MarkerUtilities.setLineNumber(attributes, line);
IRegion region= document.getLineInformation(line);
String lineContents= document.get(region.getOffset(), region.getLength());
MarkerUtilities.setMessage(attributes, lineContents.trim());
} catch (BadLocationException e) {
}
marker.setAttributes(attributes);
return marker;
}
private String getPluralLabel(String nodeContents, String elementName) {
String[] args= new String[] {nodeContents, "{0}", elementName}; //$NON-NLS-1$
return SearchMessages.getFormattedString("JavaSearchInFile.pluralPostfix", args); //$NON-NLS-1$
}
private String getSingularLabel(String nodeContents, String elementName) {
String[] args= new String[] {nodeContents, elementName}; //$NON-NLS-1$
return SearchMessages.getFormattedString("JavaSearchInFile.singularPostfix", args); //$NON-NLS-1$
}
private void run(final IWorkspaceRunnable runnable) {
BusyIndicator.showWhile(null,
new Runnable() {
public void run() {
try {
JavaCore.run(runnable, null);
} catch (CoreException e) {
JavaPlugin.log(e);
}
}
}
);
}
private IRunnableWithProgress getNullOperation() {
return new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
}
};
}
}
|
30,630 |
Bug 30630 nested source folders: unclear error message
|
20030129 create a jproject, a source folder s1 and a nested in it source folder s2 delete s1 open the 'new' wizard and try creating a source folder s1 the error message is very long and compilicated while it should be a simple warning saying 'You have a folder s1 - I will turn it into a source folder fo you' (and then it could automagically add excelusion filter so that s2 is still a source folder)
|
resolved fixed
|
739c70f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T15:00:10Z | 2003-01-30T18:06:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceContainerWorkbookPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.wizards.buildpaths;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.views.navigator.ResourceSorter;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.util.PixelConverter;
import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.ITreeListAdapter;
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;
import org.eclipse.jdt.internal.ui.wizards.dialogfields.TreeListDialogField;
public class SourceContainerWorkbookPage extends BuildPathBasePage {
private ListDialogField fClassPathList;
private IJavaProject fCurrJProject;
private IPath fProjPath;
private Control fSWTControl;
private IWorkspaceRoot fWorkspaceRoot;
private TreeListDialogField fFoldersList;
private StringDialogField fOutputLocationField;
private SelectionButtonDialogField fUseFolderOutputs;
private final int IDX_ADD= 0;
private final int IDX_EDIT= 2;
private final int IDX_REMOVE= 3;
public SourceContainerWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList, StringDialogField outputLocationField) {
fWorkspaceRoot= root;
fClassPathList= classPathList;
fOutputLocationField= outputLocationField;
fSWTControl= null;
SourceContainerAdapter adapter= new SourceContainerAdapter();
String[] buttonLabels;
buttonLabels= new String[] {
/* 0 = IDX_ADDEXIST */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.add.button"), //$NON-NLS-1$
/* 1 */ null,
/* 2 = IDX_EDIT */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.edit.button"), //$NON-NLS-1$
/* 3 = IDX_REMOVE */ NewWizardMessages.getString("SourceContainerWorkbookPage.folders.remove.button") //$NON-NLS-1$
};
fFoldersList= new TreeListDialogField(adapter, buttonLabels, new CPListLabelProvider());
fFoldersList.setDialogFieldListener(adapter);
fFoldersList.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.label")); //$NON-NLS-1$
fFoldersList.setViewerSorter(new CPListElementSorter());
fFoldersList.enableButton(IDX_EDIT, false);
fUseFolderOutputs= new SelectionButtonDialogField(SWT.CHECK);
fUseFolderOutputs.setSelection(false);
fUseFolderOutputs.setLabelText(NewWizardMessages.getString("SourceContainerWorkbookPage.folders.check")); //$NON-NLS-1$
fUseFolderOutputs.setDialogFieldListener(adapter);
}
public void init(IJavaProject jproject) {
fCurrJProject= jproject;
fProjPath= fCurrJProject.getProject().getFullPath();
updateFoldersList();
}
private void updateFoldersList() {
ArrayList folders= new ArrayList();
boolean useFolderOutputs= false;
List cpelements= fClassPathList.getElements();
for (int i= 0; i < cpelements.size(); i++) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (cpe.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
folders.add(cpe);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (hasOutputFolder) {
useFolderOutputs= true;
}
}
}
fFoldersList.setElements(folders);
fUseFolderOutputs.setSelection(useFolderOutputs);
for (int i= 0; i < folders.size(); i++) {
CPListElement cpe= (CPListElement) folders.get(i);
IPath[] patterns= (IPath[]) cpe.getAttribute(CPListElement.EXCLUSION);
boolean hasOutputFolder= (cpe.getAttribute(CPListElement.OUTPUT) != null);
if (patterns.length > 0 || hasOutputFolder) {
fFoldersList.expandElement(cpe, 3);
}
}
}
public Control getControl(Composite parent) {
PixelConverter converter= new PixelConverter(parent);
Composite composite= new Composite(parent, SWT.NONE);
LayoutUtil.doDefaultLayout(composite, new DialogField[] { fFoldersList, fUseFolderOutputs }, true);
LayoutUtil.setHorizontalGrabbing(fFoldersList.getTreeControl(null));
int buttonBarWidth= converter.convertWidthInCharsToPixels(24);
fFoldersList.setButtonsMinWidth(buttonBarWidth);
fSWTControl= composite;
// expand
List elements= fFoldersList.getElements();
for (int i= 0; i < elements.size(); i++) {
CPListElement elem= (CPListElement) elements.get(i);
IPath[] patterns= (IPath[]) elem.getAttribute(CPListElement.EXCLUSION);
IPath output= (IPath) elem.getAttribute(CPListElement.OUTPUT);
if (patterns.length > 0 || output != null) {
fFoldersList.expandElement(elem, 3);
}
}
return composite;
}
private Shell getShell() {
if (fSWTControl != null) {
return fSWTControl.getShell();
}
return JavaPlugin.getActiveWorkbenchShell();
}
private class SourceContainerAdapter implements ITreeListAdapter, IDialogFieldListener {
private final Object[] EMPTY_ARR= new Object[0];
// -------- IListAdapter --------
public void customButtonPressed(TreeListDialogField field, int index) {
sourcePageCustomButtonPressed(field, index);
}
public void selectionChanged(TreeListDialogField field) {
sourcePageSelectionChanged(field);
}
public void doubleClicked(TreeListDialogField field) {
sourcePageDoubleClicked(field);
}
public Object[] getChildren(TreeListDialogField field, Object element) {
if (element instanceof CPListElement) {
return ((CPListElement) element).getChildren(!fUseFolderOutputs.isSelected());
}
return EMPTY_ARR;
}
public Object getParent(TreeListDialogField field, Object element) {
if (element instanceof CPListElementAttribute) {
return ((CPListElementAttribute) element).getParent();
}
return null;
}
public boolean hasChildren(TreeListDialogField field, Object element) {
return (element instanceof CPListElement);
}
// ---------- IDialogFieldListener --------
public void dialogFieldChanged(DialogField field) {
sourcePageDialogFieldChanged(field);
}
}
protected void sourcePageDoubleClicked(TreeListDialogField field) {
if (field == fFoldersList) {
List selection= fFoldersList.getSelectedElements();
if (canEdit(selection)) {
editEntry();
}
}
}
protected void sourcePageCustomButtonPressed(DialogField field, int index) {
if (field == fFoldersList) {
if (index == IDX_ADD) {
List elementsToAdd= new ArrayList(10);
if (fCurrJProject.getProject().exists()) {
CPListElement[] srcentries= openSourceContainerDialog(null);
if (srcentries != null) {
for (int i= 0; i < srcentries.length; i++) {
elementsToAdd.add(srcentries[i]);
}
}
} else {
CPListElement entry= openNewSourceContainerDialog(null);
if (entry != null) {
elementsToAdd.add(entry);
}
}
if (!elementsToAdd.isEmpty()) {
if (fFoldersList.getSize() == 1) {
CPListElement existing= (CPListElement) fFoldersList.getElement(0);
if (existing.getResource() instanceof IProject) {
askForChangingBuildPathDialog(existing);
}
}
HashSet modifiedElements= new HashSet();
askForAddingExclusionPatternsDialog(elementsToAdd, modifiedElements);
fFoldersList.addElements(elementsToAdd);
fFoldersList.postSetSelection(new StructuredSelection(elementsToAdd));
if (!modifiedElements.isEmpty()) {
for (Iterator iter= modifiedElements.iterator(); iter.hasNext();) {
Object elem= iter.next();
fFoldersList.refresh(elem);
fFoldersList.expandElement(elem, 3);
}
}
}
} else if (index == IDX_EDIT) {
editEntry();
} else if (index == IDX_REMOVE) {
removeEntry();
}
}
}
private void editEntry() {
List selElements= fFoldersList.getSelectedElements();
if (selElements.size() != 1) {
return;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
editElementEntry((CPListElement) elem);
} else if (elem instanceof CPListElementAttribute) {
editAttributeEntry((CPListElementAttribute) elem);
}
}
private void editElementEntry(CPListElement elem) {
CPListElement res= null;
IResource resource= elem.getResource();
if (resource.exists()) {
CPListElement[] arr= openSourceContainerDialog(elem);
if (arr != null) {
res= arr[0];
}
} else {
res= openNewSourceContainerDialog(elem);
}
if (res != null) {
fFoldersList.replaceElement(elem, res);
}
}
private void editAttributeEntry(CPListElementAttribute elem) {
String key= elem.getKey();
if (key.equals(CPListElement.OUTPUT)) {
CPListElement selElement= (CPListElement) elem.getParent();
OutputLocationDialog dialog= new OutputLocationDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.OUTPUT, dialog.getOutputLocation());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
} else if (key.equals(CPListElement.EXCLUSION)) {
CPListElement selElement= (CPListElement) elem.getParent();
ExclusionPatternDialog dialog= new ExclusionPatternDialog(getShell(), selElement);
if (dialog.open() == OutputLocationDialog.OK) {
selElement.setAttribute(CPListElement.EXCLUSION, dialog.getExclusionPattern());
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
}
}
}
protected void sourcePageSelectionChanged(DialogField field) {
List selected= fFoldersList.getSelectedElements();
fFoldersList.enableButton(IDX_EDIT, canEdit(selected));
fFoldersList.enableButton(IDX_REMOVE, canRemove(selected));
}
private void removeEntry() {
List selElements= fFoldersList.getSelectedElements();
for (int i= selElements.size() - 1; i >= 0 ; i--) {
Object elem= selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
String key= attrib.getKey();
Object value= key.equals(CPListElement.EXCLUSION) ? new Path[0] : null;
attrib.getParent().setAttribute(key, value);
selElements.remove(i);
}
}
if (selElements.isEmpty()) {
fFoldersList.refresh();
fClassPathList.dialogFieldChanged(); // validate
} else {
fFoldersList.removeElements(selElements);
}
}
private boolean canRemove(List selElements) {
if (selElements.size() == 0) {
return false;
}
for (int i= 0; i < selElements.size(); i++) {
Object elem= (Object) selElements.get(i);
if (elem instanceof CPListElementAttribute) {
CPListElementAttribute attrib= (CPListElementAttribute) elem;
if (attrib.getKey().equals(CPListElement.EXCLUSION)) {
if (((IPath[]) attrib.getValue()).length == 0) {
return false;
}
} else if (attrib.getValue() == null) {
return false;
}
} else if (elem instanceof CPListElement) {
CPListElement curr= (CPListElement) elem;
if (curr.getParentContainer() != null) {
return false;
}
}
}
return true;
}
private boolean canEdit(List selElements) {
if (selElements.size() != 1) {
return false;
}
Object elem= selElements.get(0);
if (fFoldersList.getIndexOfElement(elem) != -1) {
return true;
}
if (elem instanceof CPListElementAttribute) {
return true;
}
return false;
}
private void sourcePageDialogFieldChanged(DialogField field) {
if (fCurrJProject == null) {
// not initialized
return;
}
if (field == fUseFolderOutputs) {
if (!fUseFolderOutputs.isSelected()) {
int nFolders= fFoldersList.getSize();
for (int i= 0; i < nFolders; i++) {
CPListElement cpe= (CPListElement) fFoldersList.getElement(i);
cpe.setAttribute(CPListElement.OUTPUT, null);
}
}
fFoldersList.refresh();
} else if (field == fFoldersList) {
updateClasspathList();
}
}
private void updateClasspathList() {
List cpelements= fClassPathList.getElements();
List srcelements= fFoldersList.getElements();
boolean changeDone= false;
CPListElement lastSourceFolder= null;
// backwards, as entries will be deleted
for (int i= cpelements.size() - 1; i >= 0 ; i--) {
CPListElement cpe= (CPListElement)cpelements.get(i);
if (isEntryKind(cpe.getEntryKind())) {
// if it is a source folder, but not one of the accepted entries, remove it
// at the same time, for the entries seen, remove them from the accepted list
if (!srcelements.remove(cpe)) {
cpelements.remove(i);
changeDone= true;
} else if (lastSourceFolder == null) {
lastSourceFolder= cpe;
}
}
}
if (!srcelements.isEmpty()) {
int insertIndex= (lastSourceFolder == null) ? 0 : cpelements.indexOf(lastSourceFolder) + 1;
cpelements.addAll(insertIndex, srcelements);
changeDone= true;
}
if (changeDone) {
fClassPathList.setElements(cpelements);
}
}
private CPListElement openNewSourceContainerDialog(CPListElement existing) {
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.NewSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
IProject proj= fCurrJProject.getProject();
NewSourceFolderDialog dialog= new NewSourceFolderDialog(getShell(), title, proj, getExistingContainers(existing), existing);
dialog.setMessage(NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.NewSourceFolderDialog.description", fProjPath.toString())); //$NON-NLS-1$
if (dialog.open() == NewContainerDialog.OK) {
IResource folder= dialog.getSourceFolder();
return newCPSourceElement(folder);
}
return null;
}
/**
* Asks to change the output folder to 'proj/bin' when no source folders were existing
*/
private void askForChangingBuildPathDialog(CPListElement existing) {
IPath outputFolder= new Path(fOutputLocationField.getText());
IPath newOutputFolder= null;
String message;
if (outputFolder.segmentCount() == 1) {
String outputFolderName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME);
newOutputFolder= outputFolder.append(outputFolderName);
message= NewWizardMessages.getFormattedString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project_and_output.message", newOutputFolder); //$NON-NLS-1$
} else {
message= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.project.message"); //$NON-NLS-1$
}
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.ChangeOutputLocationDialog.title"); //$NON-NLS-1$
if (MessageDialog.openQuestion(getShell(), title, message)) {
fFoldersList.removeElement(existing);
if (newOutputFolder != null) {
fOutputLocationField.setText(newOutputFolder.toString());
}
}
}
private void askForAddingExclusionPatternsDialog(List newEntries, Set modifiedEntries) {
for (int i= 0; i < newEntries.size(); i++) {
CPListElement curr= (CPListElement) newEntries.get(i);
addExclusionPatterns(curr, modifiedEntries);
}
if (!modifiedEntries.isEmpty()) {
String title= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.title"); //$NON-NLS-1$
String message= NewWizardMessages.getString("SourceContainerWorkbookPage.exclusion_added.message"); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), title, message);
}
}
private void addExclusionPatterns(CPListElement newEntry, Set modifiedEntries) {
IPath entryPath= newEntry.getPath();
List existing= fFoldersList.getElements();
for (int i= 0; i < existing.size(); i++) {
CPListElement curr= (CPListElement) existing.get(i);
IPath currPath= curr.getPath();
if (currPath.isPrefixOf(entryPath)) {
IPath[] exclusionFilters= (IPath[]) curr.getAttribute(CPListElement.EXCLUSION);
if (!JavaModelUtil.isExcludedPath(entryPath, exclusionFilters)) {
IPath pathToExclude= entryPath.removeFirstSegments(currPath.segmentCount()).addTrailingSeparator();
IPath[] newExclusionFilters= new IPath[exclusionFilters.length + 1];
System.arraycopy(exclusionFilters, 0, newExclusionFilters, 0, exclusionFilters.length);
newExclusionFilters[exclusionFilters.length]= pathToExclude;
curr.setAttribute(CPListElement.EXCLUSION, newExclusionFilters);
modifiedEntries.add(curr);
}
}
}
}
private CPListElement[] openSourceContainerDialog(CPListElement existing) {
Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class };
TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null, getExistingContainers(null));
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();
String title= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.title") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$
String message= (existing == null) ? NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.new.description") : NewWizardMessages.getString("SourceContainerWorkbookPage.ExistingSourceFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$
FolderSelectionDialog dialog= new FolderSelectionDialog(getShell(), lp, cp);
dialog.setValidator(validator);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.addFilter(filter);
dialog.setInput(fCurrJProject.getProject().getParent());
dialog.setSorter(new ResourceSorter(ResourceSorter.NAME));
if (existing == null) {
dialog.setInitialSelection(fCurrJProject.getProject());
} else {
dialog.setInitialSelection(existing.getResource());
}
if (dialog.open() == FolderSelectionDialog.OK) {
Object[] elements= dialog.getResult();
CPListElement[] res= new CPListElement[elements.length];
for (int i= 0; i < res.length; i++) {
IResource elem= (IResource)elements[i];
res[i]= newCPSourceElement(elem);
}
return res;
}
return null;
}
private List getExistingContainers(CPListElement existing) {
List res= new ArrayList();
List cplist= fFoldersList.getElements();
for (int i= 0; i < cplist.size(); i++) {
CPListElement elem= (CPListElement)cplist.get(i);
if (elem != existing) {
IResource resource= elem.getResource();
if (resource instanceof IContainer) { // defensive code
res.add(resource);
}
}
}
return res;
}
private CPListElement newCPSourceElement(IResource res) {
Assert.isNotNull(res);
return new CPListElement(fCurrJProject, IClasspathEntry.CPE_SOURCE, res.getFullPath(), res);
}
/*
* @see BuildPathBasePage#getSelection
*/
public List getSelection() {
return fFoldersList.getSelectedElements();
}
/*
* @see BuildPathBasePage#setSelection
*/
public void setSelection(List selElements) {
fFoldersList.selectElements(new StructuredSelection(selElements));
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathBasePage#isEntryKind(int)
*/
public boolean isEntryKind(int kind) {
return kind == IClasspathEntry.CPE_SOURCE;
}
}
|
31,213 |
Bug 31213 occurrences in file: exception trace in log
|
20030206 after i ran the action on a file outside of my classpath !ENTRY org.eclipse.jdt.ui 4 10001 Feb 07, 2003 10:48:29.593 !MESSAGE Internal Error !STACK 1 Java Model Exception: Java Model Status [ddd [in xxx] does not exist.] at org.eclipse.jdt.internal.core.JavaElement.newNotPresentException (JavaElement.java:482) at org.eclipse.jdt.internal.core.PackageFragmentRoot.getUnderlyingResource (PackageFragmentRoot.java:714) at org.eclipse.jdt.internal.core.PackageFragment.getUnderlyingResource (PackageFragment.java:249) at org.eclipse.jdt.internal.core.Openable.getUnderlyingResource (Openable.java:235) at org.eclipse.jdt.internal.core.CompilationUnit.getUnderlyingResource (CompilationUnit.java:546) at org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine$FindOccurencesCUEngine. getMarkerOwner(FindOccurrencesEngine.java:116) at org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine$1.run (FindOccurrencesEngine.java:178) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation (BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:343) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:671) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2633) at org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine$2.run (FindOccurrencesEngine.java:274) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:65) at org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.run (FindOccurrencesEngine.java:270) at org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.run (FindOccurrencesEngine.java:190) at org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (FindOccurrencesInFileAction.java:165) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:193) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:169) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:177) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:207) at org.eclipse.ui.internal.WWinKeyBindingService.invoke (WWinKeyBindingService.java:135) at org.eclipse.ui.internal.WWinKeyBindingService.pressed (WWinKeyBindingService.java:116) at org.eclipse.ui.internal.WWinKeyBindingService$6.widgetSelected (WWinKeyBindingService.java:365) at org.eclipse.ui.internal.AcceleratorMenu$2.handleEvent (AcceleratorMenu.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at java.lang.reflect.Method.invoke(Native Method) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539)
|
resolved fixed
|
d31adb7
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T15:02:13Z | 2003-02-07T09:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindOccurrencesInFileAction.java
|
/*******************************************************************************
* Copyright (c) 2003 International Business Machines Corp. and others. All
* rights reserved. This program and the accompanying materials are made
* available under the terms of the Common Public License v0.5 which accompanies
* this distribution, and is available at http://www.eclipse.org/legal/cpl-v05.
* html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
/**
* Action to find all occurrences of a compilation unit member (e.g.
* fields, methods, types, and local variables) in a file.
* <p>
* Action is applicable to selections containing elements of type
* <tt>IMember</tt>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class FindOccurrencesInFileAction extends SelectionDispatchAction {
private JavaEditor fEditor;
private IActionBars fActionBars;
/**
* Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
* that the selection provided by the view part's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the part providing context information for this action
*/
public FindOccurrencesInFileAction(IViewPart part) {
this(part.getSite());
fActionBars= part.getViewSite().getActionBars();
}
/**
* Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
* that the selection provided by the page's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page providing context information for this action
*/
public FindOccurrencesInFileAction(Page page) {
this(page.getSite());
fActionBars= page.getSite().getActionBars();
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public FindOccurrencesInFileAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
private FindOccurrencesInFileAction(IWorkbenchSite site) {
super(site);
setText(SearchMessages.getString("Search.FindOccurrencesInFile.label")); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindOccurrencesInFile.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_OCCURRENCES_IN_FILE_ACTION);
}
//---- Structured Selection -------------------------------------------------------------
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(getMember(selection) != null);
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
private IMember getMember(IStructuredSelection selection) {
if (selection.size() != 1)
return null;
Object o= selection.getFirstElement();
if (o instanceof IMember) {
IMember member= (IMember)o;
IClassFile file= member.getClassFile();
if (file != null) {
try {
if (file.getSourceRange() != null)
return member;
} catch (JavaModelException e) {
return null;
}
}
return member;
}
return null;
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
IMember member= getMember(selection);
FindOccurrencesEngine engine= FindOccurrencesEngine.create(member);
try {
ISourceRange range= member.getNameRange();
String result= engine.run(range.getOffset(), range.getLength());
if (result != null)
showMessage(getShell(), fActionBars, result);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private static void showMessage(Shell shell, IActionBars actionBars, String msg) {
IStatusLineManager statusLine= actionBars.getStatusLineManager();
if (statusLine != null)
statusLine.setMessage(msg);
shell.getDisplay().beep();
}
//---- Text Selection ----------------------------------------------------------------------
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected final void run(ITextSelection ts) {
IJavaElement input= getEditorInput(fEditor);
FindOccurrencesEngine engine= FindOccurrencesEngine.create(input);
try {
String result= engine.run(ts.getOffset(), ts.getLength());
if (result != null)
showMessage(getShell(), fEditor, result);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private static IJavaElement getEditorInput(JavaEditor editor) {
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
}
private static void showMessage(Shell shell, JavaEditor editor, String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
shell.getDisplay().beep();
}
}
|
31,576 |
Bug 31576 2.1M5 NullPointerException in ClassPathDetector.detectOutputFolder
|
I'm attempting to create a new Java Project and point it to a directory in my ClearCase directory. It appears that in an attempt to discover source directories and libraries, a NullPointerException is being thrown. This is in version 2.1 M5. The relevant information from the log is: !SESSION Feb 11, 2003 12:35:23.406 --------------------------------------------- java.version=1.4.1_01 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86, WS=win32, NL=en_US Command-line arguments: -os win32 -ws win32 -arch x86 -data c:\source\eclipse-workspace -install file:C:/software/eclipse/ !ENTRY com.rational.clearcase 1 0 Feb 11, 2003 12:35:23.406 !MESSAGE traceLevel = 2(option=null) !ENTRY org.eclipse.jdt.ui 4 10001 Feb 11, 2003 12:44:56.854 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:307) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:246) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:716) at org.eclipse.jdt.internal.ui.wizards.NewElementWizard.performFinish(NewElementWizard.java:86) at org.eclipse.jface.wizard.WizardDialog.finishPressed(WizardDialog.java:570) at org.eclipse.jface.wizard.WizardDialog.buttonPressed(WizardDialog.java:308) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:417) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:87) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.jface.window.Window.runEventLoop(Window.java:561) at org.eclipse.jface.window.Window.open(Window.java:541) at org.eclipse.ui.actions.NewProjectAction.run(NewProjectAction.java:97) at org.eclipse.jface.action.Action.runWithEvent(Action.java:804) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:450) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent(ActionContributionItem.java:398) at org.eclipse.jface.action.ActionContributionItem.access$0(ActionContributionItem.java:392) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent(ActionContributionItem.java:72) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:836) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1692) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1410) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1289) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1272) at org.eclipse.core.internal.boot.InternalBootLoader.run(InternalBootLoader.java:845) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:324) at org.eclipse.core.launcher.Main.basicRun(Main.java:247) at org.eclipse.core.launcher.Main.run(Main.java:703) at org.eclipse.core.launcher.Main.main(Main.java:539) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.wizards.ClassPathDetector.detectOutputFolder(ClassPathDetector.java:122) at org.eclipse.jdt.internal.ui.wizards.ClassPathDetector.detectClasspath(ClassPathDetector.java:77) at org.eclipse.jdt.internal.ui.wizards.ClassPathDetector.<init>(ClassPathDetector.java:56) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizardPage.updateProject(NewProjectCreationWizardPage.java:109) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizardPage.performFinish(NewProjectCreationWizardPage.java:129) at org.eclipse.jdt.internal.ui.wizards.NewProjectCreationWizard.finishPage(NewProjectCreationWizard.java:56) at org.eclipse.jdt.internal.ui.wizards.NewElementWizard$2.run(NewElementWizard.java:79) at org.eclipse.jdt.internal.core.BatchOperation.executeOperation(BatchOperation.java:34) at org.eclipse.jdt.internal.core.JavaModelOperation.execute(JavaModelOperation.java:343) at org.eclipse.jdt.internal.core.JavaModelOperation.run(JavaModelOperation.java:671) at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:1588) at org.eclipse.jdt.core.JavaCore.run(JavaCore.java:2633) at org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter.run(WorkbenchRunnableAdapter.java:32) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:296) ... 34 more
|
resolved fixed
|
5bfd2cf
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T15:05:17Z | 2003-02-11T19:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/ClassPathDetector.java
|
package org.eclipse.jdt.internal.ui.wizards;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.JavaConventions;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.ToolFactory;
import org.eclipse.jdt.core.compiler.CharOperation;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.ui.PreferenceConstants;
/**
*/
public class ClassPathDetector implements IResourceProxyVisitor {
private HashMap fSourceFolders;
private List fClassFiles;
private HashSet fJARFiles;
private IProject fProject;
private IPath fResultOutputFolder;
private IClasspathEntry[] fResultClasspath;
public ClassPathDetector(IProject project) throws CoreException {
fSourceFolders= new HashMap();
fJARFiles= new HashSet(10);
fClassFiles= new ArrayList(100);
fProject= project;
project.accept(this, IResource.NONE);
fResultClasspath= null;
fResultOutputFolder= null;
detectClasspath();
}
private boolean isNested(IPath path, Iterator iter) {
while (iter.hasNext()) {
IPath other= (IPath) iter.next();
if (other.isPrefixOf(path)) {
return true;
}
}
return false;
}
/**
* Method detectClasspath.
*/
private void detectClasspath() {
ArrayList cpEntries= new ArrayList();
detectSourceFolders(cpEntries);
IPath outputLocation= detectOutputFolder(cpEntries);
detectLibraries(cpEntries, outputLocation);
if (cpEntries.isEmpty() && fClassFiles.isEmpty()) {
return;
}
IClasspathEntry[] jreEntries= PreferenceConstants.getDefaultJRELibrary();
for (int i= 0; i < jreEntries.length; i++) {
cpEntries.add(jreEntries[i]);
}
IClasspathEntry[] entries= (IClasspathEntry[]) cpEntries.toArray(new IClasspathEntry[cpEntries.size()]);
if (!JavaConventions.validateClasspath(JavaCore.create(fProject), entries, outputLocation).isOK()) {
return;
}
fResultClasspath= entries;
fResultOutputFolder= outputLocation;
}
private IPath findInSourceFolders(IPath path) {
Iterator iter= fSourceFolders.keySet().iterator();
while (iter.hasNext()) {
Object key= iter.next();
List cus= (List) fSourceFolders.get(key);
if (cus.contains(path)) {
return (IPath) key;
}
}
return null;
}
private IPath detectOutputFolder(List entries) {
HashSet classFolders= new HashSet();
for (Iterator iter= fClassFiles.iterator(); iter.hasNext();) {
IFile file= (IFile) iter.next();
IPath location= file.getLocation();
if (location == null) {
continue;
}
IClassFileReader reader= ToolFactory.createDefaultClassFileReader(location.toOSString(), IClassFileReader.CLASSFILE_ATTRIBUTES);
char[] className= reader.getClassName();
char[] sourceName= reader.getSourceFileAttribute().getSourceFileName();
if (className != null && sourceName != null) {
IPath packPath= file.getParent().getFullPath();
int idx= CharOperation.lastIndexOf('/', className) + 1;
IPath relPath= new Path(new String(className, 0, idx));
IPath cuPath= relPath.append(new String(sourceName));
IPath resPath= null;
if (idx == 0) {
resPath= packPath;
} else {
IPath folderPath= getFolderPath(packPath, relPath);
if (folderPath != null) {
resPath= folderPath;
}
}
if (resPath != null) {
IPath path= findInSourceFolders(cuPath);
if (path != null) {
return resPath;
} else {
classFolders.add(resPath);
}
}
}
}
IPath projPath= fProject.getFullPath();
if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
return projPath;
} else {
IPath path= projPath.append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
while (classFolders.contains(path)) {
path= new Path(path.toString() + '1');
}
return path;
}
}
private void detectLibraries(ArrayList cpEntries, IPath outputLocation) {
Set sourceFolderSet= fSourceFolders.keySet();
for (Iterator iter= fJARFiles.iterator(); iter.hasNext();) {
IPath path= (IPath) iter.next();
if (isNested(path, sourceFolderSet.iterator())) {
continue;
}
if (outputLocation != null && outputLocation.isPrefixOf(path)) {
continue;
}
IClasspathEntry entry= JavaCore.newLibraryEntry(path, null, null);
cpEntries.add(entry);
}
}
private void detectSourceFolders(ArrayList resEntries) {
Set sourceFolderSet= fSourceFolders.keySet();
for (Iterator iter= sourceFolderSet.iterator(); iter.hasNext();) {
IPath path= (IPath) iter.next();
ArrayList excluded= new ArrayList();
for (Iterator inner= sourceFolderSet.iterator(); inner.hasNext();) {
IPath other= (IPath) inner.next();
if (!path.equals(other) && path.isPrefixOf(other)) {
IPath pathToExclude= other.removeFirstSegments(path.segmentCount()).addTrailingSeparator();
excluded.add(pathToExclude);
}
}
IPath[] excludedPaths= (IPath[]) excluded.toArray(new IPath[excluded.size()]);
IClasspathEntry entry= JavaCore.newSourceEntry(path, excludedPaths);
resEntries.add(entry);
}
}
private void visitCompilationUnit(IFile file) throws JavaModelException {
ICompilationUnit cu= JavaCore.createCompilationUnitFrom(file);
if (cu != null) {
ICompilationUnit workingCopy= null;
try {
workingCopy= (ICompilationUnit) cu.getWorkingCopy();
synchronized(workingCopy) {
workingCopy.reconcile();
}
IPath packPath= file.getParent().getFullPath();
IPackageDeclaration[] decls= workingCopy.getPackageDeclarations();
String cuName= file.getName();
if (decls.length == 0) {
addToMap(fSourceFolders, packPath, new Path(cuName));
} else {
IPath relpath= new Path(decls[0].getElementName().replace('.', '/'));
IPath folderPath= getFolderPath(packPath, relpath);
if (folderPath != null) {
addToMap(fSourceFolders, folderPath, relpath.append(cuName));
}
}
} finally {
if (workingCopy != null) {
workingCopy.destroy();
}
}
}
}
private void addToMap(HashMap map, IPath folderPath, IPath relPath) {
List list= (List) map.get(folderPath);
if (list == null) {
list= new ArrayList(50);
map.put(folderPath, list);
}
list.add(relPath);
}
private IPath getFolderPath(IPath packPath, IPath relpath) {
int remainingSegments= packPath.segmentCount() - relpath.segmentCount();
if (remainingSegments >= 0) {
IPath common= packPath.removeFirstSegments(remainingSegments);
if (common.equals(relpath)) {
return packPath.uptoSegment(remainingSegments);
}
}
return null;
}
/* (non-Javadoc)
* @see org.eclipse.core.resources.IResourceProxyVisitor#visit(org.eclipse.core.resources.IResourceProxy)
*/
public boolean visit(IResourceProxy proxy) throws CoreException {
if (proxy.getType() == IResource.FILE) {
String name= proxy.getName();
String extension= Signature.getSimpleName(name);
if ("java".equalsIgnoreCase(extension)) { //$NON-NLS-1$
visitCompilationUnit((IFile) proxy.requestResource());
} else if ("class".equalsIgnoreCase(extension)) { //$NON-NLS-1$
fClassFiles.add((IFile) proxy.requestResource());
} else if ("jar".equalsIgnoreCase(extension)) { //$NON-NLS-1$
fJARFiles.add(proxy.requestFullPath());
}
return false;
}
return true;
}
public IPath getOutputLocation() {
return fResultOutputFolder;
}
public IClasspathEntry[] getClasspath() {
return fResultClasspath;
}
}
|
30,870 |
Bug 30870 NameMatcher - incorrect way of testing [code manipulation]
|
20030204 NameMatcher has a main method that is used for testing it should be removed and proper tests should be added to the jdt ui suite (it's the only class in jdt ui with a main method)
|
resolved fixed
|
fe373a5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T15:32:31Z | 2003-02-04T14:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NameMatcher.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
public class NameMatcher {
/**
* Returns a similarity value of the two names.
* The range of is from 0 to 256. no similarity is negative
*/
public static boolean isSimilarName(String name1, String name2) {
return getSimilarity(name1, name2) >= 0;
}
/**
* Returns a similarity value of the two names.
* The range of is from 0 to 256. no similarity is negative
*/
public static int getSimilarity(String name1, String name2) {
if (name1.length() > name2.length()) {
String tmp= name1;
name1= name2;
name2= tmp;
}
int name1len= name1.length();
int name2len= name2.length();
int nMatched= 0;
int i= 0;
while (i < name1len && isSimilarChar(name1.charAt(i), name2.charAt(i))) {
i++;
nMatched++;
}
int k= name1len;
int diff= name2len - name1len;
while (k > i && isSimilarChar(name1.charAt(k - 1), name2.charAt(k + diff - 1))) {
k--;
nMatched++;
}
if (nMatched == name2len) {
return 200;
}
if (name2len - nMatched > nMatched) {
return -1;
}
int tolerance= name2len / 4 + 1;
return (tolerance - (k - i)) * 256 / tolerance;
}
private static boolean isSimilarChar(char ch1, char ch2) {
return Character.toLowerCase(ch1) == Character.toLowerCase(ch2);
}
private static void test(String name1, String name2) {
int sim= getSimilarity(name1, name2);
System.out.println(name1 + " - " + name2 + " : " + sim); //$NON-NLS-1$ //$NON-NLS-2$
}
public static void main(String[] arguments) {
test("XXX", "XSecurity"); //$NON-NLS-1$ //$NON-NLS-2$
test("runner", "gunner"); //$NON-NLS-1$ //$NON-NLS-2$
test("rundner", "gunner"); //$NON-NLS-1$ //$NON-NLS-2$
test("rundner", "rund"); //$NON-NLS-1$ //$NON-NLS-2$
test("test", "rund"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
|
31,556 |
Bug 31556 Export jar from Navigator view fails
|
(M5 build) In Navigator view (resource perspective), right-click on a src/ directory containing your sources, select export->jar file and the package selector opens with no resource selected (and finish button disabled); but it seems that the src/ dir is really selected, because if you re-select it in the window, it ends up with a "jar creation failed" and a lot of duplicate entries in the error log. If you try the same from the Projects view (Java browsing perspective), it works fine.
|
resolved fixed
|
01d8cb2
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:06:29Z | 2003-02-11T16:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/jarpackager/JarPackageWizardPage.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* 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.jface.wizard.WizardPage;
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.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.jarpackager.JarPackageData;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.filters.EmptyInnerPackageFilter;
import org.eclipse.jdt.internal.ui.util.SWTUtil;
import org.eclipse.jdt.internal.ui.viewsupport.LibraryFilter;
/**
* Page 1 of the JAR Package wizard
*/
class JarPackageWizardPage extends WizardExportResourcesPage implements IJarPackageWizardPage {
private JarPackageData fJarPackage;
private IStructuredSelection fInitialSelection;
private CheckboxTreeAndListGroup fInputGroup;
// widgets
private Text fSourceNameField;
private Button fExportClassFilesCheckbox;
private Button fExportJavaFilesCheckbox;
private Combo fDestinationNamesCombo;
private Button fDestinationBrowseButton;
private Button fCompressCheckbox;
private Button fOverwriteCheckbox;
private Text fDescriptionFileText;
// 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= 480;
private final static int SIZING_SELECTION_WIDGET_HEIGHT= 150;
/**
* Create an instance of this class
*/
public JarPackageWizardPage(JarPackageData 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 "." + JarPackagerUtil.JAR_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 (!((JarPackageWizard)getWizard()).isInitializingFromJarPackage())
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.setElements(getSelectedElements());
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(new Path(directoryNames[0]));
}
}
/**
* Stores the widget values in the JAR package.
*/
protected void updateModel() {
if (getControl() == null)
return;
// source
fJarPackage.setElements(getSelectedElements());
fJarPackage.setExportClassFiles(fExportClassFilesCheckbox.getSelection());
fJarPackage.setExportJavaFiles(fExportJavaFilesCheckbox.getSelection());
// destination
String comboText= fDestinationNamesCombo.getText();
IPath path= new Path(comboText);
if (!new File(comboText).isAbsolute())
// prepend workspace path
path= getWorkspaceLocation().append(path);
if (path.segmentCount() > 0 && ensureTargetFileIsValid(path.toFile()) && path.getFileExtension() == null) //$NON-NLS-1$
// append .jar
path= path.addFileExtension(JarPackagerUtil.JAR_EXTENSION);
fJarPackage.setJarLocation(path);
// options
fJarPackage.setCompress(fCompressCheckbox.getSelection());
fJarPackage.setOverwrite(fOverwriteCheckbox.getSelection());
}
/**
* 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() && fDestinationNamesCombo.getText().length() > 0) {
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() == SaveAsDialog.OK) {
IPath path= dialog.getResult();
path= path.removeFileExtension().addFileExtension(JarPackagerUtil.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= ResourcesPlugin.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 StandardJavaElementContentProvider() {
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(ResourcesPlugin.getWorkspace().getRoot()),
treeContentProvider,
new JavaElementLabelProvider(labelFlags),
new StandardJavaElementContentProvider(),
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() {
boolean complete= validateSourceGroup();
complete= validateDestinationGroup() && complete;
complete= validateOptionsGroup() && complete;
if (complete)
setErrorMessage(null);
return complete;
}
/*
* Implements method from Listener
*/
public void handleEvent(Event e) {
if (getControl() == null)
return;
update();
}
protected void update() {
updateModel();
updateWidgetEnablements();
updatePageCompletion();
}
protected void updatePageCompletion() {
boolean pageComplete= isPageComplete();
setPageComplete(pageComplete);
if (pageComplete)
setErrorMessage(null);
}
/*
* Overrides method from WizardDataTransferPage
*/
protected boolean validateDestinationGroup() {
if (fDestinationNamesCombo.getText().length() == 0) {
// Clear error
if (getErrorMessage() != null)
setErrorMessage(null);
if (getMessage() != null)
setMessage(null);
return false;
}
if (fJarPackage.getJarLocation().toString().endsWith("/")) { //$NON-NLS-1$
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.exportDestinationMustNotBeDirectory")); //$NON-NLS-1$
fDestinationNamesCombo.setFocus();
return false;
}
if (getWorkspaceLocation() != null && getWorkspaceLocation().isPrefixOf(fJarPackage.getJarLocation())) {
int segments= getWorkspaceLocation().matchingFirstSegments(fJarPackage.getJarLocation());
IPath path= fJarPackage.getJarLocation().removeFirstSegments(segments);
IResource resource= ResourcesPlugin.getWorkspace().getRoot().findMember(path);
if (resource != null && resource.getType() == IResource.FILE) {
// test if included
if (JarPackagerUtil.contains(JarPackagerUtil.asResources(fJarPackage.getElements()), (IFile)resource)) {
setErrorMessage(JarPackagerMessages.getString("JarPackageWizardPage.error.cantExportJARIntoItself")); //$NON-NLS-1$
return false;
}
}
}
// Inform user about relative directory
String currentMessage= getMessage();
if (!(new File(fDestinationNamesCombo.getText()).isAbsolute())) {
if (currentMessage == null)
setMessage(JarPackagerMessages.getString("JarPackageWizardPage.info.relativeExportDestination"), WizardPage.INFORMATION); //$NON-NLS-1$
} else {
if (currentMessage != null)
setMessage(null);
}
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) {
if (getErrorMessage() != null)
setErrorMessage(null);
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;
}
if (getErrorMessage() != null)
setErrorMessage(null);
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();
}
Object[] getSelectedElementsWithoutContainedChildren() {
Set closure= removeContainedChildren(fInputGroup.getWhiteCheckedTreeItems());
closure.addAll(getExportedNonContainers());
return closure.toArray();
}
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;
}
private Object[] getSelectedElements() {
return getSelectedResources().toArray();
}
/**
* @return the location or <code>null</code>
*/
private IPath getWorkspaceLocation() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation();
}
}
|
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/CopyRefactoring.java
| |
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/core
| |
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgRefactoring.java
| |
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtCopyAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.util.List;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.CopyProjectAction;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
public class JdtCopyAction extends ReorgDestinationAction {
protected JdtCopyAction(IWorkbenchSite site) {
super(site);
}
ReorgRefactoring createRefactoring(List elements){
return new CopyRefactoring(elements, new ReorgQueries(), createUpdateClasspathQuery(getShell()));
}
String getActionName() {
return ReorgMessages.getString("copyAction.name"); //$NON-NLS-1$
}
String getDestinationDialogMessage() {
return ReorgMessages.getString("copyAction.destination.label"); //$NON-NLS-1$
}
/* non java-doc
* @see IRefactoringAction#canOperateOn(IStructuredSelection)
*/
public boolean canOperateOn(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
if (ClipboardActionUtil.hasOnlyProjects(selection))
return selection.size() == 1;
else
return super.canOperateOn(selection);
}
protected void run(IStructuredSelection selection) {
if (ClipboardActionUtil.hasOnlyProjects(selection)){
copyProject(selection);
} else {
super.run(selection);
}
}
private void copyProject(IStructuredSelection selection){
CopyProjectAction action= new CopyProjectAction(JavaPlugin.getActiveWorkbenchShell());
action.selectionChanged(selection);
action.run();
}
public static IPackageFragmentRootManipulationQuery createUpdateClasspathQuery(Shell shell){
String messagePattern= ReorgMessages.getString("JdtCopyAction.referenced") + //$NON-NLS-1$
ReorgMessages.getString("JdtCopyAction.update_classpath"); //$NON-NLS-1$
return new PackageFragmentRootManipulationQuery(shell, ReorgMessages.getString("JdtCopyAction.Copy"), messagePattern); //$NON-NLS-1$
}
}
|
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/JdtMoveAction.java
|
package org.eclipse.jdt.internal.ui.reorg;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.DialogSettings;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.MoveProjectAction;
import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation;
import org.eclipse.jdt.internal.ui.refactoring.QualifiedNameComponent;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringSaveHelper;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardPage;
import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringErrorDialogUtil;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.base.RefactoringStatus;
import org.eclipse.jdt.internal.corext.refactoring.reorg.IPackageFragmentRootManipulationQuery;
import org.eclipse.jdt.internal.corext.refactoring.reorg.MoveRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgUtils;
public class JdtMoveAction extends ReorgDestinationAction {
public static final int PREVIEW_ID= IDialogConstants.CLIENT_ID + 1;
private boolean fShowPreview= false;
public JdtMoveAction(IWorkbenchSite site) {
super(site);
setText(ReorgMessages.getString("moveAction.label"));//$NON-NLS-1$
}
public boolean canOperateOn(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
if (ClipboardActionUtil.hasOnlyProjects(selection))
return selection.size() == 1;
else
return super.canOperateOn(selection);
}
protected void run(IStructuredSelection selection) {
if (ClipboardActionUtil.hasOnlyProjects(selection)){
moveProject(selection);
} else {
if (!needsSaving(selection)) {
super.run(selection);
} else {
RefactoringSaveHelper helper= new RefactoringSaveHelper();
try {
if (helper.saveEditors()) {
super.run(selection);
}
} finally {
helper.triggerBuild();
}
}
}
}
private boolean needsSaving(IStructuredSelection selection) {
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= (Object) iter.next();
if (element instanceof ICompilationUnit || element instanceof IType)
return true;
}
return false;
}
public static ElementTreeSelectionDialog makeDialog(Shell parent, MoveRefactoring refactoring) {
StandardJavaElementContentProvider cp= new StandardJavaElementContentProvider() {
public boolean hasChildren(Object element) {
// prevent the + from being shown in front of packages
return !(element instanceof IPackageFragment) && super.hasChildren(element);
}
};
MoveDestinationDialog dialog= new MoveDestinationDialog(
parent, new DestinationRenderer(JavaElementLabelProvider.SHOW_SMALL_ICONS),
cp, refactoring);
return dialog;
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
String getActionName() {
return ReorgMessages.getString("moveAction.name"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#getDestinationDialogMessage
*/
String getDestinationDialogMessage() {
return ReorgMessages.getString("moveAction.destination.label"); //$NON-NLS-1$
}
/* non java-doc
* see @ReorgDestinationAction#createRefactoring
*/
ReorgRefactoring createRefactoring(List elements){
IPackageFragmentRootManipulationQuery query= createUpdateClasspathQuery(getShell());
return new MoveRefactoring(elements, JavaPreferencesSettings.getCodeGenerationSettings(), query);
}
ElementTreeSelectionDialog createDestinationSelectionDialog(Shell parent, ILabelProvider labelProvider, StandardJavaElementContentProvider cp, ReorgRefactoring refactoring){
return new MoveDestinationDialog(parent, labelProvider, cp, (MoveRefactoring)refactoring);
}
/* non java-doc
* see @ReorgDestinationAction#isOkToProceed
*/
protected boolean isOkToProceed(ReorgRefactoring refactoring) throws JavaModelException{
return isOkToMoveReadOnly(refactoring);
}
protected void setShowPreview(boolean showPreview) {
fShowPreview = showPreview;
}
private static boolean isOkToMoveReadOnly(ReorgRefactoring refactoring){
if (! hasReadOnlyElements(refactoring))
return true;
return MessageDialog.openQuestion(
JavaPlugin.getActiveWorkbenchShell(),
ReorgMessages.getString("moveAction.checkMove"), //$NON-NLS-1$
ReorgMessages.getString("moveAction.error.readOnly")); //$NON-NLS-1$
}
private static boolean hasReadOnlyElements(ReorgRefactoring refactoring){
for (Iterator iter= refactoring.getElementsToReorg().iterator(); iter.hasNext(); ){
if (ReorgUtils.shouldConfirmReadOnly(iter.next()))
return true;
}
return false;
}
protected Object openDialog(ElementTreeSelectionDialog dialog) {
Object result= super.openDialog(dialog);
if (dialog instanceof MoveDestinationDialog) {
fShowPreview= dialog.getReturnCode() == PREVIEW_ID;
} else {
fShowPreview= false;
}
return result;
}
/* non java-doc
* @see ReorgDestinationAction#doReorg(ReorgRefactoring)
*/
void doReorg(ReorgRefactoring refactoring) throws JavaModelException{
if (fShowPreview){
openWizard(getShell(), refactoring);
return;
}
CheckConditionsOperation runnable= new CheckConditionsOperation(refactoring, CheckConditionsOperation.PRECONDITIONS);
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(false, false, runnable);
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
return;
} catch (InterruptedException e) {
Assert.isTrue(false); //cannot happen - not cancelable
}
RefactoringStatus status= runnable.getStatus();
if (status == null)
return;
if (status.hasFatalError())
RefactoringErrorDialogUtil.open(ReorgMessages.getString("JdtMoveAction.move"), status);//$NON-NLS-1$
else
super.doReorg(refactoring);
}
public static void openWizard(Shell parent, ReorgRefactoring refactoring) {
//XX incorrect help
RefactoringWizard wizard= new RefactoringWizard(refactoring, ReorgMessages.getString("JdtMoveAction.move"), IJavaHelpContextIds.MOVE_CU_ERROR_WIZARD_PAGE); //$NON-NLS-1$
wizard.setChangeCreationCancelable(false);
new RefactoringWizardDialog(parent, wizard).open();
return;
}
private void moveProject(IStructuredSelection selection){
MoveProjectAction action= new MoveProjectAction(JavaPlugin.getActiveWorkbenchShell());
action.selectionChanged(selection);
action.run();
}
//--- static inner classes
private static class MoveDestinationDialog extends ElementTreeSelectionDialog {
private MoveRefactoring fRefactoring;
private Button fReferenceCheckbox;
private Button fQualifiedNameCheckbox;
private QualifiedNameComponent fQualifiedNameComponent;
private Button fPreview;
MoveDestinationDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, MoveRefactoring refactoring) {
super(parent, labelProvider, contentProvider);
fRefactoring= refactoring;
setDoubleClickSelects(false);
}
protected void updateOKStatus() {
super.updateOKStatus();
try{
Button okButton= getOkButton();
boolean okEnabled= okButton.getEnabled();
fRefactoring.setDestination(getFirstResult());
fReferenceCheckbox.setEnabled(okEnabled && canUpdateReferences());
fRefactoring.setUpdateReferences(fReferenceCheckbox.getEnabled() && fReferenceCheckbox.getSelection());
if (fQualifiedNameCheckbox != null) {
boolean enabled= okEnabled && fRefactoring.canEnableQualifiedNameUpdating();
fQualifiedNameCheckbox.setEnabled(enabled);
if (enabled) {
fQualifiedNameComponent.setEnabled(fRefactoring.getUpdateQualifiedNames());
if (fRefactoring.getUpdateQualifiedNames())
okButton.setEnabled(false);
} else {
fQualifiedNameComponent.setEnabled(false);
}
fRefactoring.setUpdateQualifiedNames(fQualifiedNameCheckbox.getEnabled() && fQualifiedNameCheckbox.getSelection());
}
boolean preview= okEnabled;
if (preview)
preview=
fRefactoring.getUpdateQualifiedNames() && fRefactoring.canEnableQualifiedNameUpdating() ||
fReferenceCheckbox.getSelection() && fRefactoring.canUpdateReferences();
fPreview.setEnabled(preview);
} catch (JavaModelException e){
ExceptionHandler.handle(e, ReorgMessages.getString("JdtMoveAction.move"), ReorgMessages.getString("JdtMoveAction.exception")); //$NON-NLS-1$ //$NON-NLS-2$
}
}
protected void buttonPressed(int buttonId) {
super.buttonPressed(buttonId);
if (buttonId == PREVIEW_ID) {
setReturnCode(PREVIEW_ID);
close();
}
}
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.MOVE_DESTINATION_DIALOG);
}
protected void createButtonsForButtonBar(Composite parent) {
fPreview= createButton(parent, PREVIEW_ID, ReorgMessages.getString("JdtMoveAction.preview"), false); //$NON-NLS-1$
super.createButtonsForButtonBar(parent);
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
addUpdateReferenceComponent(result);
addUpdateQualifiedNameComponent(result, ((GridLayout)result.getLayout()).marginWidth);
return result;
}
private void addUpdateReferenceComponent(Composite result) {
fReferenceCheckbox= new Button(result, SWT.CHECK);
fReferenceCheckbox.setText(ReorgMessages.getString("JdtMoveAction.update_references")); //$NON-NLS-1$
fReferenceCheckbox.setSelection(fRefactoring.getUpdateReferences());
fReferenceCheckbox.setEnabled(canUpdateReferences());
fReferenceCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
fRefactoring.setUpdateReferences(((Button)e.widget).getSelection());
updateOKStatus();
}
});
}
private boolean canUpdateReferences() {
try{
return fRefactoring.canUpdateReferences();
} catch (JavaModelException e){
return false;
}
}
private void addUpdateQualifiedNameComponent(Composite parent, int marginWidth) {
if (!fRefactoring.canUpdateQualifiedNames())
return;
fQualifiedNameCheckbox= new Button(parent, SWT.CHECK);
int indent= marginWidth + fQualifiedNameCheckbox.computeSize(SWT.DEFAULT, SWT.DEFAULT).x;
fQualifiedNameCheckbox.setText(RefactoringMessages.getString("RenameInputWizardPage.update_qualified_names")); //$NON-NLS-1$
fQualifiedNameCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
fQualifiedNameCheckbox.setSelection(fRefactoring.getUpdateQualifiedNames());
fQualifiedNameComponent= new QualifiedNameComponent(parent, SWT.NONE, fRefactoring, getRefactoringSettings());
fQualifiedNameComponent.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridData gd= (GridData)fQualifiedNameComponent.getLayoutData();
gd.horizontalAlignment= GridData.FILL;
gd.horizontalIndent= indent;
fQualifiedNameComponent.setEnabled(false);
fQualifiedNameCheckbox.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
boolean enabled= ((Button)e.widget).getSelection();
fQualifiedNameComponent.setEnabled(enabled);
fRefactoring.setUpdateQualifiedNames(enabled);
updateOKStatus();
}
});
}
protected IDialogSettings getRefactoringSettings() {
IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings();
if (settings == null)
return null;
IDialogSettings result= settings.getSection(RefactoringWizardPage.REFACTORING_SETTINGS);
if (result == null) {
result= new DialogSettings(RefactoringWizardPage.REFACTORING_SETTINGS);
settings.addSection(result);
}
return result;
}
}
public static IPackageFragmentRootManipulationQuery createUpdateClasspathQuery(Shell shell){
String messagePattern= ReorgMessages.getString("JdtMoveAction.referenced") + //$NON-NLS-1$
ReorgMessages.getString("JdtMoveAction.update_classpath"); //$NON-NLS-1$
return new PackageFragmentRootManipulationQuery(shell, ReorgMessages.getString("JdtMoveAction.Move"), messagePattern); //$NON-NLS-1$
}
}
|
31,298 |
Bug 31298 move of read-only java file gives error dialog after confirmation
|
- 'move' read-only java file - uncheck all options - choose dest package - press ok - confirm the movement of a read-only file -> error dialog
|
resolved fixed
|
12cd63f
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T16:50:12Z | 2003-02-07T15:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/reorg/ReorgDestinationAction.java
| |
31,254 |
Bug 31254 Change Method signature refactoring: Table leaves cursor edit mode
|
20030206 Change Method signature refactoring: Doubleclick should open edit window
|
resolved fixed
|
a377259
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T17:07:42Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/ui
| |
31,254 |
Bug 31254 Change Method signature refactoring: Table leaves cursor edit mode
|
20030206 Change Method signature refactoring: Doubleclick should open edit window
|
resolved fixed
|
a377259
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T17:07:42Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeParametersControl.java
| |
31,170 |
Bug 31170 Errors in outline view
|
build i0206, win2k, j9 I noticed that my outline view wasn't updating...it only displayed "a top level type not defined". I clicked on the "go into top level type" button a couple of times and got the following in my log. !ENTRY org.eclipse.jdt.ui 4 10001 Feb 06, 2003 16:50:27.383 !MESSAGE Template newtype not added: Variable 'package_statement' is unknown. !ENTRY org.eclipse.jdt.ui 4 10001 Feb 06, 2003 16:50:51.137 !MESSAGE Internal Error !STACK 1 Java Model Exception: Java Model Status [[Working copy] ResourcesPlugin.java [in org.eclipse.core.resources [in src [in org.eclipse.core.resources]]] 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/WorkingCopy.openBuffer (Lorg/eclipse/core/runtime/IProgressMonitor;)Lorg/eclipse/jdt/core/IBuffer; org/eclipse/jdt/internal/core/Openable.openWhenClosed (Lorg/eclipse/core/runtime/IProgressMonitor;)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/JavaElement.getChildren() [Lorg/eclipse/jdt/core/IJavaElement; org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage$ChildrenProvider.getChild ren(Ljava/lang/Object;)[Ljava/lang/Object; org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage$ChildrenProvider.getEleme nts(Ljava/lang/Object;)[Ljava/lang/Object; org/eclipse/jface/viewers/StructuredViewer.getRawChildren(Ljava/lang/Object;) [Ljava/lang/Object; org/eclipse/jface/viewers/AbstractTreeViewer.getRawChildren (Ljava/lang/Object;)[Ljava/lang/Object; org/eclipse/jface/viewers/StructuredViewer.getFilteredChildren (Ljava/lang/Object;)[Ljava/lang/Object; org/eclipse/jface/viewers/StructuredViewer.getSortedChildren (Ljava/lang/Object;)[Ljava/lang/Object; org/eclipse/jface/viewers/AbstractTreeViewer.updateChildren (Lorg/eclipse/swt/widgets/Widget;Ljava/lang/Object;[Ljava/lang/Object;)V org/eclipse/jface/viewers/AbstractTreeViewer.internalRefresh (Lorg/eclipse/swt/widgets/Widget;Ljava/lang/Object;Z)V org/eclipse/jface/viewers/AbstractTreeViewer.internalRefresh (Ljava/lang/Object;)V org/eclipse/jface/viewers/StructuredViewer$7.run()V org/eclipse/jface/viewers/StructuredViewer.preservingSelection (Ljava/lang/Runnable;)V org/eclipse/jface/viewers/StructuredViewer.refresh(Ljava/lang/Object;)V org/eclipse/jface/viewers/StructuredViewer.refresh()V org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage$ClassOnlyAction.setTopLev elTypeOnly(Z)V org/eclipse/jdt/internal/ui/javaeditor/JavaOutlinePage$ClassOnlyAction.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.sendEvent(Lorg/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 (Lorg/eclipse/jface/window/Window$IExceptionHandler;)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/Runnable;)Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String; [Ljava/lang/String;Ljava/lang/Runnable;)Ljava/lang/Object; java/lang/reflect/AccessibleObject.invokeL(Ljava/lang/Object; [Ljava/lang/Object;)Ljava/lang/Object; java/lang/reflect/Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;) Ljava/lang/Object; org/eclipse/core/launcher/Main.basicRun([Ljava/lang/String;) Ljava/lang/Object; org/eclipse/core/launcher/Main.run([Ljava/lang/String;)Ljava/lang/Object; org/eclipse/core/launcher/Main.main([Ljava/lang/String;)V !ENTRY org.eclipse.jdt.core 4 969 Feb 06, 2003 16:50:51.137 !MESSAGE [Working copy] ResourcesPlugin.java [in org.eclipse.core.resources [in src [in org.eclipse.core.resources]]] does not exist. !ENTRY org.eclipse.jface 4 2 Feb 06, 2003 16:50:57.376 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 java.lang.NullPointerException Stack trace: java/lang/Throwable.<init>()V java/lang/Throwable.<init>(Ljava/lang/String;)V java/lang/NullPointerException.<init>(Ljava/lang/String;)V org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.setSelection (Lorg/eclipse/jdt/core/ISourceReference;Z)V org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.doSelectionChanged (Lorg/eclipse/jface/viewers/SelectionChangedEvent;)V org/eclipse/jdt/internal/ui/javaeditor/JavaEditor$SelectionChangedListener.selec tionChanged(Lorg/eclipse/jface/viewers/SelectionChangedEvent;)V org/eclipse/jface/viewers/StructuredViewer$3.run()V org/eclipse/core/internal/runtime/InternalPlatform.run (Lorg/eclipse/core/runtime/ISafeRunnable;)V org/eclipse/core/runtime/Platform.run (Lorg/eclipse/core/runtime/ISafeRunnable;)V org/eclipse/jface/viewers/StructuredViewer.firePostSelectionChanged (Lorg/eclipse/jface/viewers/SelectionChangedEvent;)V org/eclipse/jface/viewers/StructuredViewer.handlePostSelect (Lorg/eclipse/swt/events/SelectionEvent;)V org/eclipse/jface/viewers/StructuredViewer$5.widgetSelected (Lorg/eclipse/swt/events/SelectionEvent;)V org/eclipse/jface/util/OpenStrategy.firePostSelectionEvent (Lorg/eclipse/swt/events/SelectionEvent;)V org/eclipse/jface/util/OpenStrategy.access$4 (Lorg/eclipse/jface/util/OpenStrategy;Lorg/eclipse/swt/events/SelectionEvent;)V org/eclipse/jface/util/OpenStrategy$3.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 (Lorg/eclipse/jface/window/Window$IExceptionHandler;)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/Runnable;)Ljava/lang/Object; org/eclipse/core/boot/BootLoader.run (Ljava/lang/String;Ljava/net/URL;Ljava/lang/String; [Ljava/lang/String;Ljava/lang/Runnable;)Ljava/lang/Object; java/lang/reflect/AccessibleObject.invokeL(Ljava/lang/Object; [Ljava/lang/Object;)Ljava/lang/Object; java/lang/reflect/Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;) Ljava/lang/Object; org/eclipse/core/launcher/Main.basicRun([Ljava/lang/String;) Ljava/lang/Object; org/eclipse/core/launcher/Main.run([Ljava/lang/String;)Ljava/lang/Object; org/eclipse/core/launcher/Main.main([Ljava/lang/String;)V
|
resolved fixed
|
8ae5f04
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:18:20Z | 2003-02-06T22:20:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/JavaEditor.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;
import java.util.StringTokenizer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BidiSegmentEvent;
import org.eclipse.swt.custom.BidiSegmentListener;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DefaultInformationControl;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IInformationControl;
import org.eclipse.jface.text.IInformationControlCreator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextInputListener;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.ITextViewerExtension2;
import org.eclipse.jface.text.ITextViewerExtension3;
import org.eclipse.jface.text.ITypedRegion;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.text.information.IInformationProvider;
import org.eclipse.jface.text.information.InformationPresenter;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.AnnotationRulerColumn;
import org.eclipse.jface.text.source.CompositeRuler;
import org.eclipse.jface.text.source.IAnnotationAccess;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.IOverviewRuler;
import org.eclipse.jface.text.source.ISharedTextColors;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.text.source.IVerticalRulerColumn;
import org.eclipse.jface.text.source.LineNumberRulerColumn;
import org.eclipse.jface.text.source.OverviewRuler;
import org.eclipse.jface.text.source.SourceViewerConfiguration;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.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.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.core.resources.IMarker;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPartService;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.editors.text.DefaultEncodingSupport;
import org.eclipse.ui.editors.text.IEncodingSupport;
import org.eclipse.ui.part.EditorActionBarContributor;
import org.eclipse.ui.texteditor.AddTaskAction;
import org.eclipse.ui.texteditor.DefaultRangeIndicator;
import org.eclipse.ui.texteditor.IAbstractTextEditorHelpContextIds;
import org.eclipse.ui.texteditor.IDocumentProvider;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.ui.texteditor.ITextEditorActionDefinitionIds;
import org.eclipse.ui.texteditor.MarkerAnnotation;
import org.eclipse.ui.texteditor.ResourceAction;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.ui.texteditor.StatusTextEditor;
import org.eclipse.ui.texteditor.TextEditorAction;
import org.eclipse.ui.texteditor.TextOperationAction;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
import org.eclipse.ui.views.tasklist.TaskList;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICodeAssist;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IPackageDeclaration;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.ISourceReference;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectEnclosingAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectHistoryAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectNextAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectPreviousAction;
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction;
import org.eclipse.jdt.internal.ui.text.HTMLTextPresenter;
import org.eclipse.jdt.internal.ui.text.JavaPairMatcher;
import org.eclipse.jdt.internal.ui.text.JavaPartitionScanner;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jdt.ui.text.JavaSourceViewerConfiguration;
import org.eclipse.jdt.ui.text.JavaTextTools;
/**
* Java specific text editor.
*/
public abstract class JavaEditor extends StatusTextEditor implements IViewPartInputProvider {
/**
* "Smart" runnable for updating the outline page's selection.
*/
class OutlinePageSelectionUpdater implements Runnable {
/** Has the runnable already been posted? */
private boolean fPosted= false;
public OutlinePageSelectionUpdater() {
}
/*
* @see Runnable#run()
*/
public void run() {
synchronizeOutlinePageSelection();
fPosted= false;
}
/**
* Posts this runnable into the event queue.
*/
public void post() {
if (fPosted)
return;
Shell shell= getSite().getShell();
if (shell != null & !shell.isDisposed()) {
fPosted= true;
shell.getDisplay().asyncExec(this);
}
}
};
class SelectionChangedListener implements ISelectionChangedListener {
public void selectionChanged(SelectionChangedEvent event) {
doSelectionChanged(event);
}
};
/*
* Link mode.
*/
class MouseClickListener implements KeyListener, MouseListener, MouseMoveListener,
FocusListener, PaintListener, IPropertyChangeListener, IDocumentListener, ITextInputListener {
/** The session is active. */
private boolean fActive;
/** The currently active style range. */
private IRegion fActiveRegion;
/** The currently active style range as position. */
private Position fRememberedPosition;
/** The hand cursor. */
private Cursor fCursor;
/** The link color. */
private Color fColor;
/** The key modifier mask. */
private int fKeyModifierMask;
public void deactivate() {
deactivate(false);
}
public void deactivate(boolean redrawAll) {
if (!fActive)
return;
repairRepresentation(redrawAll);
fActive= false;
}
public void install() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
updateColor(sourceViewer);
sourceViewer.addTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.addDocumentListener(this);
text.addKeyListener(this);
text.addMouseListener(this);
text.addMouseMoveListener(this);
text.addFocusListener(this);
text.addPaintListener(this);
updateKeyModifierMask();
IPreferenceStore preferenceStore= getPreferenceStore();
preferenceStore.addPropertyChangeListener(this);
}
private void updateKeyModifierMask() {
String modifiers= getPreferenceStore().getString(BROWSER_LIKE_LINKS_KEY_MODIFIER);
fKeyModifierMask= computeStateMask(modifiers);
}
private int computeStateMask(String modifiers) {
if (modifiers == null)
return -1;
if (modifiers.length() == 0)
return SWT.NONE;
int stateMask= 0;
StringTokenizer modifierTokenizer= new StringTokenizer(modifiers, ",;.:+-* "); //$NON-NLS-1$
while (modifierTokenizer.hasMoreTokens()) {
int modifier= Action.findModifier(modifierTokenizer.nextToken());
if (modifier == 0 || (stateMask & modifier) == modifier)
return -1;
stateMask= stateMask | modifier;
}
return stateMask;
}
public void uninstall() {
if (fColor != null) {
fColor.dispose();
fColor= null;
}
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
sourceViewer.removeTextInputListener(this);
IDocument document= sourceViewer.getDocument();
if (document != null)
document.removeDocumentListener(this);
IPreferenceStore preferenceStore= getPreferenceStore();
if (preferenceStore != null)
preferenceStore.removePropertyChangeListener(this);
StyledText text= sourceViewer.getTextWidget();
if (text == null || text.isDisposed())
return;
text.removeKeyListener(this);
text.removeMouseListener(this);
text.removeMouseMoveListener(this);
text.removeFocusListener(this);
text.removePaintListener(this);
}
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(JavaEditor.LINK_COLOR)) {
ISourceViewer viewer= getSourceViewer();
if (viewer != null)
updateColor(viewer);
} else if (event.getProperty().equals(BROWSER_LIKE_LINKS_KEY_MODIFIER)) {
updateKeyModifierMask();
}
}
private void updateColor(ISourceViewer viewer) {
if (fColor != null)
fColor.dispose();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
fColor= createColor(getPreferenceStore(), JavaEditor.LINK_COLOR, display);
}
/**
* Creates a color from the information stored in the given preference store.
* Returns <code>null</code> if there is no such information available.
*/
private Color createColor(IPreferenceStore store, String key, Display display) {
RGB rgb= null;
if (store.contains(key)) {
if (store.isDefault(key))
rgb= PreferenceConverter.getDefaultColor(store, key);
else
rgb= PreferenceConverter.getColor(store, key);
if (rgb != null)
return new Color(display, rgb);
}
return null;
}
private void repairRepresentation() {
repairRepresentation(false);
}
private void repairRepresentation(boolean redrawAll) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
resetCursor(viewer);
int offset= fActiveRegion.getOffset();
int length= fActiveRegion.getLength();
// remove style
if (!redrawAll && viewer instanceof ITextViewerExtension2)
((ITextViewerExtension2) viewer).invalidateTextPresentation(offset, length);
else
viewer.invalidateTextPresentation();
// remove underline
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
offset= extension.modelOffset2WidgetOffset(offset);
} else {
offset -= viewer.getVisibleRegion().getOffset();
}
StyledText text= viewer.getTextWidget();
try {
text.redrawRange(offset, length, true);
} catch (IllegalArgumentException x) {
JavaPlugin.log(x);
}
}
fActiveRegion= null;
}
// will eventually be replaced by a method provided by jdt.core
private IRegion selectWord(IDocument document, int anchor) {
try {
int offset= anchor;
char c;
while (offset >= 0) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
--offset;
}
int start= offset;
offset= anchor;
int length= document.getLength();
while (offset < length) {
c= document.getChar(offset);
if (!Character.isJavaIdentifierPart(c))
break;
++offset;
}
int end= offset;
if (start == end)
return new Region(start, 0);
else
return new Region(start + 1, end - start - 1);
} catch (BadLocationException x) {
return null;
}
}
IRegion getCurrentTextRegion(ISourceViewer viewer) {
int offset= getCurrentTextOffset(viewer);
if (offset == -1)
return null;
IJavaElement input= SelectionConverter.getInput(JavaEditor.this);
if (input == null)
return null;
try {
IJavaElement[] elements= null;
synchronized (input) {
elements= ((ICodeAssist) input).codeSelect(offset, 0);
}
if (elements == null || elements.length == 0)
return null;
return selectWord(viewer.getDocument(), offset);
} catch (JavaModelException e) {
return null;
}
}
private int getCurrentTextOffset(ISourceViewer viewer) {
try {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return -1;
Display display= text.getDisplay();
Point absolutePosition= display.getCursorLocation();
Point relativePosition= text.toControl(absolutePosition);
int widgetOffset= text.getOffsetAtLocation(relativePosition);
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
return extension.widgetOffset2ModelOffset(widgetOffset);
} else {
return widgetOffset + viewer.getVisibleRegion().getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
private void highlightRegion(ISourceViewer viewer, IRegion region) {
if (region.equals(fActiveRegion))
return;
repairRepresentation();
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
// highlight region
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(region);
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
offset= region.getOffset() - viewer.getVisibleRegion().getOffset();
length= region.getLength();
}
StyleRange oldStyleRange= text.getStyleRangeAtOffset(offset);
Color foregroundColor= fColor;
Color backgroundColor= oldStyleRange == null ? text.getBackground() : oldStyleRange.background;
StyleRange styleRange= new StyleRange(offset, length, foregroundColor, backgroundColor);
text.setStyleRange(styleRange);
// underline
text.redrawRange(offset, length, true);
fActiveRegion= region;
}
private void activateCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
Display display= text.getDisplay();
if (fCursor == null)
fCursor= new Cursor(display, SWT.CURSOR_HAND);
text.setCursor(fCursor);
}
private void resetCursor(ISourceViewer viewer) {
StyledText text= viewer.getTextWidget();
if (text != null && !text.isDisposed())
text.setCursor(null);
if (fCursor != null) {
fCursor.dispose();
fCursor= null;
}
}
/*
* @see org.eclipse.swt.events.KeyListener#keyPressed(org.eclipse.swt.events.KeyEvent)
*/
public void keyPressed(KeyEvent event) {
if (fActive) {
deactivate();
return;
}
if (event.keyCode != fKeyModifierMask) {
deactivate();
return;
}
fActive= true;
// removed for #25871
//
// ISourceViewer viewer= getSourceViewer();
// if (viewer == null)
// return;
//
// IRegion region= getCurrentTextRegion(viewer);
// if (region == null)
// return;
//
// highlightRegion(viewer, region);
// activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.KeyListener#keyReleased(org.eclipse.swt.events.KeyEvent)
*/
public void keyReleased(KeyEvent event) {
if (!fActive)
return;
deactivate();
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDoubleClick(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDoubleClick(MouseEvent e) {}
/*
* @see org.eclipse.swt.events.MouseListener#mouseDown(org.eclipse.swt.events.MouseEvent)
*/
public void mouseDown(MouseEvent event) {
if (!fActive)
return;
if (event.stateMask != fKeyModifierMask) {
deactivate();
return;
}
if (event.button != 1) {
deactivate();
return;
}
}
/*
* @see org.eclipse.swt.events.MouseListener#mouseUp(org.eclipse.swt.events.MouseEvent)
*/
public void mouseUp(MouseEvent e) {
if (!fActive)
return;
if (e.button != 1) {
deactivate();
return;
}
deactivate();
IAction action= getAction("OpenEditor"); //$NON-NLS-1$
if (action == null)
return;
action.run();
}
/*
* @see org.eclipse.swt.events.MouseMoveListener#mouseMove(org.eclipse.swt.events.MouseEvent)
*/
public void mouseMove(MouseEvent event) {
if (event.widget instanceof Control && !((Control) event.widget).isFocusControl()) {
deactivate();
return;
}
if (!fActive) {
if (event.stateMask != fKeyModifierMask)
return;
// modifier was already pressed
fActive= true;
}
ISourceViewer viewer= getSourceViewer();
if (viewer == null) {
deactivate();
return;
}
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed()) {
deactivate();
return;
}
if ((event.stateMask & SWT.BUTTON1) != 0 && text.getSelectionCount() != 0) {
deactivate();
return;
}
IRegion region= getCurrentTextRegion(viewer);
if (region == null || region.getLength() == 0) {
repairRepresentation();
return;
}
highlightRegion(viewer, region);
activateCursor(viewer);
}
/*
* @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent)
*/
public void focusGained(FocusEvent e) {}
/*
* @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent)
*/
public void focusLost(FocusEvent event) {
deactivate();
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentAboutToBeChanged(DocumentEvent event) {
if (fActive && fActiveRegion != null) {
fRememberedPosition= new Position(fActiveRegion.getOffset(), fActiveRegion.getLength());
try {
event.getDocument().addPosition(fRememberedPosition);
} catch (BadLocationException x) {
fRememberedPosition= null;
}
}
}
/*
* @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent)
*/
public void documentChanged(DocumentEvent event) {
if (fRememberedPosition != null && !fRememberedPosition.isDeleted()) {
event.getDocument().removePosition(fRememberedPosition);
fActiveRegion= new Region(fRememberedPosition.getOffset(), fRememberedPosition.getLength());
}
fRememberedPosition= null;
ISourceViewer viewer= getSourceViewer();
if (viewer != null) {
StyledText widget= viewer.getTextWidget();
if (widget != null && !widget.isDisposed()) {
widget.getDisplay().asyncExec(new Runnable() {
public void run() {
deactivate();
}
});
}
}
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentAboutToBeChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentAboutToBeChanged(IDocument oldInput, IDocument newInput) {
if (oldInput == null)
return;
deactivate();
oldInput.removeDocumentListener(this);
}
/*
* @see org.eclipse.jface.text.ITextInputListener#inputDocumentChanged(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocument)
*/
public void inputDocumentChanged(IDocument oldInput, IDocument newInput) {
if (newInput == null)
return;
newInput.addDocumentListener(this);
}
/*
* @see PaintListener#paintControl(PaintEvent)
*/
public void paintControl(PaintEvent event) {
if (fActiveRegion == null)
return;
ISourceViewer viewer= getSourceViewer();
if (viewer == null)
return;
StyledText text= viewer.getTextWidget();
if (text == null || text.isDisposed())
return;
int offset= 0;
int length= 0;
if (viewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) viewer;
IRegion widgetRange= extension.modelRange2WidgetRange(new Region(offset, length));
if (widgetRange == null)
return;
offset= widgetRange.getOffset();
length= widgetRange.getLength();
} else {
IRegion region= viewer.getVisibleRegion();
if (!includes(region, fActiveRegion))
return;
offset= fActiveRegion.getOffset() - region.getOffset();
length= fActiveRegion.getLength();
}
// support for bidi
Point minLocation= getMinimumLocation(text, offset, length);
Point maxLocation= getMaximumLocation(text, offset, length);
int x1= minLocation.x;
int x2= minLocation.x + maxLocation.x - minLocation.x - 1;
int y= minLocation.y + text.getLineHeight() - 1;
GC gc= event.gc;
if (fColor != null && !fColor.isDisposed())
gc.setForeground(fColor);
gc.drawLine(x1, y, x2, y);
}
private boolean includes(IRegion region, IRegion position) {
return
position.getOffset() >= region.getOffset() &&
position.getOffset() + position.getLength() <= region.getOffset() + region.getLength();
}
private Point getMinimumLocation(StyledText text, int offset, int length) {
Point minLocation= new Point(Integer.MAX_VALUE, Integer.MAX_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x < minLocation.x)
minLocation.x= location.x;
if (location.y < minLocation.y)
minLocation.y= location.y;
}
return minLocation;
}
private Point getMaximumLocation(StyledText text, int offset, int length) {
Point maxLocation= new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
for (int i= 0; i <= length; i++) {
Point location= text.getLocationAtOffset(offset + i);
if (location.x > maxLocation.x)
maxLocation.x= location.x;
if (location.y > maxLocation.y)
maxLocation.y= location.y;
}
return maxLocation;
}
};
/**
* This action dispatches into two behaviours: If there is no current text
* hover, the javadoc is displayed using information presenter. If there is
* a current text hover, it is converted into a information presenter in
* order to make it sticky.
*/
class InformationDispatchAction extends TextEditorAction {
/** The wrapped text operation action. */
private final TextOperationAction fTextOperationAction;
/**
* Creates a dispatch action.
*/
public InformationDispatchAction(ResourceBundle resourceBundle, String prefix, final TextOperationAction textOperationAction) {
super(resourceBundle, prefix, JavaEditor.this);
if (textOperationAction == null)
throw new IllegalArgumentException();
fTextOperationAction= textOperationAction;
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null) {
fTextOperationAction.run();
return;
}
if (! (sourceViewer instanceof ITextViewerExtension2)) {
fTextOperationAction.run();
return;
}
ITextViewerExtension2 textViewerExtension2= (ITextViewerExtension2) sourceViewer;
// does a text hover exist?
ITextHover textHover= textViewerExtension2.getCurrentTextHover();
if (textHover == null) {
fTextOperationAction.run();
return;
}
Point hoverEventLocation= textViewerExtension2.getHoverEventLocation();
int offset= computeOffsetAtLocation(sourceViewer, hoverEventLocation.x, hoverEventLocation.y);
if (offset == -1) {
fTextOperationAction.run();
return;
}
try {
// get the text hover content
IDocument document= sourceViewer.getDocument();
String contentType= document.getContentType(offset);
final IRegion hoverRegion= textHover.getHoverRegion(sourceViewer, offset);
if (hoverRegion == null)
return;
final String hoverInfo= textHover.getHoverInfo(sourceViewer, hoverRegion);
// with information provider
IInformationProvider informationProvider= new IInformationProvider() {
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getSubject(org.eclipse.jface.text.ITextViewer, int)
*/
public IRegion getSubject(ITextViewer textViewer, int offset) {
return hoverRegion;
}
/*
* @see org.eclipse.jface.text.information.IInformationProvider#getInformation(org.eclipse.jface.text.ITextViewer, org.eclipse.jface.text.IRegion)
*/
public String getInformation(ITextViewer textViewer, IRegion subject) {
return hoverInfo;
}
};
fInformationPresenter.setOffset(offset);
fInformationPresenter.setInformationProvider(informationProvider, contentType);
fInformationPresenter.showInformation();
} catch (BadLocationException e) {
}
}
// modified version from TextViewer
private int computeOffsetAtLocation(ITextViewer textViewer, int x, int y) {
StyledText styledText= textViewer.getTextWidget();
IDocument document= textViewer.getDocument();
if (document == null)
return -1;
try {
int widgetLocation= styledText.getOffsetAtLocation(new Point(x, y));
if (textViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) textViewer;
return extension.widgetOffset2ModelOffset(widgetLocation);
} else {
IRegion visibleRegion= textViewer.getVisibleRegion();
return widgetLocation + visibleRegion.getOffset();
}
} catch (IllegalArgumentException e) {
return -1;
}
}
};
static protected class AnnotationAccess implements IAnnotationAccess {
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#getType(org.eclipse.jface.text.source.Annotation)
*/
public Object getType(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.getAnnotationType();
}
return null;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isMultiLine(org.eclipse.jface.text.source.Annotation)
*/
public boolean isMultiLine(Annotation annotation) {
return true;
}
/*
* @see org.eclipse.jface.text.source.IAnnotationAccess#isTemporary(org.eclipse.jface.text.source.Annotation)
*/
public boolean isTemporary(Annotation annotation) {
if (annotation instanceof IJavaAnnotation) {
IJavaAnnotation javaAnnotation= (IJavaAnnotation) annotation;
if (javaAnnotation.isRelevant())
return javaAnnotation.isTemporary();
}
return false;
}
};
private class PropertyChangeListener implements org.eclipse.core.runtime.Preferences.IPropertyChangeListener {
/*
* @see IPropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
handlePreferencePropertyChanged(event);
}
};
/** Preference key for showing the line number ruler */
protected final static String LINE_NUMBER_RULER= PreferenceConstants.EDITOR_LINE_NUMBER_RULER;
/** Preference key for the foreground color of the line numbers */
protected final static String LINE_NUMBER_COLOR= PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR;
/** Preference key for the link color */
protected final static String LINK_COLOR= PreferenceConstants.EDITOR_LINK_COLOR;
/** Preference key for matching brackets */
protected final static String MATCHING_BRACKETS= PreferenceConstants.EDITOR_MATCHING_BRACKETS;
/** Preference key for matching brackets color */
protected final static String MATCHING_BRACKETS_COLOR= PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR;
/** Preference key for highlighting current line */
protected final static String CURRENT_LINE= PreferenceConstants.EDITOR_CURRENT_LINE;
/** Preference key for highlight color of current line */
protected final static String CURRENT_LINE_COLOR= PreferenceConstants.EDITOR_CURRENT_LINE_COLOR;
/** Preference key for showing print marging ruler */
protected final static String PRINT_MARGIN= PreferenceConstants.EDITOR_PRINT_MARGIN;
/** Preference key for print margin ruler color */
protected final static String PRINT_MARGIN_COLOR= PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR;
/** Preference key for print margin ruler column */
protected final static String PRINT_MARGIN_COLUMN= PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN;
/** Preference key for error indication */
protected final static String ERROR_INDICATION= PreferenceConstants.EDITOR_PROBLEM_INDICATION;
/** Preference key for error color */
protected final static String ERROR_INDICATION_COLOR= PreferenceConstants.EDITOR_PROBLEM_INDICATION_COLOR;
/** Preference key for warning indication */
protected final static String WARNING_INDICATION= PreferenceConstants.EDITOR_WARNING_INDICATION;
/** Preference key for warning color */
protected final static String WARNING_INDICATION_COLOR= PreferenceConstants.EDITOR_WARNING_INDICATION_COLOR;
/** Preference key for task indication */
protected final static String TASK_INDICATION= PreferenceConstants.EDITOR_TASK_INDICATION;
/** Preference key for task color */
protected final static String TASK_INDICATION_COLOR= PreferenceConstants.EDITOR_TASK_INDICATION_COLOR;
/** Preference key for bookmark indication */
protected final static String BOOKMARK_INDICATION= PreferenceConstants.EDITOR_BOOKMARK_INDICATION;
/** Preference key for bookmark color */
protected final static String BOOKMARK_INDICATION_COLOR= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_COLOR;
/** Preference key for search result indication */
protected final static String SEARCH_RESULT_INDICATION= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION;
/** Preference key for search result color */
protected final static String SEARCH_RESULT_INDICATION_COLOR= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_COLOR;
/** Preference key for unknown annotation indication */
protected final static String UNKNOWN_INDICATION= PreferenceConstants.EDITOR_UNKNOWN_INDICATION;
/** Preference key for unknown annotation color */
protected final static String UNKNOWN_INDICATION_COLOR= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_COLOR;
/** Preference key for shwoing the overview ruler */
protected final static String OVERVIEW_RULER= PreferenceConstants.EDITOR_OVERVIEW_RULER;
/** Preference key for error indication in overview ruler */
protected final static String ERROR_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for warning indication in overview ruler */
protected final static String WARNING_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for task indication in overview ruler */
protected final static String TASK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for bookmark indication in overview ruler */
protected final static String BOOKMARK_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for search result indication in overview ruler */
protected final static String SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for unknown annotation indication in overview ruler */
protected final static String UNKNOWN_INDICATION_IN_OVERVIEW_RULER= PreferenceConstants.EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER;
/** Preference key for compiler task tags */
private final static String COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS;
/** Preference key for browser like links */
private final static String BROWSER_LIKE_LINKS= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS;
/** Preference key for key modifier of browser like links */
private final static String BROWSER_LIKE_LINKS_KEY_MODIFIER= PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER;
protected final static char[] BRACKETS= { '{', '}', '(', ')', '[', ']' };
/** The outline page */
protected JavaOutlinePage fOutlinePage;
/** Outliner context menu Id */
protected String fOutlinerContextMenuId;
/** The selection changed listener */
protected ISelectionChangedListener fSelectionChangedListener= new SelectionChangedListener();
/** The editor's bracket matcher */
protected JavaPairMatcher fBracketMatcher= new JavaPairMatcher(BRACKETS);
/** The outline page selection updater */
private OutlinePageSelectionUpdater fUpdater;
/** Indicates whether this editor should react on outline page selection changes */
private int fIgnoreOutlinePageSelection;
/** The line number ruler column */
private LineNumberRulerColumn fLineNumberRulerColumn;
/** This editor's encoding support */
private DefaultEncodingSupport fEncodingSupport;
/** The mouse listener */
private MouseClickListener fMouseListener;
/** The information presenter. */
private InformationPresenter fInformationPresenter;
/** The annotation access */
protected IAnnotationAccess fAnnotationAccess= new AnnotationAccess();
/** The overview ruler */
protected OverviewRuler isOverviewRulerVisible;
/** The source viewer decoration support */
protected SourceViewerDecorationSupport fSourceViewerDecorationSupport;
/** The overview ruler */
protected OverviewRuler fOverviewRuler;
/** History for structure select action */
private SelectionHistory fSelectionHistory;
/** The preference property change listener for java core. */
private org.eclipse.core.runtime.Preferences.IPropertyChangeListener fPropertyChangeListener= new PropertyChangeListener();
protected CompositeActionGroup fActionGroups;
private CompositeActionGroup fContextMenuGroup;
/**
* Returns the most narrow java element including the given offset
*
* @param offset the offset inside of the requested element
*/
abstract protected IJavaElement getElementAt(int offset);
/**
* Returns the java element of this editor's input corresponding to the given IJavaElement
*/
abstract protected IJavaElement getCorrespondingElement(IJavaElement element);
/**
* Sets the input of the editor's outline page.
*/
abstract protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input);
/**
* Default constructor.
*/
public JavaEditor() {
super();
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
setSourceViewerConfiguration(new JavaSourceViewerConfiguration(textTools, this));
setRangeIndicator(new DefaultRangeIndicator());
setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore());
if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE))
fUpdater= new OutlinePageSelectionUpdater();
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected final ISourceViewer createSourceViewer(Composite parent, IVerticalRuler verticalRuler, int styles) {
ISharedTextColors sharedColors= JavaPlugin.getDefault().getJavaTextTools().getColorManager();
fOverviewRuler= new OverviewRuler(fAnnotationAccess, VERTICAL_RULER_WIDTH, sharedColors);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.WARNING);
fOverviewRuler.addHeaderAnnotationType(AnnotationType.ERROR);
ISourceViewer viewer= createJavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
StyledText text= viewer.getTextWidget();
text.addBidiSegmentListener(new BidiSegmentListener() {
public void lineGetSegments(BidiSegmentEvent event) {
event.segments= getBidiLineSegments(event.lineOffset, event.lineText);
}
});
JavaUIHelp.setHelp(this, text, IJavaHelpContextIds.JAVA_EDITOR);
fSourceViewerDecorationSupport= new SourceViewerDecorationSupport(viewer, fOverviewRuler, fAnnotationAccess, sharedColors);
configureSourceViewerDecorationSupport();
return viewer;
}
/*
* @see AbstractTextEditor#createSourceViewer(Composite, IVerticalRuler, int)
*/
protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) {
return new JavaSourceViewer(parent, verticalRuler, fOverviewRuler, isOverviewRulerVisible(), styles);
}
/*
* @see AbstractTextEditor#affectsTextPresentation(PropertyChangeEvent)
*/
protected boolean affectsTextPresentation(PropertyChangeEvent event) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
return textTools.affectsBehavior(event);
}
/**
* Sets the outliner's context menu ID.
*/
protected void setOutlinerContextMenuId(String menuId) {
fOutlinerContextMenuId= menuId;
}
/**
* Returns the standard action group of this editor.
*/
protected ActionGroup getActionGroup() {
return fActionGroups;
}
/*
* @see AbstractTextEditor#editorContextMenuAboutToShow
*/
public void editorContextMenuAboutToShow(IMenuManager menu) {
super.editorContextMenuAboutToShow(menu);
menu.appendToGroup(ITextEditorActionConstants.GROUP_UNDO, new Separator(IContextMenuConstants.GROUP_OPEN));
menu.insertAfter(IContextMenuConstants.GROUP_OPEN, new GroupMarker(IContextMenuConstants.GROUP_SHOW));
ActionContext context= new ActionContext(getSelectionProvider().getSelection());
fContextMenuGroup.setContext(context);
fContextMenuGroup.fillContextMenu(menu);
fContextMenuGroup.setContext(null);
}
/**
* Creates the outline page used with this editor.
*/
protected JavaOutlinePage createOutlinePage() {
JavaOutlinePage page= new JavaOutlinePage(fOutlinerContextMenuId, this);
page.addSelectionChangedListener(fSelectionChangedListener);
setOutlinePageInput(page, getEditorInput());
return page;
}
/**
* Informs the editor that its outliner has been closed.
*/
public void outlinePageClosed() {
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage= null;
resetHighlightRange();
}
}
/**
* Synchronizes the outliner selection with the actual cursor
* position in the editor.
*/
public void synchronizeOutlinePageSelection() {
if (isEditingScriptRunning())
return;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null || fOutlinePage == null)
return;
StyledText styledText= sourceViewer.getTextWidget();
if (styledText == null)
return;
int caret= 0;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
caret= extension.widgetOffset2ModelOffset(styledText.getCaretOffset());
} else {
int offset= sourceViewer.getVisibleRegion().getOffset();
caret= offset + styledText.getCaretOffset();
}
IJavaElement element= getElementAt(caret);
if (element instanceof ISourceReference) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
/*
* Get the desktop's StatusLineManager
*/
protected IStatusLineManager getStatusLineManager() {
IEditorActionBarContributor contributor= getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
return ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
}
return null;
}
/*
* @see AbstractTextEditor#getAdapter(Class)
*/
public Object getAdapter(Class required) {
if (IContentOutlinePage.class.equals(required)) {
if (fOutlinePage == null)
fOutlinePage= createOutlinePage();
return fOutlinePage;
}
if (IEncodingSupport.class.equals(required))
return fEncodingSupport;
return super.getAdapter(required);
}
protected void setSelection(ISourceReference reference, boolean moveCursor) {
ISelection selection= getSelectionProvider().getSelection();
if (selection instanceof TextSelection) {
TextSelection textSelection= (TextSelection) selection;
if (textSelection.getOffset() != 0 || textSelection.getLength() != 0)
markInNavigationHistory();
}
if (reference != null) {
StyledText textWidget= null;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null)
textWidget= sourceViewer.getTextWidget();
if (textWidget == null)
return;
try {
ISourceRange range= reference.getSourceRange();
if (range == null)
return;
int offset= range.getOffset();
int length= range.getLength();
if (offset < 0 || length < 0)
return;
textWidget.setRedraw(false);
setHighlightRange(offset, length, moveCursor);
if (!moveCursor)
return;
offset= -1;
length= -1;
if (reference instanceof IMember) {
range= ((IMember) reference).getNameRange();
if (range != null) {
offset= range.getOffset();
length= range.getLength();
}
} else if (reference instanceof IImportDeclaration) {
String name= ((IImportDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
} else if (reference instanceof IPackageDeclaration) {
String name= ((IPackageDeclaration) reference).getElementName();
if (name != null && name.length() > 0) {
String content= reference.getSource();
offset= range.getOffset() + content.indexOf(name);
length= name.length();
}
}
if (offset > -1 && length > 0) {
sourceViewer.revealRange(offset, length);
sourceViewer.setSelectedRange(offset, length);
}
} catch (JavaModelException x) {
} catch (IllegalArgumentException x) {
} finally {
if (textWidget != null)
textWidget.setRedraw(true);
}
} else if (moveCursor) {
resetHighlightRange();
}
markInNavigationHistory();
}
public void setSelection(IJavaElement element) {
if (element == null || element instanceof ICompilationUnit || element instanceof IClassFile) {
/*
* If the element is an ICompilationUnit this unit is either the input
* of this editor or not being displayed. In both cases, nothing should
* happened. (http://dev.eclipse.org/bugs/show_bug.cgi?id=5128)
*/
return;
}
IJavaElement corresponding= getCorrespondingElement(element);
if (corresponding instanceof ISourceReference) {
ISourceReference reference= (ISourceReference) corresponding;
// set hightlight range
setSelection(reference, true);
// set outliner selection
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select(reference);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
}
}
public synchronized void editingScriptStarted() {
++ fIgnoreOutlinePageSelection;
}
public synchronized void editingScriptEnded() {
-- fIgnoreOutlinePageSelection;
}
public synchronized boolean isEditingScriptRunning() {
return (fIgnoreOutlinePageSelection > 0);
}
protected void doSelectionChanged(SelectionChangedEvent event) {
ISourceReference reference= null;
ISelection selection= event.getSelection();
Iterator iter= ((IStructuredSelection) selection).iterator();
while (iter.hasNext()) {
Object o= iter.next();
if (o instanceof ISourceReference) {
reference= (ISourceReference) o;
break;
}
}
if (!isActivePart() && JavaPlugin.getActivePage() != null)
JavaPlugin.getActivePage().bringToTop(this);
try {
editingScriptStarted();
setSelection(reference, !isActivePart());
} finally {
editingScriptEnded();
}
}
/*
* @see AbstractTextEditor#adjustHighlightRange(int, int)
*/
protected void adjustHighlightRange(int offset, int length) {
try {
IJavaElement element= getElementAt(offset);
while (element instanceof ISourceReference) {
ISourceRange range= ((ISourceReference) element).getSourceRange();
if (offset < range.getOffset() + range.getLength() && range.getOffset() < offset + length) {
setHighlightRange(range.getOffset(), range.getLength(), true);
if (fOutlinePage != null) {
fOutlinePage.removeSelectionChangedListener(fSelectionChangedListener);
fOutlinePage.select((ISourceReference) element);
fOutlinePage.addSelectionChangedListener(fSelectionChangedListener);
}
return;
}
element= element.getParent();
}
} catch (JavaModelException x) {
JavaPlugin.log(x.getStatus());
}
resetHighlightRange();
}
protected boolean isActivePart() {
IWorkbenchWindow window= getSite().getWorkbenchWindow();
IPartService service= window.getPartService();
IWorkbenchPart part= service.getActivePart();
return part != null && part.equals(this);
}
/*
* @see StatusTextEditor#getStatusHeader(IStatus)
*/
protected String getStatusHeader(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusHeader(status);
if (message != null)
return message;
}
return super.getStatusHeader(status);
}
/*
* @see StatusTextEditor#getStatusBanner(IStatus)
*/
protected String getStatusBanner(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusBanner(status);
if (message != null)
return message;
}
return super.getStatusBanner(status);
}
/*
* @see StatusTextEditor#getStatusMessage(IStatus)
*/
protected String getStatusMessage(IStatus status) {
if (fEncodingSupport != null) {
String message= fEncodingSupport.getStatusMessage(status);
if (message != null)
return message;
}
return super.getStatusMessage(status);
}
/*
* @see AbstractTextEditor#doSetInput
*/
protected void doSetInput(IEditorInput input) throws CoreException {
super.doSetInput(input);
if (fEncodingSupport != null)
fEncodingSupport.reset();
setOutlinePageInput(fOutlinePage, input);
}
/*
* @see IWorkbenchPart#dispose()
*/
public void dispose() {
if (isBrowserLikeLinks())
disableBrowserLikeLinks();
if (fEncodingSupport != null) {
fEncodingSupport.dispose();
fEncodingSupport= null;
}
if (fPropertyChangeListener != null) {
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.removePropertyChangeListener(fPropertyChangeListener);
fPropertyChangeListener= null;
}
if (fSourceViewerDecorationSupport != null) {
fSourceViewerDecorationSupport.dispose();
fSourceViewerDecorationSupport= null;
}
if (fBracketMatcher != null) {
fBracketMatcher.dispose();
fBracketMatcher= null;
}
if (fSelectionHistory != null) {
fSelectionHistory.dispose();
fSelectionHistory= null;
}
super.dispose();
}
protected void createActions() {
super.createActions();
ResourceAction resAction= new AddTaskAction(JavaEditorMessages.getResourceBundle(), "AddTask.", this); //$NON-NLS-1$
resAction.setHelpContextId(IAbstractTextEditorHelpContextIds.ADD_TASK_ACTION);
resAction.setActionDefinitionId(ITextEditorActionDefinitionIds.ADD_TASK);
setAction(ITextEditorActionConstants.ADD_TASK, resAction);
ActionGroup oeg, ovg, jsg;
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
oeg= new OpenEditorActionGroup(this),
ovg= new OpenViewActionGroup(this),
jsg= new JavaSearchActionGroup(this)
});
fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] {oeg, ovg, jsg});
resAction= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", this, ISourceViewer.INFORMATION, true); //$NON-NLS-1$
resAction= new InformationDispatchAction(JavaEditorMessages.getResourceBundle(), "ShowJavaDoc.", (TextOperationAction) resAction); //$NON-NLS-1$
resAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_JAVADOC);
setAction("ShowJavaDoc", resAction); //$NON-NLS-1$
Action action= new GotoMatchingBracketAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_MATCHING_BRACKET);
setAction(GotoMatchingBracketAction.GOTO_MATCHING_BRACKET, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"ShowOutline.", this, JavaSourceViewer.SHOW_OUTLINE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SHOW_OUTLINE);
setAction(IJavaEditorActionDefinitionIds.SHOW_OUTLINE, action);
action= new TextOperationAction(JavaEditorMessages.getResourceBundle(),"OpenStructure.", this, JavaSourceViewer.OPEN_STRUCTURE, true); //$NON-NLS-1$
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE);
setAction(IJavaEditorActionDefinitionIds.OPEN_STRUCTURE, action);
fEncodingSupport= new DefaultEncodingSupport();
fEncodingSupport.initialize(this);
fSelectionHistory= new SelectionHistory(this);
action= new StructureSelectEnclosingAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING);
setAction(StructureSelectionAction.ENCLOSING, action);
action= new StructureSelectNextAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_NEXT);
setAction(StructureSelectionAction.NEXT, action);
action= new StructureSelectPreviousAction(this, fSelectionHistory);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_PREVIOUS);
setAction(StructureSelectionAction.PREVIOUS, action);
StructureSelectHistoryAction historyAction= new StructureSelectHistoryAction(this, fSelectionHistory);
historyAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_LAST);
setAction(StructureSelectionAction.HISTORY, historyAction);
fSelectionHistory.setHistoryAction(historyAction);
action= GoToNextPreviousMemberAction.newGoToNextMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_NEXT_MEMBER);
setAction(GoToNextPreviousMemberAction.NEXT_MEMBER, action);
action= GoToNextPreviousMemberAction.newGoToPreviousMemberAction(this);
action.setActionDefinitionId(IJavaEditorActionDefinitionIds.GOTO_PREVIOUS_MEMBER);
setAction(GoToNextPreviousMemberAction.PREVIOUS_MEMBER, action);
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
}
public void updatedTitleImage(Image image) {
setTitleImage(image);
}
/*
* @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent)
*/
protected void handlePreferenceStoreChanged(PropertyChangeEvent event) {
try {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer == null)
return;
String property= event.getProperty();
if (PreferenceConstants.EDITOR_TAB_WIDTH.equals(property)) {
Object value= event.getNewValue();
if (value instanceof Integer) {
sourceViewer.getTextWidget().setTabs(((Integer) value).intValue());
} else if (value instanceof String) {
sourceViewer.getTextWidget().setTabs(Integer.parseInt((String) value));
}
return;
}
if (OVERVIEW_RULER.equals(property)) {
if (isOverviewRulerVisible())
showOverviewRuler();
else
hideOverviewRuler();
return;
}
if (LINE_NUMBER_RULER.equals(property)) {
if (isLineNumberRulerVisible())
showLineNumberRuler();
else
hideLineNumberRuler();
return;
}
if (fLineNumberRulerColumn != null &&
(LINE_NUMBER_COLOR.equals(property) ||
PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT.equals(property) ||
PREFERENCE_COLOR_BACKGROUND.equals(property))) {
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
}
if (isJavaEditorHoverProperty(property))
updateHoverBehavior();
if (BROWSER_LIKE_LINKS.equals(property)) {
if (isBrowserLikeLinks())
enableBrowserLikeLinks();
else
disableBrowserLikeLinks();
return;
}
} finally {
super.handlePreferenceStoreChanged(event);
}
}
private boolean isJavaEditorHoverProperty(String property) {
return PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS.equals(property);
}
/**
* Return whether the browser like links should be enabled
* according to the preference store settings.
* @return <code>true</code> if the browser like links should be enabled
*/
private boolean isBrowserLikeLinks() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(BROWSER_LIKE_LINKS);
}
/**
* Enables browser like links.
*/
private void enableBrowserLikeLinks() {
if (fMouseListener == null) {
fMouseListener= new MouseClickListener();
fMouseListener.install();
}
}
/**
* Disables browser like links.
*/
private void disableBrowserLikeLinks() {
if (fMouseListener != null) {
fMouseListener.uninstall();
fMouseListener= null;
}
}
/**
* Handles a property change event describing a change
* of the java core's preferences and updates the preference
* related editor properties.
*
* @param event the property change event
*/
protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) {
if (COMPILER_TASK_TAGS.equals(event.getProperty())) {
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer != null && affectsTextPresentation(new PropertyChangeEvent(event.getSource(), event.getProperty(), event.getOldValue(), event.getNewValue())))
sourceViewer.invalidateTextPresentation();
}
}
/**
* Shows the line number ruler column.
*/
private void showLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.addDecorator(1, createLineNumberRulerColumn());
}
}
/**
* Hides the line number ruler column.
*/
private void hideLineNumberRuler() {
IVerticalRuler v= getVerticalRuler();
if (v instanceof CompositeRuler) {
CompositeRuler c= (CompositeRuler) v;
c.removeDecorator(1);
}
}
/**
* Return whether the line number ruler column should be
* visible according to the preference store settings.
* @return <code>true</code> if the line numbers should be visible
*/
private boolean isLineNumberRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(LINE_NUMBER_RULER);
}
/**
* Returns a segmentation of the line of the given document appropriate for bidi rendering.
* The default implementation returns only the string literals of a java code line as segments.
*
* @param document the document
* @param lineOffset the offset of the line
* @return the line's bidi segmentation
* @throws BadLocationException in case lineOffset is not valid in document
*/
public static int[] getBidiLineSegments(IDocument document, int lineOffset) throws BadLocationException {
IRegion line= document.getLineInformationOfOffset(lineOffset);
ITypedRegion[] linePartitioning= document.computePartitioning(lineOffset, line.getLength());
List segmentation= new ArrayList();
for (int i= 0; i < linePartitioning.length; i++) {
if (JavaPartitionScanner.JAVA_STRING.equals(linePartitioning[i].getType()))
segmentation.add(linePartitioning[i]);
}
if (segmentation.size() == 0)
return null;
int size= segmentation.size();
int[] segments= new int[size * 2 + 1];
int j= 0;
for (int i= 0; i < size; i++) {
ITypedRegion segment= (ITypedRegion) segmentation.get(i);
if (i == 0)
segments[j++]= 0;
int offset= segment.getOffset() - lineOffset;
if (offset > segments[j - 1])
segments[j++]= offset;
if (offset + segment.getLength() >= line.getLength())
break;
segments[j++]= offset + segment.getLength();
}
if (j < segments.length) {
int[] result= new int[j];
System.arraycopy(segments, 0, result, 0, j);
segments= result;
}
return segments;
}
/**
* Returns a segmentation of the given line appropriate for bidi rendering. The default
* implementation returns only the string literals of a java code line as segments.
*
* @param lineOffset the offset of the line
* @param line the content of the line
* @return the line's bidi segmentation
*/
protected int[] getBidiLineSegments(int widgetLineOffset, String line) {
IDocumentProvider provider= getDocumentProvider();
if (provider != null && line != null && line.length() > 0) {
IDocument document= provider.getDocument(getEditorInput());
if (document != null)
try {
int lineOffset;
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
lineOffset= extension.widgetOffset2ModelOffset(widgetLineOffset);
} else {
IRegion visible= sourceViewer.getVisibleRegion();
lineOffset= visible.getOffset() + widgetLineOffset;
}
return getBidiLineSegments(document, lineOffset);
} catch (BadLocationException x) {
// ignore
}
}
return null;
}
/*
* @see AbstractTextEditor#handleCursorPositionChanged()
*/
protected void handleCursorPositionChanged() {
super.handleCursorPositionChanged();
if (!isEditingScriptRunning() && fUpdater != null)
fUpdater.post();
}
/**
* Initializes the given line number ruler column from the preference store.
* @param rulerColumn the ruler column to be initialized
*/
protected void initializeLineNumberRulerColumn(LineNumberRulerColumn rulerColumn) {
JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools();
IColorManager manager= textTools.getColorManager();
IPreferenceStore store= getPreferenceStore();
if (store != null) {
RGB rgb= null;
// foreground color
if (store.contains(LINE_NUMBER_COLOR)) {
if (store.isDefault(LINE_NUMBER_COLOR))
rgb= PreferenceConverter.getDefaultColor(store, LINE_NUMBER_COLOR);
else
rgb= PreferenceConverter.getColor(store, LINE_NUMBER_COLOR);
}
rulerColumn.setForeground(manager.getColor(rgb));
rgb= null;
// background color
if (!store.getBoolean(PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT)) {
if (store.contains(PREFERENCE_COLOR_BACKGROUND)) {
if (store.isDefault(PREFERENCE_COLOR_BACKGROUND))
rgb= PreferenceConverter.getDefaultColor(store, PREFERENCE_COLOR_BACKGROUND);
else
rgb= PreferenceConverter.getColor(store, PREFERENCE_COLOR_BACKGROUND);
}
}
rulerColumn.setBackground(manager.getColor(rgb));
rulerColumn.redraw();
}
}
/**
* Creates a new line number ruler column that is appropriately initialized.
*/
protected IVerticalRulerColumn createLineNumberRulerColumn() {
fLineNumberRulerColumn= new LineNumberRulerColumn();
initializeLineNumberRulerColumn(fLineNumberRulerColumn);
return fLineNumberRulerColumn;
}
/*
* @see AbstractTextEditor#createVerticalRuler()
*/
protected IVerticalRuler createVerticalRuler() {
CompositeRuler ruler= new CompositeRuler();
ruler.addDecorator(0, new AnnotationRulerColumn(VERTICAL_RULER_WIDTH));
if (isLineNumberRulerVisible())
ruler.addDecorator(1, createLineNumberRulerColumn());
return ruler;
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#updatePropertyDependentActions()
*/
protected void updatePropertyDependentActions() {
super.updatePropertyDependentActions();
if (fEncodingSupport != null)
fEncodingSupport.reset();
}
/*
* Update the hovering behavior depending on the preferences.
*/
private void updateHoverBehavior() {
SourceViewerConfiguration configuration= getSourceViewerConfiguration();
String[] types= configuration.getConfiguredContentTypes(getSourceViewer());
for (int i= 0; i < types.length; i++) {
String t= types[i];
ISourceViewer sourceViewer= getSourceViewer();
if (sourceViewer instanceof ITextViewerExtension2) {
// Remove existing hovers
((ITextViewerExtension2)sourceViewer).removeTextHovers(t);
int[] stateMasks= configuration.getConfiguredTextHoverStateMasks(getSourceViewer(), t);
if (stateMasks != null) {
for (int j= 0; j < stateMasks.length; j++) {
int stateMask= stateMasks[j];
ITextHover textHover= configuration.getTextHover(sourceViewer, t, stateMask);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, stateMask);
}
} else {
ITextHover textHover= configuration.getTextHover(sourceViewer, t);
((ITextViewerExtension2)sourceViewer).setTextHover(textHover, t, ITextViewerExtension2.DEFAULT_HOVER_STATE_MASK);
}
} else
sourceViewer.setTextHover(configuration.getTextHover(sourceViewer, t), t);
}
}
/*
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
return getEditorInput().getAdapter(IJavaElement.class);
}
/*
* @see org.eclipse.ui.texteditor.AbstractTextEditor#doSetSelection(ISelection)
*/
protected void doSetSelection(ISelection selection) {
super.doSetSelection(selection);
synchronizeOutlinePageSelection();
}
/*
* @see org.eclipse.ui.IWorkbenchPart#createPartControl(org.eclipse.swt.
* widgets.Composite)
*/
public void createPartControl(Composite parent) {
super.createPartControl(parent);
fSourceViewerDecorationSupport.install(getPreferenceStore());
Preferences preferences= JavaCore.getPlugin().getPluginPreferences();
preferences.addPropertyChangeListener(fPropertyChangeListener);
IInformationControlCreator informationControlCreator= new IInformationControlCreator() {
public IInformationControl createInformationControl(Shell parent) {
boolean cutDown= false;
int style= cutDown ? SWT.NONE : (SWT.V_SCROLL | SWT.H_SCROLL);
return new DefaultInformationControl(parent, SWT.RESIZE, style, new HTMLTextPresenter(cutDown));
}
};
fInformationPresenter= new InformationPresenter(informationControlCreator);
fInformationPresenter.setSizeConstraints(60, 10, true, true);
fInformationPresenter.install(getSourceViewer());
}
protected void showOverviewRuler() {
if (fOverviewRuler != null) {
if (getSourceViewer() instanceof ISourceViewerExtension) {
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(true);
fSourceViewerDecorationSupport.updateOverviewDecorations();
}
}
}
protected void hideOverviewRuler() {
if (getSourceViewer() instanceof ISourceViewerExtension) {
fSourceViewerDecorationSupport.hideAnnotationOverview();
((ISourceViewerExtension) getSourceViewer()).showAnnotationsOverview(false);
}
}
protected boolean isOverviewRulerVisible() {
IPreferenceStore store= getPreferenceStore();
return store.getBoolean(OVERVIEW_RULER);
}
protected void configureSourceViewerDecorationSupport() {
fSourceViewerDecorationSupport.setCharacterPairMatcher(fBracketMatcher);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.UNKNOWN, UNKNOWN_INDICATION_COLOR, UNKNOWN_INDICATION, UNKNOWN_INDICATION_IN_OVERVIEW_RULER, 0);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.BOOKMARK, BOOKMARK_INDICATION_COLOR, BOOKMARK_INDICATION, BOOKMARK_INDICATION_IN_OVERVIEW_RULER, 1);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.TASK, TASK_INDICATION_COLOR, TASK_INDICATION, TASK_INDICATION_IN_OVERVIEW_RULER, 2);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.SEARCH, SEARCH_RESULT_INDICATION_COLOR, SEARCH_RESULT_INDICATION, SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER, 3);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.WARNING, WARNING_INDICATION_COLOR, WARNING_INDICATION, WARNING_INDICATION_IN_OVERVIEW_RULER, 4);
fSourceViewerDecorationSupport.setAnnotationPainterPreferenceKeys(AnnotationType.ERROR, ERROR_INDICATION_COLOR, ERROR_INDICATION, ERROR_INDICATION_IN_OVERVIEW_RULER, 5);
fSourceViewerDecorationSupport.setCursorLinePainterPreferenceKeys(CURRENT_LINE, CURRENT_LINE_COLOR);
fSourceViewerDecorationSupport.setMarginPainterPreferenceKeys(PRINT_MARGIN, PRINT_MARGIN_COLOR, PRINT_MARGIN_COLUMN);
fSourceViewerDecorationSupport.setMatchingCharacterPainterPreferenceKeys(MATCHING_BRACKETS, MATCHING_BRACKETS_COLOR);
}
/**
* Jumps to the matching bracket.
*/
public void gotoMatchingBracket() {
ISourceViewer sourceViewer= getSourceViewer();
IDocument document= sourceViewer.getDocument();
if (document == null)
return;
IRegion selection= getSignedSelection(sourceViewer);
int selectionLength= Math.abs(selection.getLength());
if (selectionLength > 1) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.invalidSelection")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
// #26314
int sourceCaretOffset= selection.getOffset() + selection.getLength();
if (isSurroundedByBrackets(document, sourceCaretOffset))
sourceCaretOffset -= selection.getLength();
IRegion region= fBracketMatcher.match(document, sourceCaretOffset);
if (region == null) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.noMatchingBracket")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
int offset= region.getOffset();
int length= region.getLength();
if (length < 1)
return;
int anchor= fBracketMatcher.getAnchor();
int targetOffset= (JavaPairMatcher.RIGHT == anchor) ? offset : offset + length - 1;
boolean visible= false;
if (sourceViewer instanceof ITextViewerExtension3) {
ITextViewerExtension3 extension= (ITextViewerExtension3) sourceViewer;
visible= (extension.modelOffset2WidgetOffset(targetOffset) > -1);
} else {
IRegion visibleRegion= sourceViewer.getVisibleRegion();
visible= (targetOffset >= visibleRegion.getOffset() && targetOffset < visibleRegion.getOffset() + visibleRegion.getLength());
}
if (!visible) {
setStatusLineErrorMessage(JavaEditorMessages.getString("GotoMatchingBracket.error.bracketOutsideSelectedElement")); //$NON-NLS-1$
sourceViewer.getTextWidget().getDisplay().beep();
return;
}
if (selection.getLength() < 0)
targetOffset -= selection.getLength();
sourceViewer.setSelectedRange(targetOffset, selection.getLength());
sourceViewer.revealRange(targetOffset, selection.getLength());
}
/**
* Ses the given message as error message to this editor's status line.
* @param msg message to be set
*/
protected void setStatusLineErrorMessage(String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
}
private static IRegion getSignedSelection(ITextViewer viewer) {
StyledText text= viewer.getTextWidget();
int caretOffset= text.getCaretOffset();
Point selection= text.getSelection();
// caret left
int offset, length;
if (caretOffset == selection.x) {
offset= selection.y;
length= selection.x - selection.y;
// caret right
} else {
offset= selection.x;
length= selection.y - selection.x;
}
return new Region(offset, length);
}
private static boolean isBracket(char character) {
for (int i= 0; i != BRACKETS.length; ++i)
if (character == BRACKETS[i])
return true;
return false;
}
private static boolean isSurroundedByBrackets(IDocument document, int offset) {
if (offset == 0 || offset == document.getLength())
return false;
try {
return
isBracket(document.getChar(offset - 1)) &&
isBracket(document.getChar(offset));
} catch (BadLocationException e) {
return false;
}
}
/**
* Jumps to the error next according to the given direction.
*/
public void gotoError(boolean forward) {
ISelectionProvider provider= getSelectionProvider();
ITextSelection s= (ITextSelection) provider.getSelection();
Position errorPosition= new Position(0, 0);
IJavaAnnotation nextError= getNextError(s.getOffset(), forward, errorPosition);
if (nextError != null) {
IMarker marker= null;
if (nextError instanceof MarkerAnnotation)
marker= ((MarkerAnnotation) nextError).getMarker();
else {
Iterator e= nextError.getOverlaidIterator();
if (e != null) {
while (e.hasNext()) {
Object o= e.next();
if (o instanceof MarkerAnnotation) {
marker= ((MarkerAnnotation) o).getMarker();
break;
}
}
}
}
if (marker != null) {
IWorkbenchPage page= getSite().getPage();
IViewPart view= view= page.findView("org.eclipse.ui.views.TaskList"); //$NON-NLS-1$
if (view instanceof TaskList) {
StructuredSelection ss= new StructuredSelection(marker);
((TaskList) view).setSelection(ss, true);
}
}
selectAndReveal(errorPosition.getOffset(), errorPosition.getLength());
setStatusLineErrorMessage(nextError.getMessage());
} else {
setStatusLineErrorMessage(null);
}
}
private IJavaAnnotation getNextError(int offset, boolean forward, Position errorPosition) {
IJavaAnnotation nextError= null;
Position nextErrorPosition= null;
IDocument document= getDocumentProvider().getDocument(getEditorInput());
int endOfDocument= document.getLength();
int distance= 0;
IAnnotationModel model= getDocumentProvider().getAnnotationModel(getEditorInput());
Iterator e= new JavaAnnotationIterator(model, false);
while (e.hasNext()) {
IJavaAnnotation a= (IJavaAnnotation) e.next();
if (a.hasOverlay() || !a.isProblem())
continue;
Position p= model.getPosition((Annotation) a);
if (!p.includes(offset)) {
int currentDistance= 0;
if (forward) {
currentDistance= p.getOffset() - offset;
if (currentDistance < 0)
currentDistance= endOfDocument - offset + p.getOffset();
} else {
currentDistance= offset - p.getOffset();
if (currentDistance < 0)
currentDistance= offset + endOfDocument - p.getOffset();
}
if (nextError == null || currentDistance < distance) {
distance= currentDistance;
nextError= a;
nextErrorPosition= p;
}
}
}
if (nextErrorPosition != null) {
errorPosition.setOffset(nextErrorPosition.getOffset());
errorPosition.setLength(nextErrorPosition.getLength());
}
return nextError;
}
}
|
31,235 |
Bug 31235 Move: source accepts itself as target [DnD] [ccp]
|
I20030206 - Java project with two folder src1 and src2 where src1 is on the build path (e.g. source folder) - select src2 and start DnD and move it over src2. Observe: DnD is enabled.
|
resolved fixed
|
ebd8e3d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:21:20Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/core
| |
31,235 |
Bug 31235 Move: source accepts itself as target [DnD] [ccp]
|
I20030206 - Java project with two folder src1 and src2 where src1 is on the build path (e.g. source folder) - select src2 and start DnD and move it over src2. Observe: DnD is enabled.
|
resolved fixed
|
ebd8e3d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:21:20Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/MoveRefactoring.java
| |
31,235 |
Bug 31235 Move: source accepts itself as target [DnD] [ccp]
|
I20030206 - Java project with two folder src1 and src2 where src1 is on the build path (e.g. source folder) - select src2 and start DnD and move it over src2. Observe: DnD is enabled.
|
resolved fixed
|
ebd8e3d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:21:20Z | 2003-02-07T12:13:20Z |
org.eclipse.jdt.ui/core
| |
31,235 |
Bug 31235 Move: source accepts itself as target [DnD] [ccp]
|
I20030206 - Java project with two folder src1 and src2 where src1 is on the build path (e.g. source folder) - select src2 and start DnD and move it over src2. Observe: DnD is enabled.
|
resolved fixed
|
ebd8e3d
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:21:20Z | 2003-02-07T12:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/reorg/ReorgRefactoring.java
| |
31,534 |
Bug 31534 List with files of non-externalized strings should show project [NLS Tools]
|
Build I20030211 1. Select 2 projects (which have non-externalized strings) 2. Look at the list: the project is not shown only the project-relative path
|
resolved fixed
|
91f45ad
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:27:37Z | 2003-02-11T13:26:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindStringsToExternalizeAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
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.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.WorkbenchHelp;
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.JavaModelException;
import org.eclipse.jdt.core.compiler.InvalidInputException;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSElement;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSLine;
import org.eclipse.jdt.internal.corext.refactoring.nls.NLSScanner;
import org.eclipse.jdt.internal.corext.refactoring.util.ResourceUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.ListDialog;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.ListContentProvider;
/**
* Find all Strings in a package or project that are not externalized yet.
* <p>
* The action is applicable to selections containing projects or packages.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class FindStringsToExternalizeAction extends SelectionDispatchAction {
private NonNLSElement[] fElements;
/**
* Creates a new <code>FindStringsToExternalizeAction</code>. The action
* requires that the selection provided by the site's selection provider is of type
* <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public FindStringsToExternalizeAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("FindStringsToExternalizeAction.label")); //$NON-NLS-1$
fElements= new NonNLSElement[0];
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_STRINGS_TO_EXTERNALIZE_ACTION);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(computeEnablementState(selection));
}
private boolean computeEnablementState(IStructuredSelection selection) {
if (selection.isEmpty())
return false;
for (Iterator iter= selection.iterator(); iter.hasNext();) {
Object element= (Object)iter.next();
if (!(element instanceof IJavaElement))
return false;
int elementType= ((IJavaElement)element).getElementType();
if (elementType != IJavaElement.PACKAGE_FRAGMENT && elementType != IJavaElement.PACKAGE_FRAGMENT_ROOT &&
elementType != IJavaElement.JAVA_PROJECT)
return false;
}
return true;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(final IStructuredSelection selection) {
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().run(true, true, createRunnable(selection));
} catch(InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(),
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return;
} catch(InterruptedException e) {
//ok
return;
}
showResults();
}
private IRunnableWithProgress createRunnable(final IStructuredSelection selection) {
return new IRunnableWithProgress() {
public void run(IProgressMonitor pm) {
fElements= doRun(selection, pm);
}
};
}
private NonNLSElement[] doRun(IStructuredSelection selection, IProgressMonitor pm) {
List elements= getSelectedElementList(selection);
if (elements == null || elements.isEmpty())
return new NonNLSElement[0];
pm.beginTask(ActionMessages.getString("FindStringsToExternalizeAction.find_strings"), elements.size()); //$NON-NLS-1$
try{
List l= new ArrayList();
for (Iterator iter= elements.iterator(); iter.hasNext();) {
IJavaElement element= (IJavaElement) iter.next();
if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
l.addAll(analyze((IPackageFragment) element, new SubProgressMonitor(pm, 1)));
else if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT_ROOT)
l.addAll(analyze((IPackageFragmentRoot) element, new SubProgressMonitor(pm, 1)));
if (element.getElementType() == IJavaElement.JAVA_PROJECT)
l.addAll(analyze((IJavaProject) element, new SubProgressMonitor(pm, 1)));
}
return (NonNLSElement[]) l.toArray(new NonNLSElement[l.size()]);
} catch(JavaModelException e) {
ExceptionHandler.handle(e,
getDialogTitle(),
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return new NonNLSElement[0];
} finally{
pm.done();
}
}
private void showResults() {
if (noStrings())
MessageDialog.openInformation(getShell(),
getDialogTitle(),
ActionMessages.getString("FindStringsToExternalizeAction.noStrings")); //$NON-NLS-1$
else
new NonNLSListDialog(getShell(), fElements, countStrings()).open();
}
private boolean noStrings() {
for (int i = 0; i < fElements.length; i++) {
if (fElements[i].count != 0)
return false;
}
return true;
}
/*
* returns List of Strings
*/
private List analyze(IPackageFragment pack, IProgressMonitor pm) throws JavaModelException{
try{
if (pack == null)
return new ArrayList(0);
ICompilationUnit[] cus= pack.getCompilationUnits();
pm.beginTask("", cus.length); //$NON-NLS-1$
pm.setTaskName(pack.getElementName());
List l= new ArrayList(cus.length);
for (int i= 0; i < cus.length; i++){
pm.subTask(cus[i].getElementName());
NonNLSElement element = analyze(cus[i]);
if (element != null)
l.add(element);
pm.worked(1);
if (pm.isCanceled())
throw new OperationCanceledException();
}
return l;
} finally {
pm.done();
}
}
/*
* returns List of Strings
*/
private List analyze(IPackageFragmentRoot sourceFolder, IProgressMonitor pm) throws JavaModelException{
try{
IJavaElement[] children= sourceFolder.getChildren();
pm.beginTask("", children.length); //$NON-NLS-1$
pm.setTaskName(sourceFolder.getElementName());
List result= new ArrayList();
for (int i= 0; i < children.length; i++) {
IJavaElement iJavaElement= children[i];
if (iJavaElement.getElementType() == IJavaElement.PACKAGE_FRAGMENT){
IPackageFragment pack= (IPackageFragment)iJavaElement;
if (! pack.isReadOnly())
result.addAll(analyze(pack, new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
} else
pm.worked(1);
}
return result;
} finally{
pm.done();
}
}
/*
* returns List of Strings
*/
private List analyze(IJavaProject project, IProgressMonitor pm) throws JavaModelException{
try{
IPackageFragment[] packs= project.getPackageFragments();
pm.beginTask("", packs.length); //$NON-NLS-1$
List result= new ArrayList();
for (int i= 0; i < packs.length; i++) {
if (! packs[i].isReadOnly())
result.addAll(analyze(packs[i], new SubProgressMonitor(pm, 1)));
else
pm.worked(1);
}
return result;
} finally{
pm.done();
}
}
private int countStrings(){
int found= 0;
for (int i= 0; i < fElements.length; i++)
found += fElements[i].count;
return found;
}
private NonNLSElement analyze(ICompilationUnit cu) throws JavaModelException{
int count = countNotExternalizedStrings(cu);
if (count == 0)
return null;
else
return new NonNLSElement(cu, count);
}
private int countNotExternalizedStrings(ICompilationUnit cu){
try{
NLSLine[] lines= NLSScanner.scan(cu);
int result= 0;
for (int i= 0; i < lines.length; i++) {
result += countNotExternalizedStrings(lines[i]);
}
return result;
}catch(JavaModelException e) {
ExceptionHandler.handle(e,
getDialogTitle(),
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
return 0;
}catch(InvalidInputException iie) {
JavaPlugin.log(iie);
return 0;
}
}
private int countNotExternalizedStrings(NLSLine line){
int result= 0;
NLSElement[] elements= line.getElements();
for (int i= 0; i < elements.length; i++){
if (! elements[i].hasTag())
result++;
}
return result;
}
/**
* returns <code>List</code> of <code>IPackageFragments</code>, <code>IPackageFragmentRoots</code> or
* <code>IJavaProjects</code> (all entries are of the same kind)
*/
private static List getSelectedElementList(IStructuredSelection selection) {
if (selection == null)
return null;
return selection.toList();
}
//-------private classes --------------
private static class NonNLSListDialog extends ListDialog {
private static final int OPEN_BUTTON_ID= IDialogConstants.CLIENT_ID + 1;
private Button fOpenButton;
NonNLSListDialog(Shell parent, NonNLSElement[] input, int count) {
super(parent);
setInput(Arrays.asList(input));
setTitle(ActionMessages.getString("FindStringsToExternalizeAction.dialog.title")); //$NON-NLS-1$
setMessage(ActionMessages.getFormattedString("FindStringsToExternalizeAction.not_externalized", new Object[] {new Integer(count)} )); //$NON-NLS-1$
setContentProvider(new ListContentProvider());
setLabelProvider(createLabelProvider());
}
public void create() {
setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN);
super.create();
}
protected Point getInitialSize() {
return getShell().computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
}
protected Control createDialogArea(Composite parent) {
Composite result= (Composite)super.createDialogArea(parent);
getTableViewer().addSelectionChangedListener(new ISelectionChangedListener(){
public void selectionChanged(SelectionChangedEvent event){
if (fOpenButton != null){
fOpenButton.setEnabled(! getTableViewer().getSelection().isEmpty());
}
}
});
getTableViewer().getTable().addSelectionListener(new SelectionAdapter(){
public void widgetDefaultSelected(SelectionEvent e) {
NonNLSElement element= (NonNLSElement)e.item.getData();
openWizard(element.cu);
}
});
getTableViewer().getTable().setFocus();
return result;
}
protected void createButtonsForButtonBar(Composite parent) {
fOpenButton= createButton(parent, OPEN_BUTTON_ID, ActionMessages.getString("FindStringsToExternalizeAction.button.label"), true); //$NON-NLS-1$
fOpenButton.setEnabled(false);
//looks like a 'close' but it a 'cancel'
createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CLOSE_LABEL, false);
}
protected void buttonPressed(int buttonId) {
if (buttonId != OPEN_BUTTON_ID){
super.buttonPressed(buttonId);
return;
}
ISelection s= getTableViewer().getSelection();
if (s instanceof IStructuredSelection){
IStructuredSelection ss= (IStructuredSelection)s;
if (ss.getFirstElement() instanceof NonNLSElement)
openWizard(((NonNLSElement)ss.getFirstElement()).cu);
}
}
private void openWizard(ICompilationUnit unit) {
try {
ExternalizeStringsAction.openExternalizeStringsWizard(unit);
} catch (JavaModelException e) {
ExceptionHandler.handle(e,
ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"), //$NON-NLS-1$
ActionMessages.getString("FindStringsToExternalizeAction.error.message")); //$NON-NLS-1$
}
}
private static LabelProvider createLabelProvider() {
return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT){
public String getText(Object element) {
NonNLSElement nlsel= (NonNLSElement)element;
String elementName= ResourceUtil.getResource(nlsel.cu).getProjectRelativePath().toString();
return ActionMessages.getFormattedString(
"FindStringsToExternalizeAction.foundStrings", //$NON-NLS-1$
new Object[] {new Integer(nlsel.count), elementName} );
}
public Image getImage(Object element) {
return super.getImage(((NonNLSElement)element).cu);
}
};
}
/*
* @see org.eclipse.jface.window.Window#configureShell(Shell)
*/
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.NONNLS_DIALOG);
}
}
private static class NonNLSElement{
ICompilationUnit cu;
int count;
NonNLSElement(ICompilationUnit cu, int count){
this.cu= cu;
this.count= count;
}
}
private String getDialogTitle() {
return ActionMessages.getString("FindStringsToExternalizeAction.dialog.title"); //$NON-NLS-1$
}
}
|
30,587 |
Bug 30587 inline method deletes non-javadoc comment after the inlined method
|
inline method on inline(): public class Test { public int inline() { return 0; } /* * Method test. */ public void test() { int tmp= inline(); } } results in: public class Test { public void test() { int tmp= 0; } } this only happens with non-javadoc comments.
|
resolved fixed
|
411b064
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:31:27Z | 2003-01-30T09:46:40Z |
org.eclipse.jdt.ui/core
| |
30,587 |
Bug 30587 inline method deletes non-javadoc comment after the inlined method
|
inline method on inline(): public class Test { public int inline() { return 0; } /* * Method test. */ public void test() { int tmp= inline(); } } results in: public class Test { public void test() { int tmp= 0; } } this only happens with non-javadoc comments.
|
resolved fixed
|
411b064
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T18:31:27Z | 2003-01-30T09:46:40Z |
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteAnalyzer.java
| |
31,083 |
Bug 31083 PackageView - logic container doesn't show up in classpath order [package explorer]
|
Build 20030206 The JRE System Library container shows up at the bottom of my project's children, where it is actually ordered first on my build path. This feels inconsistent with our approach of sticking to the build path.
|
resolved fixed
|
0d4cee9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T20:40:02Z | 2003-02-06T14:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/ClassPathContainer.java
|
package org.eclipse.jdt.internal.ui.packageview;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jdt.core.IClasspathContainer;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.model.IWorkbenchAdapter;
/**
* Representation of class path containers in Java UI.
*/
public class ClassPathContainer implements IAdaptable, IWorkbenchAdapter {
private IJavaProject fProject;
private IClasspathEntry fClassPathEntry;
private IClasspathContainer fContainer;
public ClassPathContainer(IJavaProject parent, IClasspathEntry entry) {
fProject= parent;
fClassPathEntry= entry;
try {
fContainer = JavaCore.getClasspathContainer(entry.getPath(), parent);
} catch (JavaModelException e) {
fContainer= null;
}
}
public Object[] getPackageFragmentRoots() throws JavaModelException {
return fProject.findPackageFragmentRoots(fClassPathEntry);
}
public Object getAdapter(Class adapter) {
if (adapter == IWorkbenchAdapter.class)
return this;
return null;
}
public Object[] getChildren(Object o) {
try {
return getPackageFragmentRoots();
} catch (JavaModelException e) {
return null;
}
}
public ImageDescriptor getImageDescriptor(Object object) {
return JavaPluginImages.DESC_OBJS_LIBRARY;
}
public String getLabel(Object o) {
if (fContainer != null)
return fContainer.getDescription();
return PackagesMessages.getString("ClassPathContainer.error_label"); //$NON-NLS-1$
}
public Object getParent(Object o) {
return fProject;
}
public IJavaProject getJavaProject() {
return fProject;
}
}
|
31,083 |
Bug 31083 PackageView - logic container doesn't show up in classpath order [package explorer]
|
Build 20030206 The JRE System Library container shows up at the bottom of my project's children, where it is actually ordered first on my build path. This feels inconsistent with our approach of sticking to the build path.
|
resolved fixed
|
0d4cee9
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-12T20:40:02Z | 2003-02-06T14:00:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementSorter.java
|
/*******************************************************************************
* Copyright (c) 2000, 2003 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui;
import java.text.Collator;
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.IAdaptable;
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.ui.model.IWorkbenchAdapter;
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.core.Signature;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
/**
* Sorter for Java elements. Ordered by element category, then by element name.
* Package fragment roots are sorted as ordered on the classpath.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class JavaElementSorter extends ViewerSorter {
private static final int PROJECTS= 1;
private static final int PACKAGEFRAGMENTROOTS= 2;
private static final int PACKAGEFRAGMENT= 3;
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;
// Includes all categories ordered using the OutlineSortOrderPage:
// types, initializers, methods & fields
private static final int MEMBERSOFFSET= 15;
private static final int JAVAELEMENTS= 50;
private static final int OTHERS= 51;
public JavaElementSorter() {
super(null); // delay initialization of collator
}
/**
* @deprecated Bug 22518. Method never used: does not override ViewerSorter#isSorterProperty(Object, String).
* Method could be removed, but kept for API compatibility.
*/
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 getMemberCategory(MembersOrderPreferenceCache.CONSTRUCTORS_INDEX);
}
int flags= method.getFlags();
if (Flags.isStatic(flags))
return getMemberCategory(MembersOrderPreferenceCache.STATIC_METHODS_INDEX);
else
return getMemberCategory(MembersOrderPreferenceCache.METHOD_INDEX);
}
case IJavaElement.FIELD :
{
int flags= ((IField) je).getFlags();
if (Flags.isStatic(flags))
return getMemberCategory(MembersOrderPreferenceCache.STATIC_FIELDS_INDEX);
else
return getMemberCategory(MembersOrderPreferenceCache.FIELDS_INDEX);
}
case IJavaElement.INITIALIZER :
{
int flags= ((IInitializer) je).getFlags();
if (Flags.isStatic(flags))
return getMemberCategory(MembersOrderPreferenceCache.STATIC_INIT_INDEX);
else
return getMemberCategory(MembersOrderPreferenceCache.INIT_INDEX);
}
case IJavaElement.TYPE :
return getMemberCategory(MembersOrderPreferenceCache.TYPE_INDEX);
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().getResource() instanceof IProject) {
return PACKAGEFRAGMENTROOTS;
}
return PACKAGEFRAGMENT;
case IJavaElement.PACKAGE_FRAGMENT_ROOT :
return PACKAGEFRAGMENTROOTS;
case IJavaElement.JAVA_PROJECT :
return PROJECTS;
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 IProject) {
return PROJECTS;
} else if (element instanceof IContainer) {
return RESOURCEFOLDERS;
} else if (element instanceof IStorage) {
return STORAGE;
}
return OTHERS;
}
private int getMemberCategory(int kind) {
int offset= JavaPlugin.getDefault().getMemberOrderPreferenceCache().getIndex(kind);
return offset + MEMBERSOFFSET;
}
/*
* @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 == PROJECTS) {
IWorkbenchAdapter a1= (IWorkbenchAdapter)((IAdaptable)e1).getAdapter(IWorkbenchAdapter.class);
IWorkbenchAdapter a2= (IWorkbenchAdapter)((IAdaptable)e2).getAdapter(IWorkbenchAdapter.class);
return getCollator().compare(a1.getLabel(e1), a2.getLabel(e2));
}
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 == PROJECTS || cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) {
return compareWithLabelProvider(viewer, e1, e2);
}
String name1= ((IJavaElement) e1).getElementName();
String name2= ((IJavaElement) e2).getElementName();
// java element are sorted by name
int cmp= getCollator().compare(name1, name2);
if (cmp != 0) {
return cmp;
}
if (e1 instanceof IMethod) {
String[] params1= ((IMethod) e1).getParameterTypes();
String[] params2= ((IMethod) e2).getParameterTypes();
int len= Math.min(params1.length, params2.length);
for (int i = 0; i < len; i++) {
cmp= getCollator().compare(Signature.toString(params1[i]), Signature.toString(params2[i]));
if (cmp != 0) {
return cmp;
}
}
return params1.length - params2.length;
}
return 0;
}
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;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ViewerSorter#getCollator()
*/
public final Collator getCollator() {
if (collator == null) {
collator= Collator.getInstance();
}
return collator;
}
}
|
27,408 |
Bug 27408 Preference convertor also maps to font registry
| null |
resolved fixed
|
64643b1
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T09:17:03Z | 2002-11-29T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/JavaPlugin.java
|
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IPluginDescriptor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.preference.PreferenceConverter;
import org.eclipse.jface.resource.ImageRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.ui.IContextMenuConstants;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.text.JavaTextTools;
import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.jdt.internal.ui.javaeditor.ClassFileDocumentProvider;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitDocumentProvider;
import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferenceCache;
import org.eclipse.jdt.internal.ui.text.java.hover.JavaEditorTextHoverDescriptor;
import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemMarkerManager;
/**
* Represents the java plugin. It provides a series of convenience methods such as
* access to the workbench, keeps track of elements shared by all editors and viewers
* of the plugin such as document providers and find-replace-dialogs.
*/
public class JavaPlugin extends AbstractUIPlugin {
// TODO: Evaluate if we should move these ID's to JavaUI
/**
* The id of the best match hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_BESTMATCH_HOVER= "org.eclipse.jdt.ui.BestMatchHover"; //$NON-NLS-1$
/**
* The id of the source code hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_SOURCE_HOVER= "org.eclipse.jdt.ui.JavaSourceHover"; //$NON-NLS-1$
/**
* The id of the javadoc hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_JAVADOC_HOVER= "org.eclipse.jdt.ui.JavadocHover"; //$NON-NLS-1$
/**
* The id of the problem hover contributed for extension point
* <code>javaEditorTextHovers</code>.
*
* @since 2.1
*/
public static String ID_PROBLEM_HOVER= "org.eclipse.jdt.ui.ProblemHover"; //$NON-NLS-1$
private static JavaPlugin fgJavaPlugin;
private CompilationUnitDocumentProvider fCompilationUnitDocumentProvider;
private ClassFileDocumentProvider fClassFileDocumentProvider;
private JavaTextTools fJavaTextTools;
private ProblemMarkerManager fProblemMarkerManager;
private ImageDescriptorRegistry fImageDescriptorRegistry;
private JavaElementAdapterFactory fJavaElementAdapterFactory;
private MarkerAdapterFactory fMarkerAdapterFactory;
private EditorInputAdapterFactory fEditorInputAdapterFactory;
private ResourceAdapterFactory fResourceAdapterFactory;
private LogicalPackageAdapterFactory fLogicalPackageAdapterFactory;
private MembersOrderPreferenceCache fMembersOrderPreferenceCache;
private IPropertyChangeListener fFontPropertyChangeListener;
private JavaEditorTextHoverDescriptor[] fJavaEditorTextHoverDescriptors;
public static JavaPlugin getDefault() {
return fgJavaPlugin;
}
public static IWorkspace getWorkspace() {
return ResourcesPlugin.getWorkspace();
}
public static IWorkbenchPage getActivePage() {
return getDefault().internalGetActivePage();
}
public static IWorkbenchWindow getActiveWorkbenchWindow() {
return getDefault().getWorkbench().getActiveWorkbenchWindow();
}
public static Shell getActiveWorkbenchShell() {
return getActiveWorkbenchWindow().getShell();
}
/**
* Returns an array of all editors that have an unsaved content. If the identical content is
* presented in more than one editor, only one of those editor parts is part of the result.
*
* @return an array of all dirty editor parts.
*/
public static IEditorPart[] getDirtyEditors() {
Set inputs= new HashSet();
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int i= 0; i < windows.length; i++) {
IWorkbenchPage[] pages= windows[i].getPages();
for (int x= 0; x < pages.length; x++) {
IEditorPart[] editors= pages[x].getDirtyEditors();
for (int z= 0; z < editors.length; z++) {
IEditorPart ep= editors[z];
IEditorInput input= ep.getEditorInput();
if (!inputs.contains(input)) {
inputs.add(input);
result.add(ep);
}
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
}
/**
* Returns an array of all instanciated editors.
*/
public static IEditorPart[] getInstanciatedEditors() {
List result= new ArrayList(0);
IWorkbench workbench= getDefault().getWorkbench();
IWorkbenchWindow[] windows= workbench.getWorkbenchWindows();
for (int windowIndex= 0; windowIndex < windows.length; windowIndex++) {
IWorkbenchPage[] pages= windows[windowIndex].getPages();
for (int pageIndex= 0; pageIndex < pages.length; pageIndex++) {
IEditorReference[] references= pages[pageIndex].getEditorReferences();
for (int refIndex= 0; refIndex < references.length; refIndex++) {
IEditorPart editor= references[refIndex].getEditor(false);
if (editor != null)
result.add(editor);
}
}
}
return (IEditorPart[])result.toArray(new IEditorPart[result.size()]);
} public static String getPluginId() {
return getDefault().getDescriptor().getUniqueIdentifier();
}
public static void log(IStatus status) {
getDefault().getLog().log(status);
}
public static void logErrorMessage(String message) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null));
}
public static void logErrorStatus(String message, IStatus status) {
if (status == null) {
logErrorMessage(message);
return;
}
MultiStatus multi= new MultiStatus(getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, null);
multi.add(status);
log(multi);
}
public static void log(Throwable e) {
log(new Status(IStatus.ERROR, getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, JavaUIMessages.getString("JavaPlugin.internal_error"), e)); //$NON-NLS-1$
}
public static boolean isDebug() {
return getDefault().isDebugging();
}
/* package */ static IPath getInstallLocation() {
return new Path(getDefault().getDescriptor().getInstallURL().getFile());
}
public static ImageDescriptorRegistry getImageDescriptorRegistry() {
return getDefault().internalGetImageDescriptorRegistry();
}
public JavaPlugin(IPluginDescriptor descriptor) {
super(descriptor);
fgJavaPlugin= this;
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void startup() throws CoreException {
super.startup();
registerAdapters();
/*
* Backward compatibility: set the Java editor font in this plug-in's
* preference store to let older versions access it. Since 2.1 the
* Java editor font is managed by the workbench font preference page.
*/
PreferenceConverter.setValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
fFontPropertyChangeListener= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
if (PreferenceConstants.EDITOR_TEXT_FONT.equals(event.getProperty()))
PreferenceConverter.setValue(getPreferenceStore(), JFaceResources.TEXT_FONT, JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT).getFontData());
}
};
JFaceResources.getFontRegistry().addListener(fFontPropertyChangeListener);
}
/* (non - Javadoc)
* Method declared in AbstractUIPlugin
*/
protected ImageRegistry createImageRegistry() {
return JavaPluginImages.getImageRegistry();
}
/* (non - Javadoc)
* Method declared in Plugin
*/
public void shutdown() throws CoreException {
if (fImageDescriptorRegistry != null)
fImageDescriptorRegistry.dispose();
unregisterAdapters();
super.shutdown();
if (fCompilationUnitDocumentProvider != null) {
fCompilationUnitDocumentProvider.shutdown();
fCompilationUnitDocumentProvider= null;
}
if (fJavaTextTools != null) {
fJavaTextTools.dispose();
fJavaTextTools= null;
}
JavaDocLocations.shutdownJavadocLocations();
JFaceResources.getFontRegistry().removeListener(fFontPropertyChangeListener);
}
private IWorkbenchPage internalGetActivePage() {
IWorkbenchWindow window= getWorkbench().getActiveWorkbenchWindow();
if (window == null)
return null;
return getWorkbench().getActiveWorkbenchWindow().getActivePage();
}
public synchronized CompilationUnitDocumentProvider getCompilationUnitDocumentProvider() {
if (fCompilationUnitDocumentProvider == null)
fCompilationUnitDocumentProvider= new CompilationUnitDocumentProvider();
return fCompilationUnitDocumentProvider;
}
public synchronized ClassFileDocumentProvider getClassFileDocumentProvider() {
if (fClassFileDocumentProvider == null)
fClassFileDocumentProvider= new ClassFileDocumentProvider();
return fClassFileDocumentProvider;
}
public synchronized IWorkingCopyManager getWorkingCopyManager() {
return getCompilationUnitDocumentProvider();
}
public synchronized ProblemMarkerManager getProblemMarkerManager() {
if (fProblemMarkerManager == null)
fProblemMarkerManager= new ProblemMarkerManager();
return fProblemMarkerManager;
}
public synchronized JavaTextTools getJavaTextTools() {
if (fJavaTextTools == null)
fJavaTextTools= new JavaTextTools(getPreferenceStore(), JavaCore.getPlugin().getPluginPreferences());
return fJavaTextTools;
}
public synchronized MembersOrderPreferenceCache getMemberOrderPreferenceCache() {
if (fMembersOrderPreferenceCache == null)
fMembersOrderPreferenceCache= new MembersOrderPreferenceCache();
return fMembersOrderPreferenceCache;
}
/**
* Returns all Java editor text hovers contributed to the workbench.
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public JavaEditorTextHoverDescriptor[] getJavaEditorTextHoverDescriptors() {
if (fJavaEditorTextHoverDescriptors == null)
fJavaEditorTextHoverDescriptors= JavaEditorTextHoverDescriptor.getContributedHovers();
return fJavaEditorTextHoverDescriptors;
}
/**
* Resets the Java editor text hovers contributed to the workbench.
* <p>
* This will force a rebuild of the descriptors the next time
* a client asks for them.
* </p>
*
* @return an array of JavaEditorTextHoverDescriptor
* @since 2.1
*/
public void resetJavaEditorTextHoverDescriptors() {
fJavaEditorTextHoverDescriptors= null;
}
/**
* Creates the Java plugin standard groups in a context menu.
*/
public static void createStandardGroups(IMenuManager menu) {
if (!menu.isEmpty())
return;
menu.add(new Separator(IContextMenuConstants.GROUP_NEW));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_GOTO));
menu.add(new Separator(IContextMenuConstants.GROUP_OPEN));
menu.add(new GroupMarker(IContextMenuConstants.GROUP_SHOW));
menu.add(new Separator(IContextMenuConstants.GROUP_REORGANIZE));
menu.add(new Separator(IContextMenuConstants.GROUP_GENERATE));
menu.add(new Separator(IContextMenuConstants.GROUP_SEARCH));
menu.add(new Separator(IContextMenuConstants.GROUP_BUILD));
menu.add(new Separator(IContextMenuConstants.GROUP_ADDITIONS));
menu.add(new Separator(IContextMenuConstants.GROUP_VIEWER_SETUP));
menu.add(new Separator(IContextMenuConstants.GROUP_PROPERTIES));
}
/**
* @see AbstractUIPlugin#initializeDefaultPreferences
*/
protected void initializeDefaultPreferences(IPreferenceStore store) {
super.initializeDefaultPreferences(store);
PreferenceConstants.initializeDefaultValues(store);
}
private synchronized ImageDescriptorRegistry internalGetImageDescriptorRegistry() {
if (fImageDescriptorRegistry == null)
fImageDescriptorRegistry= new ImageDescriptorRegistry();
return fImageDescriptorRegistry;
}
private void registerAdapters() {
fJavaElementAdapterFactory= new JavaElementAdapterFactory();
fMarkerAdapterFactory= new MarkerAdapterFactory();
fEditorInputAdapterFactory= new EditorInputAdapterFactory();
fResourceAdapterFactory= new ResourceAdapterFactory();
fLogicalPackageAdapterFactory= new LogicalPackageAdapterFactory();
IAdapterManager manager= Platform.getAdapterManager();
manager.registerAdapters(fJavaElementAdapterFactory, IJavaElement.class);
manager.registerAdapters(fMarkerAdapterFactory, IMarker.class);
manager.registerAdapters(fEditorInputAdapterFactory, IEditorInput.class);
manager.registerAdapters(fResourceAdapterFactory, IResource.class);
manager.registerAdapters(fLogicalPackageAdapterFactory, LogicalPackage.class);
}
private void unregisterAdapters() {
IAdapterManager manager= Platform.getAdapterManager();
manager.unregisterAdapters(fJavaElementAdapterFactory);
manager.unregisterAdapters(fMarkerAdapterFactory);
manager.unregisterAdapters(fEditorInputAdapterFactory);
manager.unregisterAdapters(fResourceAdapterFactory);
manager.unregisterAdapters(fLogicalPackageAdapterFactory);
}
}
|
31,668 |
Bug 31668 Icons squished in Types view
|
I20030211 Now that (non-java) resources are available in the types view, I see squished icons. The attached picture shows what I mean. I think what's happening is that the package.html's icon is 16x16, and it constrains all the other icons in the tree to 16x16, but the JDT icons want to be wider than 16 to add decorations ("F", "A", etc) to the side.
|
resolved fixed
|
f66f7f6
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T09:33:11Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/filters/NonJavaElementFilter.java
| |
31,720 |
Bug 31720 Browsing views should add listener to page [Browsing]
| null |
resolved fixed
|
bea7ed5
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T09:38:57Z | 2003-02-12T22:46:40Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
|
/*
* (c) Copyright IBM Corp. 2000, 2002.
* All Rights Reserved.
*/
package org.eclipse.jdt.internal.ui.browsing;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
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.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.DragSourceEvent;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Shell;
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.text.ITextSelection;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.IContentProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IOpenListener;
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.OpenEvent;
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.IPartListener2;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartReference;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.part.ResourceTransfer;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.search.ui.ISearchResultView;
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.IPackageFragment;
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.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
import org.eclipse.jdt.ui.actions.BuildActionGroup;
import org.eclipse.jdt.ui.actions.CCPActionGroup;
import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup;
import org.eclipse.jdt.ui.actions.GenerateActionGroup;
import org.eclipse.jdt.ui.actions.ImportActionGroup;
import org.eclipse.jdt.ui.actions.JavaSearchActionGroup;
import org.eclipse.jdt.ui.actions.OpenEditorActionGroup;
import org.eclipse.jdt.ui.actions.OpenViewActionGroup;
import org.eclipse.jdt.ui.actions.RefactorActionGroup;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup;
import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup;
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.packageview.SelectionTransferDragAdapter;
import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter;
import org.eclipse.jdt.internal.ui.search.SearchUtil;
import org.eclipse.jdt.internal.ui.util.JavaUIHelp;
import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.DecoratingJavaLabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider;
import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer;
import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater;
import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup;
abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener, IViewPartInputProvider {
private static final String TAG_SELECTED_ELEMENTS= "selectedElements"; //$NON-NLS-1$
private static final String TAG_SELECTED_ELEMENT= "selectedElement"; //$NON-NLS-1$
private static final String TAG_LOGICAL_PACKAGE= "logicalPackage"; //$NON-NLS-1$
private static final String TAG_SELECTED_ELEMENT_PATH= "selectedElementPath"; //$NON-NLS-1$
private JavaUILabelProvider fLabelProvider;
private ILabelProvider fTitleProvider;
private StructuredViewer fViewer;
private IMemento fMemento;
private JavaElementTypeComparator fTypeComparator;
// Actions
private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup;
private boolean fHasWorkingSetFilter= true;
private boolean fHasCustomFilter= true;
private OpenEditorActionGroup fOpenEditorGroup;
private CCPActionGroup fCCPActionGroup;
private BuildActionGroup fBuildActionGroup;
protected CompositeActionGroup fActionGroups;
// Filters
private CustomFiltersActionGroup fCustomFiltersActionGroup;
protected IWorkbenchPart fPreviousSelectionProvider;
protected Object fPreviousSelectedElement;
/*
* Ensure selection changed events being processed only if
* initiated by user interaction with this part.
*/
private boolean fProcessSelectionEvents= true;
private IPartListener2 fPartListener= new IPartListener2() {
public void partActivated(IWorkbenchPartReference ref) {
setSelectionFromEditor(ref);
}
public void partBroughtToTop(IWorkbenchPartReference ref) {
setSelectionFromEditor(ref);
}
public void partInputChanged(IWorkbenchPartReference ref) {
setSelectionFromEditor(ref);
}
public void partClosed(IWorkbenchPartReference ref) {
}
public void partDeactivated(IWorkbenchPartReference ref) {
}
public void partOpened(IWorkbenchPartReference ref) {
}
public void partVisible(IWorkbenchPartReference ref) {
if (ref != null && ref.getId() == getSite().getId()){
fProcessSelectionEvents= true;
IWorkbenchPage page= getSite().getWorkbenchWindow().getActivePage();
if (page != null)
selectionChanged(page.getActivePart(), page.getSelection());
}
}
public void partHidden(IWorkbenchPartReference ref) {
if (ref != null && ref.getId() == getSite().getId())
fProcessSelectionEvents= false;
}
};
/*
* 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;
}
if (fHasWorkingSetFilter)
fWorkingSetFilterActionGroup.saveState(memento);
if (fHasCustomFilter)
fCustomFiltersActionGroup.saveState(memento);
saveSelectionState(memento);
}
private void saveSelectionState(IMemento memento) {
Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray();
if (elements.length > 0) {
IMemento selectionMem= memento.createChild(TAG_SELECTED_ELEMENTS);
for (int i= 0; i < elements.length; i++) {
IMemento elementMem= selectionMem.createChild(TAG_SELECTED_ELEMENT);
Object o= elements[i];
if (o instanceof IJavaElement)
elementMem.putString(TAG_SELECTED_ELEMENT_PATH, ((IJavaElement) elements[i]).getHandleIdentifier());
else if (o instanceof LogicalPackage) {
IPackageFragment[] packages=((LogicalPackage)o).getFragments();
for (int j= 0; j < packages.length; j++) {
IMemento packageMem= elementMem.createChild(TAG_LOGICAL_PACKAGE);
packageMem.putString(TAG_SELECTED_ELEMENT_PATH, packages[j].getHandleIdentifier());
}
}
}
}
}
protected void restoreState(IMemento memento) {
if (fHasWorkingSetFilter)
fWorkingSetFilterActionGroup.restoreState(memento);
if (fHasCustomFilter)
fCustomFiltersActionGroup.restoreState(memento);
if (fHasCustomFilter || fHasWorkingSetFilter) {
fViewer.getControl().setRedraw(false);
fViewer.refresh();
fViewer.getControl().setRedraw(true);
}
}
private ISelection restoreSelectionState(IMemento memento) {
if (memento == null)
return null;
IMemento childMem;
childMem= memento.getChild(TAG_SELECTED_ELEMENTS);
if (childMem != null) {
ArrayList list= new ArrayList();
IMemento[] elementMem= childMem.getChildren(TAG_SELECTED_ELEMENT);
for (int i= 0; i < elementMem.length; i++) {
String javaElementHandle= elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH);
if (javaElementHandle == null) {
// logical package
IMemento[] packagesMem= elementMem[i].getChildren(TAG_LOGICAL_PACKAGE);
LogicalPackage lp= null;
for (int j= 0; j < packagesMem.length; j++) {
javaElementHandle= packagesMem[j].getString(TAG_SELECTED_ELEMENT_PATH);
Object pack= (IPackageFragment)JavaCore.create(javaElementHandle);
if (pack instanceof IPackageFragment && ((IPackageFragment)pack).exists()) {
if (lp == null)
lp= new LogicalPackage((IPackageFragment)pack);
else
lp.add((IPackageFragment)pack);
}
}
if (lp != null)
list.add(lp);
} else {
IJavaElement element= JavaCore.create(javaElementHandle);
if (element != null && element.exists())
list.add(element);
}
}
return new StructuredSelection(list);
}
return null;
}
/**
* Creates the search list inner viewer.
*/
public void createPartControl(Composite parent) {
Assert.isTrue(fViewer == null);
fTypeComparator= new JavaElementTypeComparator();
// Setup viewer
fViewer= createViewer(parent);
fLabelProvider= createLabelProvider();
fViewer.setLabelProvider(createDecoratingLabelProvider(fLabelProvider));
fViewer.setSorter(createJavaElementSorter());
fViewer.setUseHashlookup(true);
fTitleProvider= createTitleProvider();
createContextMenu();
getSite().setSelectionProvider(fViewer);
createActions(); // call before registering for selection changes
addKeyListener();
if (fMemento != null)
restoreState(fMemento);
getSite().setSelectionProvider(fViewer);
// Status line
IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager();
fViewer.addSelectionChangedListener(createStatusBarUpdater(slManager));
hookViewerListeners();
// Filters
addFilters();
// Initialize viewer input
fViewer.setContentProvider(createContentProvider());
setInitialInput();
initDragAndDrop();
// Initialize selecton
setInitialSelection();
fMemento= null;
// Listen to workbench window changes
getViewSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(this);
getViewSite().getPage().addPartListener(fPartListener);
fillActionBars(getViewSite().getActionBars());
setHelp();
}
protected DecoratingLabelProvider createDecoratingLabelProvider(JavaUILabelProvider provider) {
// XXX: Work in progress for problem decorator being a workbench decorator//
// return new ExcludingDecoratingLabelProvider(provider, decorationMgr, "org.eclipse.jdt.ui.problem.decorator"); //$NON-NLS-1$
return new DecoratingJavaLabelProvider(provider);
}
protected JavaElementSorter createJavaElementSorter() {
return new JavaElementSorter();
}
protected StatusBarUpdater createStatusBarUpdater(IStatusLineManager slManager) {
return new StatusBarUpdater(slManager);
}
protected void createContextMenu() {
MenuManager menuManager= new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuManager.setRemoveAllWhenShown(true);
menuManager.addMenuListener(this);
Menu contextMenu= menuManager.createContextMenu(fViewer.getControl());
fViewer.getControl().setMenu(contextMenu);
getSite().registerContextMenu(menuManager, fViewer);
}
protected void initDragAndDrop() {
int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK;
Transfer[] transfers= new Transfer[] {
LocalSelectionTransfer.getInstance(),
ResourceTransfer.getInstance()};
// Drop Adapter
TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] {
new SelectionTransferDropAdapter(fViewer)
};
fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners));
// Drag Adapter
Control control= fViewer.getControl();
TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] {
new SelectionTransferDragAdapter(fViewer),
new ResourceTransferDragAdapter(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) {
public void dragStart(DragSourceEvent event) {
IStructuredSelection selection= (IStructuredSelection)getSelectionProvider().getSelection();
for (Iterator iter= selection.iterator(); iter.hasNext(); ) {
if (iter.next() instanceof IMember) {
setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)});
break;
}
}
super.dragStart(event);
}
});
}
protected void fillActionBars(IActionBars actionBars) {
IToolBarManager toolBar= actionBars.getToolBarManager();
fillToolBar(toolBar);
if (fHasWorkingSetFilter)
fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars());
actionBars.updateActionBars();
fActionGroups.fillActionBars(actionBars);
if (fHasCustomFilter)
fCustomFiltersActionGroup.fillActionBars(actionBars);
}
//---- IWorkbenchPart ------------------------------------------------------
public void setFocus() {
fViewer.getControl().setFocus();
}
public void dispose() {
if (fViewer != null) {
getViewSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this);
getViewSite().getPage().removePartListener(fPartListener);
fViewer= null;
}
if (fActionGroups != null)
fActionGroups.dispose();
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;
IAction action;
if (key == SWT.F5) {
action= fBuildActionGroup.getRefreshAction();
if (action.isEnabled())
action.run();
} if (event.character == SWT.DEL) {
action= fCCPActionGroup.getDeleteAction();
if (action.isEnabled())
action.run();
}
}
//---- Adding Action to Toolbar -------------------------------------------
protected void fillToolBar(IToolBarManager tbm) {
}
/**
* 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();
int size= selection.size();
Object element= selection.getFirstElement();
if (size == 1)
addOpenNewWindowAction(menu, element);
fActionGroups.setContext(new ActionContext(selection));
fActionGroups.fillContextMenu(menu);
fActionGroups.setContext(null);
}
private void addOpenNewWindowAction(IMenuManager menu, Object element) {
if (element instanceof IJavaElement) {
element= ((IJavaElement)element).getResource();
}
if (!(element instanceof IContainer))
return;
menu.appendToGroup(
IContextMenuConstants.GROUP_OPEN,
new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element));
}
protected void createActions() {
fActionGroups= new CompositeActionGroup(new ActionGroup[] {
new NewWizardsActionGroup(this.getSite()),
fOpenEditorGroup= new OpenEditorActionGroup(this),
new OpenViewActionGroup(this),
fCCPActionGroup= new CCPActionGroup(this),
new RefactorActionGroup(this),
new ImportActionGroup(this),
new GenerateActionGroup(this),
fBuildActionGroup= new BuildActionGroup(this),
new JavaSearchActionGroup(this)});
if (fHasWorkingSetFilter) {
String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$
Assert.isNotNull(viewId);
IPropertyChangeListener titleUpdater= new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
String property= event.getProperty();
if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property))
updateTitle();
}
};
fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(fViewer, viewId, getShell(), titleUpdater);
}
// Custom filter group
if (fHasCustomFilter)
fCustomFiltersActionGroup= new CustomFiltersActionGroup(this, fViewer);
}
/**
* Returns the shell to use for opening dialogs.
* Used in this class, and in the actions.
*/
Shell getShell() {
return fViewer.getControl().getShell();
}
protected final Display getDisplay() {
return fViewer.getControl().getDisplay();
}
/**
* Returns the selection provider.
*/
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;
if((newInput instanceof List) && (part instanceof PackagesView))
return true;
else
return false;
}
private boolean isInputResetBy(IWorkbenchPart part) {
if (!(part instanceof JavaBrowsingPart))
return true;
Object thisInput= getViewer().getInput();
Object partInput= ((JavaBrowsingPart)part).getViewer().getInput();
if(thisInput instanceof Collection)
thisInput= ((Collection)thisInput).iterator().next();
if(partInput instanceof Collection)
partInput= ((Collection)partInput).iterator().next();
if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement)
return getTypeComparator().compare(partInput, thisInput) > 0;
else
return true;
}
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;
}
private boolean isSearchResultView(IWorkbenchPart part) {
return SearchUtil.isSearchPlugInActivated() && (part instanceof ISearchResultView);
}
protected boolean needsToProcessSelectionChanged(IWorkbenchPart part, ISelection selection) {
if (!fProcessSelectionEvents || part == this || isSearchResultView(part) || !(selection instanceof IStructuredSelection)){
if (part == this)
fPreviousSelectionProvider= part;
return false;
}
return true;
}
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
if (!needsToProcessSelectionChanged(part, selection))
return;
// Set selection
Object selectedElement= getSingleElementFromSelection(selection);
if (selectedElement != null && (part == null || part.equals(fPreviousSelectionProvider)) && selectedElement.equals(fPreviousSelectedElement))
return;
fPreviousSelectedElement= selectedElement;
Object currentInput= getViewer().getInput();
if (selectedElement != null && selectedElement.equals(currentInput)) {
IJavaElement elementToSelect= findElementToSelect(selectedElement);
if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0)
setSelection(new StructuredSelection(elementToSelect), true);
else if (elementToSelect == null && (this instanceof MembersView)) {
setSelection(StructuredSelection.EMPTY, true);
fPreviousSelectedElement= StructuredSelection.EMPTY;
}
fPreviousSelectionProvider= part;
return;
}
// Clear input if needed
if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) {
if (!isAncestorOf(selectedElement, currentInput))
setInput(null);
fPreviousSelectionProvider= part;
return;
} else if (selection.isEmpty() && !isInputResetBy(part)) {
fPreviousSelectionProvider= part;
return;
} else if (selectedElement == null && part == fPreviousSelectionProvider) {
setInput(null);
fPreviousSelectionProvider= part;
return;
}
fPreviousSelectionProvider= part;
// Adjust input and set selection and
adjustInputAndSetSelection(selectedElement);
}
void setHasWorkingSetFilter(boolean state) {
fHasWorkingSetFilter= state;
}
void setHasCustomSetFilter(boolean state) {
fHasCustomFilter= state;
}
protected Object getInput() {
return fViewer.getInput();
}
protected void setInput(Object input) {
setViewerInput(input);
updateTitle();
}
private void setViewerInput(Object input) {
fProcessSelectionEvents= false;
fViewer.setInput(input);
fProcessSelectionEvents= true;
}
void updateTitle() {
setTitleToolTip(getToolTipText(fViewer.getInput()));
}
/**
* Returns the tool tip text for the given element.
*/
String getToolTipText(Object element) {
String result;
if (!(element instanceof IResource)) {
result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS);
} else {
IPath path= ((IResource) element).getFullPath();
if (path.isRoot()) {
result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$
} else {
result= path.makeRelative().toString();
}
}
if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null)
return result;
IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet();
String wsstr= JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$
if (result.length() == 0)
return wsstr;
return JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$
}
public String getTitleToolTip() {
if (fViewer == null)
return super.getTitleToolTip();
return getToolTipText(fViewer.getInput());
}
protected final StructuredViewer getViewer() {
return fViewer;
}
protected final void setViewer(StructuredViewer viewer){
fViewer= viewer;
}
protected JavaUILabelProvider createLabelProvider() {
return new AppearanceAwareLabelProvider(
AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS,
AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS
);
}
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.MULTI);
}
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 IContentProvider createContentProvider() {
return new JavaBrowsingContentProvider(true, this);
}
protected void setInitialInput() {
// Use the selection, if any
ISelection selection= getSite().getPage().getSelection();
Object input= getSingleElementFromSelection(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((IJavaElement)input));
}
protected void setInitialSelection() {
// Use the selection, if any
Object input;
IWorkbenchPage page= getSite().getPage();
ISelection selection= null;
if (page != null)
selection= page.getSelection();
if (selection instanceof ITextSelection) {
Object part= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
if (part instanceof IEditorPart) {
setSelectionFromEditor((IEditorPart)part);
if (fViewer.getSelection() != null)
return;
}
}
// Use saved selection from memento
if (selection == null || selection.isEmpty())
selection= restoreSelectionState(fMemento);
if (selection == null || selection.isEmpty()) {
// Use the input of the page
input= getSite().getPage().getInput();
if (!(input instanceof IJavaElement)) {
if (input instanceof IAdaptable)
input= ((IAdaptable)input).getAdapter(IJavaElement.class);
else
return;
}
selection= new StructuredSelection(input);
}
selectionChanged(null, selection);
}
protected final 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.
* This method can be overridden but should
* call super.
*/
protected void hookViewerListeners() {
fViewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
if (!fProcessSelectionEvents)
return;
fPreviousSelectedElement= getSingleElementFromSelection(event.getSelection());
IWorkbenchPage page= getSite().getPage();
if (page == null)
return;
if (page.equals(JavaPlugin.getActivePage()) && JavaBrowsingPart.this.equals(page.getActivePart())) {
linkToEditor((IStructuredSelection)event.getSelection());
}
}
});
fViewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
IAction open= fOpenEditorGroup.getOpenAction();
if (open.isEnabled()) {
open.run();
restoreSelection();
}
}
});
}
void restoreSelection() {
// Default is to do nothing
}
void adjustInputAndSetSelection(Object o) {
if (!(o instanceof IJavaElement)) {
setSelection(StructuredSelection.EMPTY, true);
return;
};
IJavaElement je= (IJavaElement)o;
IJavaElement elementToSelect= getSuitableJavaElement(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(newInput);
// Recompute suitable element since it depends on the viewer's input
elementToSelect= getSuitableJavaElement(elementToSelect);
}
if (elementToSelect != null && elementToSelect.exists())
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 || !je.exists())
return null;
if (isValidInput(je))
return je;
return findInputForJavaElement(je.getParent());
}
protected final 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);
protected final Object getSingleElementFromSelection(ISelection selection) {
if (!(selection instanceof StructuredSelection) || selection.isEmpty())
return null;
Iterator iter= ((StructuredSelection)selection).iterator();
Object firstElement= iter.next();
if (!(firstElement instanceof IJavaElement)) {
if (SearchUtil.isISearchResultViewEntry(firstElement)) {
IJavaElement je= SearchUtil.getJavaElement(firstElement);
if (je != null)
return je;
firstElement= SearchUtil.getResource(firstElement);
}
if (firstElement instanceof IAdaptable) {
IJavaElement je= (IJavaElement)((IAdaptable)firstElement).getAdapter(IJavaElement.class);
if (je == null && firstElement instanceof IFile) {
IContainer parent= ((IFile)firstElement).getParent();
if (parent != null)
return (IJavaElement)parent.getAdapter(IJavaElement.class);
else return null;
} else
return je;
} else
return firstElement;
}
Object currentInput= getViewer().getInput();
if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement)))
if (iter.hasNext())
// multi selection and view is empty
return null;
else
// ok: single selection and view is empty
return firstElement;
// be nice to multi selection
while (iter.hasNext()) {
Object element= iter.next();
if (!(element instanceof IJavaElement))
return null;
if (!currentInput.equals(findInputForJavaElement((IJavaElement)element)))
return null;
}
return firstElement;
}
/**
* Gets the typeComparator.
* @return Returns a JavaElementTypeComparator
*/
protected Comparator getTypeComparator() {
return fTypeComparator;
}
/**
* Links to editor (if option enabled)
*/
private void linkToEditor(IStructuredSelection selection) {
Object obj= selection.getFirstElement();
if (selection.size() == 1) {
IEditorPart part= EditorUtility.isOpenInEditor(obj);
if (part != null) {
IWorkbenchPage page= getSite().getPage();
page.bringToTop(part);
if (obj instanceof IJavaElement)
EditorUtility.revealInEditor(part, (IJavaElement) obj);
}
}
}
private void setSelectionFromEditor(IWorkbenchPartReference ref) {
IWorkbenchPart part= ref.getPart(false);
setSelectionFromEditor(part);
}
void setSelectionFromEditor(IWorkbenchPart part) {
if (!linkBrowsingViewSelectionToEditor())
return;
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) {
IJavaElement element= null;
if (selection instanceof IStructuredSelection) {
Object obj= getSingleElementFromSelection(selection);
if (obj instanceof IJavaElement)
element= (IJavaElement)obj;
}
IEditorInput ei= ((IEditorPart)part).getEditorInput();
if (selection instanceof ITextSelection) {
int offset= ((ITextSelection)selection).getOffset();
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) {
IContainer container= ((IFileEditorInput)ei).getFile().getParent();
if (container != null)
je= (IJavaElement)container.getAdapter(IJavaElement.class);
}
if (je == null) {
setSelection(null, false);
return;
}
adjustInputAndSetSelection(je);
} else if (ei instanceof IClassFileEditorInput) {
IClassFile cf= ((IClassFileEditorInput)ei).getClassFile();
adjustInputAndSetSelection(cf);
}
}
}
/**
* 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;
}
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 ((ICompilationUnit)input).findSharedWorkingCopy(JavaUI.getBufferFactory());
else
return EditorUtility.getWorkingCopy(input, false);
} 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
*/
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 (isInputAWorkingCopy()) {
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;
}
}
boolean isInputAWorkingCopy() {
return ((StandardJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy();
}
/**
* @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)
try {
unit.reconcile();
return unit.getElementAt(offset);
} catch (JavaModelException ex) {
}
return null;
}
protected IType getTypeForCU(ICompilationUnit cu) {
cu= (ICompilationUnit)getSuitableJavaElement(cu);
// Use primary type if possible
IType primaryType= cu.findPrimaryType();
if (primaryType != null)
return primaryType;
// Use first top-level type
try {
IType[] types= cu.getTypes();
if (types.length > 0)
return types[0];
else
return null;
} catch (JavaModelException ex) {
return null;
}
}
void setProcessSelectionEvents(boolean state) {
fProcessSelectionEvents= state;
}
/* (non-Javadoc)
* @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput()
*/
public Object getViewPartInput() {
if (fViewer != null) {
return fViewer.getInput();
}
return null;
}
protected void setActionGroups(CompositeActionGroup actionGroups) {
fActionGroups= actionGroups;
}
protected void setBuildActionGroup(BuildActionGroup actionGroup) {
fBuildActionGroup= actionGroup;
}
protected void setCCPActionGroup(CCPActionGroup actionGroup) {
fCCPActionGroup= actionGroup;
}
protected void setCustomFiltersActionGroup(CustomFiltersActionGroup customFiltersActionGroup) {
fCustomFiltersActionGroup= customFiltersActionGroup;
}
protected void setWorkingSetFilterActionGroup(WorkingSetFilterActionGroup workingSetFilterActionGroup) {
fWorkingSetFilterActionGroup= workingSetFilterActionGroup;
}
protected boolean hasCustomFilter() {
return fHasCustomFilter;
}
protected boolean hasWorkingSetFilter() {
return fHasWorkingSetFilter;
}
protected void setOpenEditorGroup(OpenEditorActionGroup fOpenEditorGroup) {
this.fOpenEditorGroup= fOpenEditorGroup;
}
protected OpenEditorActionGroup getOpenEditorGroup() {
return fOpenEditorGroup;
}
protected BuildActionGroup getBuildActionGroup() {
return fBuildActionGroup;
}
protected CCPActionGroup getCCPActionGroup() {
return fCCPActionGroup;
}
private boolean linkBrowsingViewSelectionToEditor() {
return PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_BROWSING_VIEW_TO_EDITOR);
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/AddImportOnSelectionAction.java
|
/**********************************************************************
Copyright (c) 2000, 2002 IBM Corp. and others.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Common Public License v1.0
which accompanies this distribution, and is available at
http://www.eclipse.org/legal/cpl-v10.html
Contributors:
IBM Corporation - Initial implementation
**********************************************************************/
package org.eclipse.jdt.internal.ui.javaeditor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.dialogs.ElementListSelectionDialog;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.texteditor.IUpdate;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IImportDeclaration;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.search.IJavaSearchConstants;
import org.eclipse.jdt.core.search.IJavaSearchScope;
import org.eclipse.jdt.core.search.ITypeNameRequestor;
import org.eclipse.jdt.core.search.SearchEngine;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.internal.corext.codemanipulation.AddImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.corext.util.TypeInfoRequestor;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
public class AddImportOnSelectionAction extends Action implements IUpdate {
private CompilationUnitEditor fEditor;
public AddImportOnSelectionAction(CompilationUnitEditor editor) {
super(JavaEditorMessages.getString("AddImportOnSelection.label")); //$NON-NLS-1$
setToolTipText(JavaEditorMessages.getString("AddImportOnSelection.tooltip")); //$NON-NLS-1$
setDescription(JavaEditorMessages.getString("AddImportOnSelection.description")); //$NON-NLS-1$
fEditor= editor;
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_IMPORT_ON_SELECTION_ACTION);
}
public AddImportOnSelectionAction() {
this(null);
}
public void update() {
setEnabled(fEditor != null);
}
private ICompilationUnit getCompilationUnit () {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
return manager.getWorkingCopy(fEditor.getEditorInput());
}
/*
* @see org.eclipse.jface.action.IAction#run()
*/
public void run() {
ICompilationUnit cu= getCompilationUnit();
if (!ElementValidator.checkValidateEdit(cu, getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"))) //$NON-NLS-1$
return;
if (cu != null) {
ISelection s= fEditor.getSelectionProvider().getSelection();
IDocument doc= fEditor.getDocumentProvider().getDocument(fEditor.getEditorInput());
ITextSelection selection= (ITextSelection) s;
if (doc != null) {
try {
int nameStart= getNameStart(doc, selection.getOffset());
int nameEnd= getNameEnd(doc, selection.getOffset() + selection.getLength());
int len= nameEnd - nameStart;
String name= doc.get(nameStart, len).trim();
String simpleName= Signature.getSimpleName(name);
String containerName= Signature.getQualifier(name);
IImportDeclaration existingImport= JavaModelUtil.findImport(cu, simpleName);
if (existingImport != null) {
if (!existingImport.getElementName().equals(name)) {
getShell().getDisplay().beep();
}
return;
}
IJavaSearchScope searchScope= SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
TypeInfo[] types= findAllTypes(simpleName, searchScope, null);
if (types.length== 0) {
getShell().getDisplay().beep();
return;
}
TypeInfo chosen= selectResult(types, containerName, getShell());
if (chosen == null) {
return;
}
IType type= chosen.resolveType(searchScope);
if (type == null) {
JavaPlugin.logErrorMessage("AddImportOnSelectionAction: Failed to resolve TypeRef: " + chosen.toString()); //$NON-NLS-1$
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), JavaEditorMessages.getString("AddImportOnSelection.error.notresolved.message")); //$NON-NLS-1$ //$NON-NLS-2$
return;
}
removeQualification(doc, nameStart, chosen);
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
AddImportsOperation op= new AddImportsOperation(cu, new IJavaElement[] { type }, settings, false);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
try {
dialog.run(false, true, new WorkbenchRunnableAdapter(op));
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null); //$NON-NLS-1$
} catch (InterruptedException e) {
// Do nothing. Operation has been canceled.
}
return;
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), null); //$NON-NLS-1$
} catch (BadLocationException e) {
JavaPlugin.log(e);
MessageDialog.openError(getShell(), JavaEditorMessages.getString("AddImportOnSelection.error.title"), e.getMessage()); //$NON-NLS-1$
}
}
}
}
private int getNameStart(IDocument doc, int pos) throws BadLocationException {
while (pos > 0) {
char ch= doc.getChar(pos - 1);
if (!Character.isJavaIdentifierPart(ch) && ch != '.') {
return pos;
}
pos--;
}
return pos;
}
private int getNameEnd(IDocument doc, int pos) throws BadLocationException {
if (pos > 0) {
if (Character.isWhitespace(doc.getChar(pos - 1))) {
return pos;
}
}
int len= doc.getLength();
while (pos < len) {
char ch= doc.getChar(pos);
if (!Character.isJavaIdentifierPart(ch)) {
return pos;
}
pos++;
}
return pos;
}
private void removeQualification(IDocument doc, int nameStart, TypeInfo typeInfo) throws BadLocationException {
String containerName= typeInfo.getTypeContainerName();
int containerLen= containerName.length();
int docLen= doc.getLength();
if ((containerLen > 0) && (nameStart + containerLen + 1 < docLen)) {
for (int k= 0; k < containerLen; k++) {
if (doc.getChar(nameStart + k) != containerName.charAt(k)) {
return;
}
}
if (doc.getChar(nameStart + containerLen) == '.') {
doc.replace(nameStart, containerLen + 1, ""); //$NON-NLS-1$
}
}
}
/**
* Finds a type by the simple name.
*/
private static TypeInfo[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, IProgressMonitor monitor) throws CoreException {
SearchEngine searchEngine= new SearchEngine();
ArrayList typeRefsFound= new ArrayList(10);
ITypeNameRequestor requestor= new TypeInfoRequestor(typeRefsFound);
searchEngine.searchAllTypeNames(
JavaPlugin.getWorkspace(),
null,
simpleTypeName.toCharArray(),
IJavaSearchConstants.EXACT_MATCH,
IJavaSearchConstants.CASE_SENSITIVE,
IJavaSearchConstants.TYPE,
searchScope,
requestor,
IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
monitor);
return (TypeInfo[]) typeRefsFound.toArray(new TypeInfo[typeRefsFound.size()]);
}
private Shell getShell() {
return fEditor.getSite().getShell();
}
private TypeInfo selectResult(TypeInfo[] results, String containerName, Shell shell) {
int nResults= results.length;
if (nResults == 0) {
return null;
} else if (nResults == 1) {
return results[0];
}
if (containerName.length() != 0) {
for (int i= 0; i < nResults; i++) {
TypeInfo curr= (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() == ElementListSelectionDialog.OK) {
return (TypeInfo) dialog.getFirstResult();
}
return null;
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddDelegateMethodsAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* Martin Moebius
* *****************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure;
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility;
import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableContext;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
/**
* Creates delegate methods for a type's fields. Opens a dialog with a list of
* fields for which delegate methods can be generated. User is able to check or
* uncheck items before methods are generated.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IField</code> or <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class AddDelegateMethodsAction extends SelectionDispatchAction {
private static boolean fgReplaceFlag = false;
private static boolean fgOverrideFinalsFlag = false;
private static final String DIALOG_TITLE = ActionMessages.getString("AddDelegateMethodsAction.error.title"); //$NON-NLS-1$
private CompilationUnitEditor fEditor;
/**
* Creates a new <code>AddDelegateMethodsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddDelegateMethodsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddDelegateMethodsAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddDelegateMethodsAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddDelegateMethodsAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_DELEGATE_METHODS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddDelegateMethodsAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor = editor;
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
try {
IField[] selectedFields = getSelectedFields(selection);
if (canEnableOn(selectedFields)) {
run(selectedFields[0].getDeclaringType(), selectedFields, false);
return;
}
Object firstElement = selection.getFirstElement();
if (firstElement instanceof IType)
run((IType) firstElement, new IField[0], false);
else if (firstElement instanceof ICompilationUnit)
run(JavaElementUtil.getMainType((ICompilationUnit) firstElement), new IField[0], false);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
if (canEnableOn(getSelectedFields(selection)))
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType))
return canEnableOn((IType) selection.getFirstElement());
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return canEnableOn(JavaElementUtil.getMainType((ICompilationUnit) selection.getFirstElement()));
return false;
}
private static boolean canEnableOn(IType type) throws JavaModelException {
if (type == null || type.getCompilationUnit() == null)
return false;
return canEnableOn(type.getFields());
}
private static boolean canEnableOn(IField[] fields) throws JavaModelException {
if (fields == null) {
return false;
}
int count = 0;
for (int i = 0; i < fields.length; i++) {
if (!hasPrimitiveType(fields[i])) {
count++;
}
}
return (count > 0);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements = selection.toList();
int nElements = elements.size();
if (nElements > 0) {
IField[] res = new IField[nElements];
ICompilationUnit cu = null;
for (int i = 0; i < nElements; i++) {
Object curr = elements.get(i);
if (curr instanceof IField) {
IField fld = (IField) curr;
if (i == 0) {
// remember the cu of the first element
cu = fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no delegates for fields in interfaces or fields with
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i] = fld;
} else {
return null;
}
}
return res;
}
return null;
}
private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
if (!ElementValidator.check(type, getShell(), DIALOG_TITLE, editor))
return;
showUI(type, preselected);
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
try {
IJavaElement[] elements = SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field = (IField) elements[0];
run(field.getDeclaringType(), new IField[] { field }, true);
return;
}
IJavaElement element = SelectionConverter.getElementAtOffset(fEditor);
if (element != null) {
IType type = (IType) element.getAncestor(IJavaElement.TYPE);
if (type != null) {
if (type.getFields().length > 0) {
run(type, new IField[0], true);
return;
}
}
}
MessageDialog.openInformation(getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
}
}
//---- Helpers -------------------------------------------------------------------
/**build ui */
private void showUI(IType type, IField[] preselected) {
try {
FieldContentProvider provider = new FieldContentProvider(type);
Methods2FieldLabelProvider methodLabel = new Methods2FieldLabelProvider();
CheckedTreeSelectionDialog dialog = new CheckedTreeSelectionDialog(getShell(), methodLabel, provider);
dialog.setValidator(new ISelectionStatusValidator() {
public IStatus validate(Object[] selection) {
StatusInfo state = new StatusInfo();
if (selection != null && selection.length > 0) {
HashSet map = new HashSet(selection.length);
int count = 0;
for (int i = 0; i < selection.length; i++) {
Object key = selection[i];
if (selection[i] instanceof Methods2Field) {
count++;
try {
key = createSignatureKey(((Methods2Field) selection[i]).fMethod);
} catch (JavaModelException e) {
return new StatusInfo(StatusInfo.ERROR, e.toString());
}
}
if (!map.add(key)) { //$NON-NLS-1$
state = new StatusInfo(IStatus.ERROR, ActionMessages.getString("AddDelegateMethodsAction.duplicate_methods")); //$NON-NLS-1$
break;
} else {
String message;
if (count == 1) {
message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.one", String.valueOf(count)); //$NON-NLS-1$
} else {
message = ActionMessages.getFormattedString("AddDelegateMethodsAction.selectioninfo.more", String.valueOf(count)); //$NON-NLS-1$
}
state = new StatusInfo(IStatus.INFO, message);
}
}
}
return state;
}
});
dialog.setSorter(new Methods2FieldSorter());
dialog.setInput(provider);
dialog.setContainerMode(true);
dialog.setMessage(ActionMessages.getString("AddDelegateMethodsAction.message")); //$NON-NLS-1$
dialog.setTitle(ActionMessages.getString("AddDelegateMethodsAction.title")); //$NON-NLS-1$
dialog.setExpandedElements(preselected);
int result = dialog.open();
if (result == Window.OK) {
Object[] o = dialog.getResult();
if (o == null)
return;
ArrayList methods = new ArrayList(o.length);
for (int i = 0; i < o.length; i++) {
if (o[i] instanceof Methods2Field)
methods.add(o[i]);
}
IEditorPart part = EditorUtility.openInEditor(type);
type = (IType) JavaModelUtil.toWorkingCopy(type);
IMethod[] createdMethods = processResults(methods, type);
if (createdMethods != null && createdMethods.length > 0) {
EditorUtility.revealInEditor(part, createdMethods[0]);
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, DIALOG_TITLE, ActionMessages.getString("AddDelegateMethodsAction.error.actionfailed")); //$NON-NLS-1$
}
}
/**Runnable for the operation*/
private static class ResultRunner implements IWorkspaceRunnable {
/**List with Methods2Field*/
List fList = null;
/**Type to add methods to*/
IType fType = null;
ArrayList fCreatedMethods;
public ResultRunner(List resultList, IType type) {
fList = resultList;
fType = type;
fCreatedMethods = new ArrayList();
}
public IMethod[] getCreatedMethods() {
return (IMethod[]) fCreatedMethods.toArray(new IMethod[fCreatedMethods.size()]);
}
public void run(IProgressMonitor monitor) throws CoreException {
String message = ActionMessages.getFormattedString("AddDelegateMethodsAction.monitor.message", String.valueOf(fList.size())); //$NON-NLS-1$
monitor.beginTask(message, fList.size());
// the preferences
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings();
boolean addComments = settings.createComments;
// already existing methods
IMethod[] existingMethods = fType.getMethods();
//the delemiter used
String lineDelim = StubUtility.getLineDelimiterUsed(fType);
// the indent used + 1
int indent = StubUtility.getIndentUsed(fType) + 1;
// perhaps we have to add import statements
final ImportsStructure imports =
new ImportsStructure(fType.getCompilationUnit(), settings.importOrder, settings.importThreshold, true);
for (int i = 0; i < fList.size(); i++) {
//long time=System.currentTimeMillis();
//check for cancel each iteration
if (monitor.isCanceled()) {
if (i > 0) {
imports.create(false, null);
}
return;
}
ITypeHierarchy typeHierarchy = fType.newSupertypeHierarchy(null);
String content = null;
Methods2Field wrapper = (Methods2Field) fList.get(i);
IMethod curr = wrapper.fMethod;
IField field = wrapper.fField;
IMethod overwrittenMethod =
JavaModelUtil.findMethodImplementationInHierarchy(
typeHierarchy,
fType,
curr.getElementName(),
curr.getParameterTypes(),
curr.isConstructor());
if (overwrittenMethod == null) {
content = createStub(field, curr, addComments, overwrittenMethod, imports);
} else {
int flags = overwrittenMethod.getFlags();
if (Flags.isFinal(flags) || Flags.isPrivate(flags)) {
// we could ask before overwriting final methods
if (fgOverrideFinalsFlag) {
System.out.println("method final"); //$NON-NLS-1$
System.out.println(overwrittenMethod);
}
}
IMethod declaration =
JavaModelUtil.findMethodDeclarationInHierarchy(
typeHierarchy,
fType,
curr.getElementName(),
curr.getParameterTypes(),
curr.isConstructor());
content = createStub(field, declaration, addComments, overwrittenMethod, imports);
}
IJavaElement sibling = null;
IMethod existing =
JavaModelUtil.findMethod(
curr.getElementName(),
curr.getParameterTypes(),
curr.isConstructor(),
existingMethods);
if (existing != null) {
// we could ask before replacing a method
if (fgReplaceFlag) {
System.out.println("method does already exists"); //$NON-NLS-1$
System.out.println(existing);
sibling = StubUtility.findNextSibling(existing);
existing.delete(false, null);
} else {
continue;
}
} else if (curr.isConstructor() && existingMethods.length > 0) {
// add constructors at the beginning
sibling = existingMethods[0];
}
String formattedContent = StubUtility.codeFormat(content, indent, lineDelim) + lineDelim;
IMethod created = fType.createMethod(formattedContent, sibling, true, null);
fCreatedMethods.add(created);
monitor.worked(1);
//System.out.println(System.currentTimeMillis()-time +" for #"+i);
}
imports.create(false, null);
}
private String createStub(
IField field,
IMethod curr,
boolean addComment,
IMethod overridden,
IImportsStructure imports)
throws CoreException {
String methodName = curr.getElementName();
String[] paramNames = curr.getParameterNames();
String returnTypSig = curr.getReturnType();
StringBuffer buf = new StringBuffer();
if (addComment) {
String comment =
StubUtility.getMethodComment(
fType.getCompilationUnit(),
fType.getElementName(),
methodName,
paramNames,
curr.getExceptionTypes(),
returnTypSig,
overridden);
if (comment != null) {
buf.append(comment);
}
}
String methodDeclaration = null;
if (fType.isClass()) {
StringBuffer body = new StringBuffer();
if (!Signature.SIG_VOID.equals(returnTypSig)) {
body.append("return "); //$NON-NLS-1$
}
if (JdtFlags.isStatic(curr)) {
body.append(resolveTypeOfField(field).getElementName());
} else {
body.append(field.getElementName());
}
body.append('.').append(methodName).append('(');
for (int i = 0; i < paramNames.length; i++) {
body.append(paramNames[i]);
if (i < paramNames.length - 1)
body.append(',');
}
body.append(");"); //$NON-NLS-1$
methodDeclaration = body.toString();
}
StubUtility.genMethodDeclaration(fType.getElementName(), curr, methodDeclaration, imports, buf);
return buf.toString();
}
}
/**creates methods in class*/
private IMethod[] processResults(List list, IType type) throws InvocationTargetException {
if (list.size() == 0)
return null;
ResultRunner resultRunner = new ResultRunner(list, type);
IRunnableContext runnableContext = new ProgressMonitorDialog(getShell());
try {
runnableContext.run(false, true, new WorkbenchRunnableAdapter(resultRunner));
} catch (InterruptedException e) {
// cancel pressed
return null;
}
return resultRunner.getCreatedMethods();
}
/** The model (content provider) for the field-methods tree */
private static class FieldContentProvider implements ITreeContentProvider {
private TreeMap fTreeMap = null;
private HashMap fFieldMap = null;
private HashMap fFilter = null;
/**
* Method FieldContentProvider.
* @param type outer type to insert in (hide final methods in tree))
*/
FieldContentProvider(IType type) throws JavaModelException {
//hiding final methods
fFilter = new HashMap();
//mapping name to methods
fTreeMap = new TreeMap();
//mapping name to field
fFieldMap = new HashMap();
buildModel(type);
}
private void buildModel(IType type) throws JavaModelException {
IField[] fields = type.getFields();
//build map to filter against
IMethod[] finMeths = resolveFinalMethods(type);
for (int i = 0; i < finMeths.length; i++) {
fFilter.put(createSignatureKey(finMeths[i]), finMeths[i]);
}
IMethod[] filter = type.getMethods();
for (int i = 0; i < filter.length; i++) {
fFilter.put(createSignatureKey(filter[i]), filter[i]);
}
for (int i = 0; i < fields.length; i++) {
IType fieldType = resolveTypeOfField(fields[i]);
if (fieldType == null)
continue;
IMethod[] methods = resolveMethodsHierarchy(fieldType);
ArrayList accessMethods = new ArrayList();
//show public methods; hide constructors + final methods
for (int j = 0; j < methods.length; j++) {
boolean publicField = Flags.isPublic(methods[j].getFlags());
boolean constructor = methods[j].isConstructor();
boolean finalExist = fFilter.get(createSignatureKey(methods[j])) != null;
if (publicField && !constructor && !finalExist)
accessMethods.add(new Methods2Field(methods[j], fields[i]));
}
Object[] m = accessMethods.toArray();
Methods2Field[] mf = new Methods2Field[m.length];
for (int j = 0; j < m.length; j++) {
mf[j] = (Methods2Field) m[j];
}
fTreeMap.put(fields[i].getElementName(), mf);
fFieldMap.put(fields[i].getElementName(), fields[i]);
}
}
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IField) {
return (Object[]) fTreeMap.get(((IField) parentElement).getElementName());
}
return null;
}
public Object getParent(Object element) {
return null;
}
public boolean hasChildren(Object element) {
return element instanceof IField ? true : false;
}
public Object[] getElements(Object inputElement) {
if ((inputElement != null) && (inputElement instanceof FieldContentProvider)) {
Set set = fTreeMap.keySet();
Object[] o = set.toArray();
Object[] fields = new Object[o.length];
for (int i = 0; i < o.length; i++) {
fields[i] = fFieldMap.get(o[i]);
}
return fields;
}
return null;
}
public void dispose() {
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
/**to map from dialog results to corresponding fields*/
private static class Methods2Field {
public Methods2Field(IMethod method, IField field) {
fMethod = method;
fField = field;
}
/**method to wrap*/
IMethod fMethod = null;
/**field where method is declared*/
IField fField = null;
}
/**just to wrap JavaElementLabelProvider using my Methods2Field*/
private static class Methods2FieldLabelProvider implements ILabelProvider {
/**Delegate to forward calls*/
JavaElementLabelProvider fMethodLabel = null;
public Methods2FieldLabelProvider() {
fMethodLabel = new JavaElementLabelProvider();
fMethodLabel.turnOn(JavaElementLabelProvider.SHOW_TYPE);
}
public Image getImage(Object element) {
if (element instanceof Methods2Field) {
Methods2Field wrapper = (Methods2Field) element;
return fMethodLabel.getImage(wrapper.fMethod);
} else if (element instanceof IJavaElement) {
return fMethodLabel.getImage(element);
}
return null;
}
public String getText(Object element) {
if (element instanceof Methods2Field) {
Methods2Field wrapper = (Methods2Field) element;
return fMethodLabel.getText(wrapper.fMethod);
} else if (element instanceof IJavaElement) {
return fMethodLabel.getText(element);
}
return null;
}
public void addListener(ILabelProviderListener listener) {
fMethodLabel.addListener(listener);
}
public void dispose() {
fMethodLabel.dispose();
}
public boolean isLabelProperty(Object element, String property) {
return fMethodLabel.isLabelProperty(element, property);
}
public void removeListener(ILabelProviderListener listener) {
fMethodLabel.removeListener(listener);
}
}
/** and a delegate for the sorter*/
private static class Methods2FieldSorter extends ViewerSorter {
JavaElementSorter fSorter = new JavaElementSorter();
public int category(Object element) {
if (element instanceof Methods2Field)
element = ((Methods2Field) element).fMethod;
return fSorter.category(element);
}
public int compare(Viewer viewer, Object e1, Object e2) {
if (e1 instanceof Methods2Field)
e1 = ((Methods2Field) e1).fMethod;
if (e2 instanceof Methods2Field)
e2 = ((Methods2Field) e2).fMethod;
return fSorter.compare(viewer, e1, e2);
}
public Collator getCollator() {
return fSorter.getCollator();
}
}
/**return all methods of all super types, minus dups*/
private static IMethod[] resolveMethodsHierarchy(IType type) throws JavaModelException {
HashMap map = new HashMap();
ITypeHierarchy hierarchy = type.newSupertypeHierarchy(null);
IType[] types = hierarchy.getAllTypes();
for (int i = 0; i < types.length; i++) {
IMethod[] methods = types[i].getMethods();
for (int j = 0; j < methods.length; j++) {
map.put(createSignatureKey(methods[j]), methods[j]);
}
}
ArrayList list = new ArrayList();
list.addAll(map.values());
IMethod[] methods = new IMethod[list.size()];
for (int i = 0; i < methods.length; i++) {
methods[i] = (IMethod) list.get(i);
}
return methods;
}
/**returns a non null array of final methods of the type*/
private static IMethod[] resolveFinalMethods(IType type) throws JavaModelException {
//Interfaces are java.lang.Objects
if (type.isInterface()) {
type = JavaModelUtil.findType(type.getJavaProject(), "java.lang.Object"); //$NON-NLS-1$
}
IMethod[] methods = resolveMethodsHierarchy(type);
ArrayList list = new ArrayList(methods.length);
for (int i = 0; i < methods.length; i++) {
boolean isFinal = Flags.isFinal(methods[i].getFlags());
if (isFinal)
list.add(methods[i]);
}
IMethod[] finalMethods = new IMethod[list.size()];
for (int i = 0; i < finalMethods.length; i++) {
finalMethods[i] = (IMethod) list.get(i);
}
return finalMethods;
}
/**creates a key used for hashmaps for a method signature (name+arguments(fqn))*/
private static String createSignatureKey(IMethod method) throws JavaModelException {
StringBuffer buffer = new StringBuffer();
buffer.append(method.getElementName());
String[] args = method.getParameterTypes();
for (int i = 0; i < args.length; i++) {
String signature;
if (isUnresolved(args[i])) {
int acount = Signature.getArrayCount(args[i]);
if (acount > 0) {
String arg = args[i];
int index = arg.lastIndexOf(Signature.C_ARRAY);
arg = arg.substring(index + 1);
signature = Signature.toString(arg);
} else {
signature = Signature.toString(args[i]);
}
String[][] fqn = method.getDeclaringType().resolveType(signature);
if (fqn != null) {
buffer.append(fqn[0][0]).append('.').append(fqn[0][1]);
//TODO check for [][]
for (int j = 0; j < acount; j++) {
buffer.append("[]"); //$NON-NLS-1$
}
}
}else{
signature=Signature.toString(args[i]);
buffer.append(signature);
}
}
return buffer.toString();
}
private static boolean isUnresolved(String signature) {
boolean flag = false;
char c=Signature.getElementType(signature).charAt(0);
boolean primitive=(c!= Signature.C_RESOLVED && c != Signature.C_UNRESOLVED);
if(primitive)
return flag;
int acount = Signature.getArrayCount(signature);
if (acount > 0) {
int index = signature.lastIndexOf(Signature.C_ARRAY);
c = signature.charAt(index + 1);
} else {
c = signature.charAt(0);
}
switch (c) {
case Signature.C_RESOLVED :
flag=false;
break;
case Signature.C_UNRESOLVED :
flag=true;
break;
default :
throw new IllegalArgumentException();
}
return flag;
}
private static boolean hasPrimitiveType(IField field) throws JavaModelException {
String signature = field.getTypeSignature();
char first = Signature.getElementType(signature).charAt(0);
return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED);
}
/**
* returns Type of field.
*
* if field is primitve null is returned.
* if field is array java.lang.Object is returned.
**/
private static IType resolveTypeOfField(IField field) throws JavaModelException {
boolean isPrimitive = hasPrimitiveType(field);
boolean isArray = Signature.getArrayCount(field.getTypeSignature()) > 0;
if (!isPrimitive && !isArray) {
String typeName = JavaModelUtil.getResolvedTypeName(field.getTypeSignature(), field.getDeclaringType());
//if the cu has errors its possible no type name is resolved
IType type = typeName != null ? field.getJavaProject().findType(typeName) : null;
return type;
} else if (isArray) {
return JavaModelUtil.findType(field.getJavaProject(), "java.lang.Object"); //$NON-NLS-1$
}
return null;
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
import org.eclipse.jdt.ui.JavaElementLabelProvider;
import org.eclipse.jdt.ui.JavaElementSorter;
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
import org.eclipse.jdt.internal.corext.codemanipulation.IRequestQuery;
import org.eclipse.jdt.internal.corext.refactoring.util.JavaElementUtil;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
/**
* Creates getter and setter methods for a type's fields. Opens a dialog
* with a list of fields for which a setter or getter can be generated.
* User is able to check or uncheck items before setters or getters
* are generated.
* <p>
* Will open the parent compilation unit in a Java editor. The result is
* unsaved, so the user can decide if the changes are acceptable.
* <p>
* The action is applicable to structured selections containing elements
* of type <code>IField</code> or <code>IType</code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class AddGetterSetterAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private static final String dialogTitle= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
/**
* Creates a new <code>AddGetterSetterAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public AddGetterSetterAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("AddGetterSetterAction.label")); //$NON-NLS-1$
setDescription(ActionMessages.getString("AddGetterSetterAction.description")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("AddGetterSetterAction.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.GETTERSETTER_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public AddGetterSetterAction(CompilationUnitEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
//---- Structured Viewer -----------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(IStructuredSelection selection) {
try {
setEnabled(canEnable(selection));
} catch (JavaModelException e) {
// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
if (JavaModelUtil.filterNotPresentException(e))
JavaPlugin.log(e);
setEnabled(false);
}
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(IStructuredSelection selection) {
try {
IField[] selectedFields= getSelectedFields(selection);
if (canEnableOn(selectedFields)){
run(selectedFields[0].getDeclaringType(), selectedFields, false);
return;
}
Object firstElement= selection.getFirstElement();
if (firstElement instanceof IType)
run((IType)firstElement, new IField[0], false);
else if (firstElement instanceof ICompilationUnit)
run(JavaElementUtil.getMainType((ICompilationUnit)firstElement), new IField[0], false);
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean canEnable(IStructuredSelection selection) throws JavaModelException{
if (canEnableOn(getSelectedFields(selection)))
return true;
if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType))
return canEnableOn((IType)selection.getFirstElement());
if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
return canEnableOn(JavaElementUtil.getMainType((ICompilationUnit)selection.getFirstElement()));
return false;
}
private static boolean canEnableOn(IType type) throws JavaModelException {
if (type == null)
return false;
if (type.getFields().length == 0)
return false;
if (type.getCompilationUnit() == null)
return false;
return true;
}
private static boolean canEnableOn(IField[] fields) throws JavaModelException {
return fields != null && fields.length > 0;
}
private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
if (!ElementValidator.check(type, getShell(), dialogTitle, editor))
return;
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
ILabelProvider lp= new AddGetterSetterLabelProvider();
Map entries= createGetterSetterMapping(type, settings);
if (entries.isEmpty()){
MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$
return;
}
ITreeContentProvider cp= new AddGetterSetterContentProvider(entries);
CheckedTreeSelectionDialog dialog= new CheckedTreeSelectionDialog(getShell(), lp, cp);
dialog.setSorter(new JavaElementSorter());
dialog.setTitle(dialogTitle);
String message= ActionMessages.getFormattedString("AddGetterSetterAction.dialog.title", JavaElementUtil.createSignature(type));//$NON-NLS-1$
dialog.setMessage(message);
dialog.setValidator(createValidator());
dialog.setContainerMode(true);
dialog.setSize(60, 18);
dialog.setInput(type);
dialog.setExpandedElements(type.getFields());
dialog.setInitialSelections(preselected);
dialog.open();
Object[] result= dialog.getResult();
if (result == null)
return;
IField[] getterFields= getGetterFields(result);
IField[] setterFields= getSetterFields(result);
generate(getterFields, setterFields);
}
private static ISelectionStatusValidator createValidator() {
return new ISelectionStatusValidator(){
public IStatus validate(Object[] selection) {
int count= countSelectedMethods(selection);
if (count == 0)
return new StatusInfo(IStatus.ERROR, ""); //$NON-NLS-1$
if (count == 1)
return new StatusInfo(IStatus.INFO, ActionMessages.getString("AddGetterSetterAction.one_selected")); //$NON-NLS-1$
String message= ActionMessages.getFormattedString("AddGetterSetterAction.methods_selected", String.valueOf(count));//$NON-NLS-1$
return new StatusInfo(IStatus.INFO, message);
}
};
}
private static int countSelectedMethods(Object[] selection){
int count= 0;
for (int i = 0; i < selection.length; i++) {
if (selection[i] instanceof GetterSetterEntry)
count++;
}
return count;
}
private static IField[] getGetterFields(Object[] result){
Collection list= new ArrayList(0);
for (int i = 0; i < result.length; i++) {
Object each= result[i];
if ((each instanceof GetterSetterEntry)){
GetterSetterEntry entry= (GetterSetterEntry)each;
if (entry.isGetterEntry)
list.add(entry.field);
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private static IField[] getSetterFields(Object[] result){
Collection list= new ArrayList(0);
for (int i = 0; i < result.length; i++) {
Object each= result[i];
if ((each instanceof GetterSetterEntry)){
GetterSetterEntry entry= (GetterSetterEntry)each;
if (! entry.isGetterEntry)
list.add(entry.field);
}
}
return (IField[]) list.toArray(new IField[list.size()]);
}
private void generate(IField[] getterFields, IField[] setterFields) throws CoreException{
if (getterFields.length == 0 && setterFields.length == 0)
return;
ICompilationUnit cu= null;
if (getterFields.length != 0)
cu= getterFields[0].getCompilationUnit();
else
cu= setterFields[0].getCompilationUnit();
//open the editor, forces the creation of a working copy
IEditorPart editor= EditorUtility.openInEditor(cu);
IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields);
IField[] workingCopySetterFields= getWorkingCopyFields(setterFields);
if (workingCopyGetterFields != null && workingCopySetterFields != null)
run(workingCopyGetterFields, workingCopySetterFields, editor);
}
private IField[] getWorkingCopyFields(IField[] fields) throws CoreException{
if (fields.length == 0)
return new IField[0];
ICompilationUnit cu= fields[0].getCompilationUnit();
ICompilationUnit workingCopyCU;
IField[] workingCopyFields;
if (cu.isWorkingCopy()) {
workingCopyCU= cu;
workingCopyFields= fields;
} else {
workingCopyCU= EditorUtility.getWorkingCopy(cu);
if (workingCopyCU == null) {
showError(ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
return null;
}
workingCopyFields= new IField[fields.length];
for (int i= 0; i < fields.length; i++) {
IField field= fields[i];
IField workingCopyField= (IField) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, field);
if (workingCopyField == null) {
showError(ActionMessages.getFormattedString("AddGetterSetterAction.error.fieldNotExisting", field.getElementName())); //$NON-NLS-1$
return null;
}
workingCopyFields[i]= workingCopyField;
}
}
return workingCopyFields;
}
//---- Java Editior --------------------------------------------------------------
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction
*/
protected void run(ITextSelection selection) {
try {
IJavaElement[] elements= SelectionConverter.codeResolve(fEditor);
if (elements.length == 1 && (elements[0] instanceof IField)) {
IField field= (IField)elements[0];
run(field.getDeclaringType(), new IField[] {field}, true);
return;
}
IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
if (element != null){
IType type= (IType)element.getAncestor(IJavaElement.TYPE);
if (type != null){
if (type.getFields().length > 0){
run(type, new IField[0], true);
return;
}
}
}
MessageDialog.openInformation(getShell(), dialogTitle,
ActionMessages.getString("AddGetterSetterAction.not_applicable")); //$NON-NLS-1$
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), dialogTitle, ActionMessages.getString("AddGetterSetterAction.error.actionfailed")); //$NON-NLS-1$
}
}
private boolean checkEnabledEditor() {
return fEditor != null && !fEditor.isEditorInputReadOnly() && SelectionConverter.canOperateOn(fEditor);
}
//---- Helpers -------------------------------------------------------------------
private void run(IField[] getterFields, IField[] setterFields, IEditorPart editor) {
try{
AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields);
new ProgressMonitorDialog(getShell()).run(false, true, new WorkbenchRunnableAdapter(op));
IMethod[] createdMethods= op.getCreatedAccessors();
if (createdMethods.length > 0) {
EditorUtility.revealInEditor(editor, createdMethods[0]);
}
} catch (InvocationTargetException e) {
String message= ActionMessages.getString("AddGetterSetterAction.error.actionfailed"); //$NON-NLS-1$
ExceptionHandler.handle(e, getShell(), dialogTitle, message);
} catch (InterruptedException e) {
// operation cancelled
}
}
private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields) {
IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
IRequestQuery skipReplaceQuery= skipReplaceQuery();
CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
return new AddGetterSetterOperation(getterFields, setterFields, settings, skipSetterForFinalQuery, skipReplaceQuery);
}
private IRequestQuery skipSetterForFinalQuery() {
return new IRequestQuery() {
public int doQuery(IMember field) {
// Fix for http://dev.eclipse.org/bugs/show_bug.cgi?id=19367
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.YES_ALL, IRequestQuery.NO, IRequestQuery.CANCEL};
String[] options= {IDialogConstants.YES_LABEL, IDialogConstants.YES_TO_ALL_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL};
String fieldName= JavaElementLabels.getElementLabel(field, 0);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipSetterForFinalDialog.message", fieldName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private IRequestQuery skipReplaceQuery() {
return new IRequestQuery() {
public int doQuery(IMember method) {
int[] returnCodes= {IRequestQuery.YES, IRequestQuery.NO, IRequestQuery.YES_ALL, IRequestQuery.CANCEL};
String skipLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skip.label"); //$NON-NLS-1$
String replaceLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.replace.label"); //$NON-NLS-1$
String skipAllLabel= ActionMessages.getString("AddGetterSetterAction.SkipExistingDialog.skipAll.label"); //$NON-NLS-1$
String[] options= { skipLabel, replaceLabel, skipAllLabel, IDialogConstants.CANCEL_LABEL};
String methodName= JavaElementLabels.getElementLabel(method, JavaElementLabels.M_PARAMETER_TYPES);
String formattedMessage= ActionMessages.getFormattedString("AddGetterSetterAction.SkipExistingDialog.message", methodName); //$NON-NLS-1$
return showQueryDialog(formattedMessage, options, returnCodes);
}
};
}
private int showQueryDialog(final String message, final String[] buttonLabels, int[] returnCodes) {
final Shell shell= getShell();
if (shell == null) {
JavaPlugin.logErrorMessage("AddGetterSetterAction.showQueryDialog: No active shell found"); //$NON-NLS-1$
return IRequestQuery.CANCEL;
}
final int[] result= { MessageDialog.CANCEL };
shell.getDisplay().syncExec(new Runnable() {
public void run() {
String title= ActionMessages.getString("AddGetterSetterAction.QueryDialog.title"); //$NON-NLS-1$
MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, buttonLabels, 0);
result[0]= dialog.open();
}
});
int returnVal= result[0];
return returnVal < 0 ? IRequestQuery.CANCEL : returnCodes[returnVal];
}
private void showError(String message) {
MessageDialog.openError(getShell(), dialogTitle, message);
}
/*
* Returns fields in the selection or <code>null</code> if the selection is
* empty or not valid.
*/
private IField[] getSelectedFields(IStructuredSelection selection) {
List elements= selection.toList();
int nElements= elements.size();
if (nElements > 0) {
IField[] res= new IField[nElements];
ICompilationUnit cu= null;
for (int i= 0; i < nElements; i++) {
Object curr= elements.get(i);
if (curr instanceof IField) {
IField fld= (IField)curr;
if (i == 0) {
// remember the cu of the first element
cu= fld.getCompilationUnit();
if (cu == null) {
return null;
}
} else if (!cu.equals(fld.getCompilationUnit())) {
// all fields must be in the same CU
return null;
}
try {
if (fld.getDeclaringType().isInterface()) {
// no setters/getters for interfaces
return null;
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
return null;
}
res[i]= fld;
} else {
return null;
}
}
return res;
}
return null;
}
private static class GetterSetterEntry {
public final IField field;
public final boolean isGetterEntry;
GetterSetterEntry(IField field, boolean isGetterEntry){
this.field= field;
this.isGetterEntry= isGetterEntry;
}
}
private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider {
AddGetterSetterLabelProvider() {
}
/*
* @see ILabelProvider#getText(Object)
*/
public String getText(Object element) {
if (element instanceof GetterSetterEntry) {
GetterSetterEntry entry= (GetterSetterEntry) element;
try {
if (entry.isGetterEntry) {
return GetterSetterUtil.getGetterName(entry.field, null) + "()"; //$NON-NLS-1$
} else {
return GetterSetterUtil.getSetterName(entry.field, null) + '(' + Signature.getSimpleName(Signature.toString(entry.field.getTypeSignature())) + ')';
}
} catch (JavaModelException e) {
return ""; //$NON-NLS-1$
}
}
return super.getText(element);
}
/*
* @see ILabelProvider#getImage(Object)
*/
public Image getImage(Object element) {
if (element instanceof GetterSetterEntry) {
int flags= 0;
try {
flags= ((GetterSetterEntry) element).field.getFlags();
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, Flags.AccPublic);
int adornmentFlags= Flags.isStatic(flags) ? JavaElementImageDescriptor.STATIC : 0;
desc= new JavaElementImageDescriptor(desc, adornmentFlags, JavaElementImageProvider.BIG_SIZE);
return JavaPlugin.getImageDescriptorRegistry().get(desc);
}
return super.getImage(element);
}
}
/**
* @return map IField -> GetterSetterEntry[]
*/
private static Map createGetterSetterMapping(IType type, CodeGenerationSettings settings) throws JavaModelException{
IField[] fields= type.getFields();
Map result= new HashMap();
for (int i= 0; i < fields.length; i++) {
List l= new ArrayList(2);
if (GetterSetterUtil.getGetter(fields[i]) == null)
l.add(new GetterSetterEntry(fields[i], true));
if (GetterSetterUtil.getSetter(fields[i]) == null)
l.add(new GetterSetterEntry(fields[i], false));
if (! l.isEmpty())
result.put(fields[i], (GetterSetterEntry[]) l.toArray(new GetterSetterEntry[l.size()]));
}
return result;
}
private static class AddGetterSetterContentProvider implements ITreeContentProvider{
private static final Object[] EMPTY= new Object[0];
private Map fGetterSetterEntries;
public AddGetterSetterContentProvider(Map entries) throws JavaModelException {
fGetterSetterEntries= entries;
}
/*
* @see ITreeContentProvider#getChildren(Object)
*/
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof IField)
return (Object[])fGetterSetterEntries.get(parentElement);
return EMPTY;
}
/*
* @see ITreeContentProvider#getParent(Object)
*/
public Object getParent(Object element) {
if (element instanceof IMember)
return ((IMember)element).getDeclaringType();
if (element instanceof GetterSetterEntry)
return ((GetterSetterEntry)element).field;
return null;
}
/*
* @see ITreeContentProvider#hasChildren(Object)
*/
public boolean hasChildren(Object element) {
return getChildren(element).length > 0;
}
/*
* @see IStructuredContentProvider#getElements(Object)
*/
public Object[] getElements(Object inputElement) {
return fGetterSetterEntries.keySet().toArray();
}
/*
* @see IContentProvider#dispose()
*/
public void dispose() {
fGetterSetterEntries.clear();
fGetterSetterEntries= null;
}
/*
* @see IContentProvider#inputChanged(Viewer, Object, Object)
*/
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/FindOccurrencesInFileAction.java
|
/*******************************************************************************
* Copyright (c) 2003 International Business Machines Corp. and others. All
* rights reserved. This program and the accompanying materials are made
* available under the terms of the Common Public License v0.5 which accompanies
* this distribution, and is available at http://www.eclipse.org/legal/cpl-v05.
* html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.IEditorStatusLine;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
/**
* Action to find all occurrences of a compilation unit member (e.g.
* fields, methods, types, and local variables) in a file.
* <p>
* Action is applicable to selections containing elements of type
* <tt>IMember</tt>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.1
*/
public class FindOccurrencesInFileAction extends SelectionDispatchAction {
private JavaEditor fEditor;
private IActionBars fActionBars;
/**
* Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
* that the selection provided by the view part's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the part providing context information for this action
*/
public FindOccurrencesInFileAction(IViewPart part) {
this(part.getSite());
fActionBars= part.getViewSite().getActionBars();
}
/**
* Creates a new <code>FindOccurrencesInFileAction</code>. The action requires
* that the selection provided by the page's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page providing context information for this action
*/
public FindOccurrencesInFileAction(Page page) {
this(page.getSite());
fActionBars= page.getSite().getActionBars();
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public FindOccurrencesInFileAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
private FindOccurrencesInFileAction(IWorkbenchSite site) {
super(site);
setText(SearchMessages.getString("Search.FindOccurrencesInFile.label")); //$NON-NLS-1$
setToolTipText(SearchMessages.getString("Search.FindOccurrencesInFile.tooltip")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.FIND_OCCURRENCES_IN_FILE_ACTION);
}
//---- Structured Selection -------------------------------------------------------------
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(getMember(selection) != null);
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
private IMember getMember(IStructuredSelection selection) {
if (selection.size() != 1)
return null;
Object o= selection.getFirstElement();
if (o instanceof IMember) {
IMember member= (IMember)o;
IClassFile file= member.getClassFile();
if (file != null) {
try {
if (file.getSourceRange() != null)
return member;
} catch (JavaModelException e) {
return null;
}
}
return member;
}
return null;
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
IMember member= getMember(selection);
if (!ActionUtil.isProcessable(getShell(), member))
return;
FindOccurrencesEngine engine= FindOccurrencesEngine.create(member);
try {
ISourceRange range= member.getNameRange();
String result= engine.run(range.getOffset(), range.getLength());
if (result != null)
showMessage(getShell(), fActionBars, result);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private static void showMessage(Shell shell, IActionBars actionBars, String msg) {
IStatusLineManager statusLine= actionBars.getStatusLineManager();
if (statusLine != null)
statusLine.setMessage(msg);
shell.getDisplay().beep();
}
//---- Text Selection ----------------------------------------------------------------------
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
}
/* (non-JavaDoc)
* Method declared in SelectionDispatchAction.
*/
protected final void run(ITextSelection ts) {
IJavaElement input= getEditorInput(fEditor);
if (!ActionUtil.isProcessable(getShell(), input))
return;
FindOccurrencesEngine engine= FindOccurrencesEngine.create(input);
try {
String result= engine.run(ts.getOffset(), ts.getLength());
if (result != null)
showMessage(getShell(), fEditor, result);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
private static IJavaElement getEditorInput(JavaEditor editor) {
IEditorInput input= editor.getEditorInput();
if (input instanceof IClassFileEditorInput)
return ((IClassFileEditorInput)input).getClassFile();
return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(editor.getEditorInput());
}
private static void showMessage(Shell shell, JavaEditor editor, String msg) {
IEditorStatusLine statusLine= (IEditorStatusLine) editor.getAdapter(IEditorStatusLine.class);
if (statusLine != null)
statusLine.setMessage(true, msg, null);
shell.getDisplay().beep();
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/InlineAction.java
|
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
import org.eclipse.jdt.internal.ui.refactoring.actions.InlineConstantAction;
import org.eclipse.jdt.internal.ui.refactoring.actions.InlineMethodAction;
import org.eclipse.jdt.internal.corext.Assert;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineConstantRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineMethodRefactoring;
import org.eclipse.jdt.internal.corext.refactoring.code.InlineTempRefactoring;
/**
* Inlines a method, local variable or a static final field.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*/
public class InlineAction extends SelectionDispatchAction {
private CompilationUnitEditor fEditor;
private final InlineTempAction fInlineTemp;
private final InlineMethodAction fInlineMethod;
private final InlineConstantAction fInlineConstant;
/**
* Creates a new <code>InlineAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public InlineAction(IWorkbenchSite site) {
super(site);
setText(RefactoringMessages.getString("InlineAction.Inline")); //$NON-NLS-1$
fInlineTemp = new InlineTempAction(site);
fInlineMethod = new InlineMethodAction(site);
fInlineConstant = new InlineConstantAction(site);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public InlineAction(CompilationUnitEditor editor) {
//don't want to call 'this' here - it'd create useless action objects
super(editor.getEditorSite());
setText(RefactoringMessages.getString("InlineAction.Inline")); //$NON-NLS-1$
fEditor= editor;
fInlineTemp = new InlineTempAction(editor);
fInlineMethod = new InlineMethodAction(editor);
fInlineConstant = new InlineConstantAction(editor);
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.INLINE_ACTION);
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#selectionChanged(org.eclipse.jface.viewers.ISelection)
*/
protected void selectionChanged(ISelection selection) {
fInlineConstant.update(selection);
fInlineMethod.update(selection);
fInlineTemp.update(selection);
setEnabled(computeEnablementState());
}
private boolean computeEnablementState() {
return fInlineTemp.isEnabled() || fInlineConstant.isEnabled() || fInlineMethod.isEnabled();
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.text.ITextSelection)
*/
protected void run(ITextSelection selection) {
ICompilationUnit cu= getCompilationUnit();
if (cu == null || !ActionUtil.isProcessable(getShell(), cu))
return;
if (fInlineTemp.isEnabled() && tryInlineTemp(cu, selection))
return;
if (fInlineMethod.isEnabled() && tryInlineMethod(cu, selection))
return;
if (fInlineConstant.isEnabled() && tryInlineConstant(cu, selection))
return;
MessageDialog.openInformation(getShell(), RefactoringMessages.getString("InlineAction.dialog_title"), RefactoringMessages.getString("InlineAction.select")); //$NON-NLS-1$ //$NON-NLS-2$
}
private boolean tryInlineTemp(ICompilationUnit cu, ITextSelection selection){
InlineTempRefactoring inlineTemp= new InlineTempRefactoring(cu, selection.getOffset(), selection.getLength());
if (inlineTemp.checkIfTempSelectedSelected().hasFatalError())
return false;
fInlineTemp.run(selection);
return true;
}
private boolean tryInlineMethod(ICompilationUnit cu, ITextSelection selection){
InlineMethodRefactoring inlineMethodRef= InlineMethodRefactoring.create(
cu, selection.getOffset(), selection.getLength(),
JavaPreferencesSettings.getCodeGenerationSettings());
if (inlineMethodRef == null)
return false;
fInlineMethod.run(selection);
return true;
}
private boolean tryInlineConstant(ICompilationUnit cu, ITextSelection selection){
InlineConstantRefactoring inlineConstantRef= InlineConstantRefactoring.create(
cu, selection.getOffset(), selection.getLength(),
JavaPreferencesSettings.getCodeGenerationSettings());
if (inlineConstantRef == null || inlineConstantRef.checkStaticFinalConstantNameSelected().hasFatalError())
return false;
fInlineConstant.run(selection);
return true;
}
private ICompilationUnit getCompilationUnit() {
return SelectionConverter.getInputAsCompilationUnit(fEditor);
}
/*
* @see org.eclipse.jdt.ui.actions.SelectionDispatchAction#run(org.eclipse.jface.viewers.IStructuredSelection)
*/
protected void run(IStructuredSelection selection) {
if (fInlineConstant.isEnabled())
fInlineConstant.run(selection);
else if (fInlineMethod.isEnabled())
fInlineMethod.run(selection);
else
//inline temp will never be enabled on IStructuredSelection
//don't bother running it
Assert.isTrue(! fInlineTemp.isEnabled());
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/JavaSearchActionGroup.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import org.eclipse.jface.util.Assert;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.actions.ActionContext;
import org.eclipse.ui.actions.ActionGroup;
import org.eclipse.ui.part.Page;
import org.eclipse.ui.texteditor.ITextEditorActionConstants;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.search.SearchMessages;
import org.eclipse.jdt.ui.IContextMenuConstants;
/**
* Action group that adds the Java search actions to a context menu and
* the global menu bar.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class JavaSearchActionGroup extends ActionGroup {
private JavaEditor fEditor;
private IWorkbenchSite fSite;
private ReferencesSearchGroup fReferencesGroup;
private ReadReferencesSearchGroup fReadAccessGroup;
private WriteReferencesSearchGroup fWriteAccessGroup;
private DeclarationsSearchGroup fDeclarationsGroup;
private ImplementorsSearchGroup fImplementorsGroup;
private FindOccurrencesInFileAction fOccurrencesInFileAction;
/**
* Creates a new <code>JavaSearchActionGroup</code>. The group
* requires that the selection provided by the part's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param part the view part that owns this action group
*/
public JavaSearchActionGroup(IViewPart part) {
this(part.getViewSite());
fOccurrencesInFileAction= new FindOccurrencesInFileAction(part);
part.getViewSite().getSelectionProvider().addSelectionChangedListener(fOccurrencesInFileAction);
}
/**
* Creates a new <code>JavaSearchActionGroup</code>. The group
* requires that the selection provided by the page's selection provider
* is of type <code>org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param page the page that owns this action group
*/
public JavaSearchActionGroup(Page page) {
this(page.getSite());
fOccurrencesInFileAction= new FindOccurrencesInFileAction(page);
page.getSite().getSelectionProvider().addSelectionChangedListener(fOccurrencesInFileAction);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public JavaSearchActionGroup(JavaEditor editor) {
Assert.isNotNull(editor);
fEditor= editor;
fSite= fEditor.getSite();
fReferencesGroup= new ReferencesSearchGroup(fEditor);
fReadAccessGroup= new ReadReferencesSearchGroup(fEditor);
fWriteAccessGroup= new WriteReferencesSearchGroup(fEditor);
fDeclarationsGroup= new DeclarationsSearchGroup(fEditor);
fImplementorsGroup= new ImplementorsSearchGroup(fEditor);
fOccurrencesInFileAction= new FindOccurrencesInFileAction(fEditor);
}
private JavaSearchActionGroup(IWorkbenchSite site) {
fReferencesGroup= new ReferencesSearchGroup(site);
fReadAccessGroup= new ReadReferencesSearchGroup(site);
fWriteAccessGroup= new WriteReferencesSearchGroup(site);
fDeclarationsGroup= new DeclarationsSearchGroup(site);
fImplementorsGroup= new ImplementorsSearchGroup(site);
fSite= site;
}
/*
* Method declared on ActionGroup.
*/
public void setContext(ActionContext context) {
fReferencesGroup.setContext(context);
fDeclarationsGroup.setContext(context);
fImplementorsGroup.setContext(context);
fReadAccessGroup.setContext(context);
fWriteAccessGroup.setContext(context);
}
/*
* Method declared on ActionGroup.
*/
public void fillActionBars(IActionBars actionBar) {
super.fillActionBars(actionBar);
fReferencesGroup.fillActionBars(actionBar);
fDeclarationsGroup.fillActionBars(actionBar);
fImplementorsGroup.fillActionBars(actionBar);
fReadAccessGroup.fillActionBars(actionBar);
fWriteAccessGroup.fillActionBars(actionBar);
actionBar.setGlobalActionHandler(JdtActionConstants.FIND_OCCURRENCES_IN_FILE, fOccurrencesInFileAction);
}
/*
* Method declared on ActionGroup.
*/
public void fillContextMenu(IMenuManager menu) {
super.fillContextMenu(menu);
IMenuManager target= menu;
IMenuManager searchSubMenu= null;
if (fEditor != null) {
String groupName= SearchMessages.getString("group.search"); //$NON-NLS-1$
searchSubMenu= new MenuManager(groupName, ITextEditorActionConstants.GROUP_FIND);
searchSubMenu.add(new GroupMarker(ITextEditorActionConstants.GROUP_FIND));
target= searchSubMenu;
}
fReferencesGroup.fillContextMenu(target);
fDeclarationsGroup.fillContextMenu(target);
fImplementorsGroup.fillContextMenu(target);
fReadAccessGroup.fillContextMenu(target);
fWriteAccessGroup.fillContextMenu(target);
if (searchSubMenu != null) {
searchSubMenu.add(new Separator());
addAction(target, fOccurrencesInFileAction);
} else {
addAction(target, IContextMenuConstants.GROUP_SEARCH, fOccurrencesInFileAction);
}
// no other way to find out if we have added items.
if (searchSubMenu != null && searchSubMenu.getItems().length > 1) {
menu.appendToGroup(ITextEditorActionConstants.GROUP_FIND, searchSubMenu);
}
}
/*
* Method declared on ActionGroup.
*/
public void dispose() {
fReferencesGroup.dispose();
fDeclarationsGroup.dispose();
fImplementorsGroup.dispose();
fReadAccessGroup.dispose();
fWriteAccessGroup.dispose();
if (fOccurrencesInFileAction != null)
fSite.getSelectionProvider().removeSelectionChangedListener(fOccurrencesInFileAction);
super.dispose();
}
private void addAction(IMenuManager manager, IAction action) {
if (action != null && action.isEnabled())
manager.add(action);
}
private void addAction(IMenuManager manager, String group, IAction action) {
if (action != null && action.isEnabled())
manager.appendToGroup(group, action);
}
}
|
31,687 |
Bug 31687 NPE in FindOccurrencesEngine.create
|
I create a Java editor in plug-in code. It comes up ok but when I select a word and do the "Search...Occurrences in File" action it bombs with the traceback below. Here is the plug-in code that creates the editor: IWorkbenchPage page = PlatformUI.getWorkbench ().getActiveWorkbenchWindow().getActivePage(); if (page == null) return; IStorage storage = new FileStorage(path); IEditorRegistry registry= PlatformUI.getWorkbench().getEditorRegistry (); IEditorDescriptor desc = registry.getDefaultEditor(fileName); if (desc == null) { desc = registry.getDefaultEditor(); } IEditorInput input = new ExternalEditorInput(storage); IEditorPart editor = page.openEditor(input, desc.getId()); FileStorage and ExternalEditorInput are my own classes that I based on examples from JDT (jar reading) and CDT. I can attach them if needed. The problem seems to be that CompilationUnitDocumentProvider.getWorkingCopy is returning null because getElementInfo isn't returning a CompilationUnitInfo (an internal class). It's unclear to me if this is something I'm not setting up properly in my code or if the find engine should be doing something differently. /* * @see IWorkingCopyManager#getWorkingCopy(Object) */ public ICompilationUnit getWorkingCopy(IEditorInput element) { ElementInfo elementInfo= getElementInfo(element); if (elementInfo instanceof CompilationUnitInfo) { CompilationUnitInfo info= (CompilationUnitInfo) elementInfo; return info.fCopy; } return null; } Here's the traceback: Thread [main] (Suspended (exception java.lang.NullPointerException)) org.eclipse.jdt.internal.ui.search.FindOccurrencesEngine.create (org.eclipse.jdt.core.IJavaElement) line: 127 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction.run (org.eclipse.jface.text.ITextSelection) line: 163 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).dispatchRun (org.eclipse.jface.viewers.ISelection) line: 193 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jdt.ui.actions.SelectionDispatchAction).run() line: 169 org.eclipse.jdt.ui.actions.FindOccurrencesInFileAction (org.eclipse.jface.action.Action).runWithEvent(org.eclipse.swt.widgets.Event) line: 804 org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (org.eclipse.swt.widgets.Event) line: 450 org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (org.eclipse.swt.widgets.Event) line: 398 org.eclipse.jface.action.ActionContributionItem.access$0 (org.eclipse.jface.action.ActionContributionItem, org.eclipse.swt.widgets.Event) line: 392 org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEv ent(org.eclipse.swt.widgets.Event) line: 72 org.eclipse.swt.widgets.EventTable.sendEvent (org.eclipse.swt.widgets.Event) line: 77 org.eclipse.swt.widgets.MenuItem (org.eclipse.swt.widgets.Widget).sendEvent(org.eclipse.swt.widgets.Event) line: 836 org.eclipse.swt.widgets.Display.runDeferredEvents() line: 1692 org.eclipse.swt.widgets.Display.readAndDispatch() line: 1410 org.eclipse.ui.internal.Workbench.runEventLoop (org.eclipse.jface.window.Window$IExceptionHandler) line: 1289 org.eclipse.ui.internal.Workbench.run(java.lang.Object) line: 1272 org.eclipse.core.internal.boot.InternalBootLoader.run (java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 845 org.eclipse.core.boot.BootLoader.run(java.lang.String, java.net.URL, java.lang.String, java.lang.String[], java.lang.Runnable) line: 461 sun.reflect.NativeMethodAccessorImpl.invoke0(java.lang.reflect.Method, java.lang.Object, java.lang.Object[]) line: not available [native method] sun.reflect.NativeMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 39 [local variables unavailable] sun.reflect.DelegatingMethodAccessorImpl.invoke(java.lang.Object, java.lang.Object[]) line: 25 [local variables unavailable] java.lang.reflect.Method.invoke(java.lang.Object, java.lang.Object[]) line: 324 [local variables unavailable] org.eclipse.core.launcher.Main.basicRun(java.lang.String[]) line: 247 org.eclipse.core.launcher.Main.run(java.lang.String[]) line: 703 org.eclipse.core.launcher.Main.main(java.lang.String[]) line: 539
|
resolved fixed
|
36faefe
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T10:51:27Z | 2003-02-12T17:13:20Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/OrganizeImportsAction.java
|
/*******************************************************************************
* Copyright (c) 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
******************************************************************************/
package org.eclipse.jdt.ui.actions;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.eclipse.core.resources.IWorkspaceRunnable;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IStatusLineManager;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.IEditorActionBarContributor;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchSite;
import org.eclipse.ui.help.WorkbenchHelp;
import org.eclipse.ui.part.EditorActionBarContributor;
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.ISourceRange;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.ui.IWorkingCopyManager;
import org.eclipse.jdt.ui.JavaUI;
import org.eclipse.jdt.ui.PreferenceConstants;
import org.eclipse.jdt.internal.corext.ValidateEditException;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.TypeInfo;
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
import org.eclipse.jdt.internal.ui.browsing.LogicalPackage;
import org.eclipse.jdt.internal.ui.dialogs.MultiElementListSelectionDialog;
import org.eclipse.jdt.internal.ui.dialogs.ProblemDialog;
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.internal.ui.util.ElementValidator;
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
import org.eclipse.jdt.internal.ui.util.TypeInfoLabelProvider;
/**
* Organizes the imports of a compilation unit.
* <p>
* The action is applicable to selections containing elements of
* type <code>ICompilationUnit</code> or <code>IPackage
* </code>.
*
* <p>
* This class may be instantiated; it is not intended to be subclassed.
* </p>
*
* @since 2.0
*/
public class OrganizeImportsAction extends SelectionDispatchAction {
private JavaEditor fEditor;
/* (non-Javadoc)
* Class implements IObjectActionDelegate
*/
public static class ObjectDelegate implements IObjectActionDelegate {
private OrganizeImportsAction fAction;
public void setActivePart(IAction action, IWorkbenchPart targetPart) {
fAction= new OrganizeImportsAction(targetPart.getSite());
}
public void run(IAction action) {
fAction.run();
}
public void selectionChanged(IAction action, ISelection selection) {
if (fAction == null)
action.setEnabled(false);
}
}
/**
* Creates a new <code>OrganizeImportsAction</code>. The action requires
* that the selection provided by the site's selection provider is of type <code>
* org.eclipse.jface.viewers.IStructuredSelection</code>.
*
* @param site the site providing context information for this action
*/
public OrganizeImportsAction(IWorkbenchSite site) {
super(site);
setText(ActionMessages.getString("OrganizeImportsAction.label")); //$NON-NLS-1$
setToolTipText(ActionMessages.getString("OrganizeImportsAction.tooltip")); //$NON-NLS-1$
setDescription(ActionMessages.getString("OrganizeImportsAction.description")); //$NON-NLS-1$
WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ORGANIZE_IMPORTS_ACTION);
}
/**
* Note: This constructor is for internal use only. Clients should not call this constructor.
*/
public OrganizeImportsAction(JavaEditor editor) {
this(editor.getEditorSite());
fEditor= editor;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(ITextSelection selection) {
// do nothing
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void selectionChanged(IStructuredSelection selection) {
setEnabled(isEnabled(selection));
}
private ICompilationUnit[] getCompilationUnits(IStructuredSelection selection) {
HashSet result= new HashSet();
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
result.add(elem);
break;
case IJavaElement.IMPORT_CONTAINER:
result.add(elem.getParent());
break;
case IJavaElement.PACKAGE_FRAGMENT:
collectCompilationUnits((IPackageFragment) elem, result);
break;
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
collectCompilationUnits((IPackageFragmentRoot) elem, result);
break;
case IJavaElement.JAVA_PROJECT:
IPackageFragmentRoot[] roots= ((IJavaProject) elem).getPackageFragmentRoots();
for (int k= 0; k < roots.length; k++) {
collectCompilationUnits(roots[k], result);
}
break;
}
} else if (selected[i] instanceof LogicalPackage) {
IPackageFragment[] packageFragments= ((LogicalPackage)selected[i]).getFragments();
for (int k= 0; k < packageFragments.length; k++)
collectCompilationUnits(packageFragments[k], result);
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return (ICompilationUnit[]) result.toArray(new ICompilationUnit[result.size()]);
}
private void collectCompilationUnits(IPackageFragment pack, Collection result) throws JavaModelException {
result.addAll(Arrays.asList(pack.getCompilationUnits()));
}
private void collectCompilationUnits(IPackageFragmentRoot root, Collection result) throws JavaModelException {
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
IJavaElement[] children= root.getChildren();
for (int i= 0; i < children.length; i++) {
collectCompilationUnits((IPackageFragment) children[i], result);
}
}
}
private boolean isEnabled(IStructuredSelection selection) {
Object[] selected= selection.toArray();
for (int i= 0; i < selected.length; i++) {
try {
if (selected[i] instanceof IJavaElement) {
IJavaElement elem= (IJavaElement) selected[i];
switch (elem.getElementType()) {
case IJavaElement.COMPILATION_UNIT:
return true;
case IJavaElement.IMPORT_CONTAINER:
return true;
case IJavaElement.PACKAGE_FRAGMENT:
case IJavaElement.PACKAGE_FRAGMENT_ROOT:
IPackageFragmentRoot root= (IPackageFragmentRoot) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
return (root.getKind() == IPackageFragmentRoot.K_SOURCE);
case IJavaElement.JAVA_PROJECT:
return hasSourceFolders((IJavaProject) elem);
}
}
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
return false;
}
private boolean hasSourceFolders(IJavaProject project) throws JavaModelException {
IPackageFragmentRoot[] roots= project.getPackageFragmentRoots();
for (int i= 0; i < roots.length; i++) {
IPackageFragmentRoot root= roots[i];
if (root.getKind() == IPackageFragmentRoot.K_SOURCE) {
return true;
}
}
return false;
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(ITextSelection selection) {
IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager();
ICompilationUnit cu= manager.getWorkingCopy(fEditor.getEditorInput());
run(cu);
}
/* (non-Javadoc)
* Method declared on SelectionDispatchAction.
*/
protected void run(IStructuredSelection selection) {
ICompilationUnit[] cus= getCompilationUnits(selection);
if (cus.length == 1) {
run(cus[0]);
} else {
runOnMultiple(cus);
}
}
private void runOnMultiple(final ICompilationUnit[] cus) {
try {
String message= ActionMessages.getString("OrganizeImportsAction.multi.status.description"); //$NON-NLS-1$
final MultiStatus status= new MultiStatus(JavaUI.ID_PLUGIN, Status.OK, message, null);
ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell());
dialog.run(true, true, new WorkbenchRunnableAdapter(new IWorkspaceRunnable() {
public void run(IProgressMonitor monitor) {
doRunOnMultiple(cus, status, monitor);
}
}));
if (!status.isOK()) {
String title= ActionMessages.getString("OrganizeImportsAction.multi.status.title"); //$NON-NLS-1$
ProblemDialog.open(getShell(), title, null, status);
}
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
// cancelled by user
}
}
static final class OrganizeImportError extends Error {
}
private void doRunOnMultiple(ICompilationUnit[] cus, MultiStatus status, IProgressMonitor monitor) throws OperationCanceledException {
if (monitor == null) {
monitor= new NullProgressMonitor();
}
monitor.beginTask(ActionMessages.getString("OrganizeImportsAction.multi.op.description"), cus.length); //$NON-NLS-1$
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
IChooseImportQuery query= new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
throw new OrganizeImportError();
}
};
for (int i= 0; i < cus.length; i++) {
ICompilationUnit cu= cus[i];
String cuLocation= cu.getPath().makeRelative().toString();
cu= JavaModelUtil.toWorkingCopy(cu);
monitor.subTask(cuLocation);
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), true, query);
runInSync(op, cuLocation, status, monitor);
if (monitor.isCanceled()) {
throw new OperationCanceledException();
}
IProblem parseError= op.getParseError();
if (parseError != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.parse", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
}
} finally {
monitor.done();
}
}
private void runInSync(final OrganizeImportsOperation op, final String cuLocation, final MultiStatus status, final IProgressMonitor monitor) {
Runnable runnable= new Runnable() {
public void run() {
try {
op.run(new SubProgressMonitor(monitor, 1));
} catch (ValidateEditException e) {
status.add(e.getStatus());
} catch (CoreException e) {
JavaPlugin.log(e);
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unexpected", e.getStatus().getMessage()); //$NON-NLS-1$
status.add(new Status(Status.ERROR, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
} catch (OrganizeImportError e) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.multi.error.unresolvable", cuLocation); //$NON-NLS-1$
status.add(new Status(Status.INFO, JavaUI.ID_PLUGIN, Status.ERROR, message, null));
}
}
};
getShell().getDisplay().syncExec(runnable);
}
public void run(ICompilationUnit cu) {
if (!ElementValidator.check(cu, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), fEditor != null)) //$NON-NLS-1$
return;
try {
IPreferenceStore store= PreferenceConstants.getPreferenceStore();
String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store);
int threshold= JavaPreferencesSettings.getImportNumberThreshold(store);
boolean ignoreLowerCaseNames= store.getBoolean(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE);
if (!cu.isWorkingCopy()) {
IEditorPart editor= EditorUtility.openInEditor(cu);
if (editor instanceof JavaEditor) {
fEditor= (JavaEditor) editor;
}
cu= JavaModelUtil.toWorkingCopy(cu);
}
OrganizeImportsOperation op= new OrganizeImportsOperation(cu, prefOrder, threshold, ignoreLowerCaseNames, !cu.isWorkingCopy(), true, createChooseImportQuery());
BusyIndicatorRunnableContext context= new BusyIndicatorRunnableContext();
context.run(false, true, new WorkbenchRunnableAdapter(op));
IProblem parseError= op.getParseError();
if (parseError != null) {
String message= ActionMessages.getFormattedString("OrganizeImportsAction.single.error.parse", parseError.getMessage()); //$NON-NLS-1$
MessageDialog.openInformation(getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), message); //$NON-NLS-1$
if (fEditor != null && parseError.getSourceStart() != -1) {
fEditor.selectAndReveal(parseError.getSourceStart(), parseError.getSourceEnd() - parseError.getSourceStart() + 1);
}
} else {
if (fEditor != null) {
setStatusBarMessage(getOrganizeInfo(op));
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InvocationTargetException e) {
ExceptionHandler.handle(e, getShell(), ActionMessages.getString("OrganizeImportsAction.error.title"), ActionMessages.getString("OrganizeImportsAction.error.message")); //$NON-NLS-1$ //$NON-NLS-2$
} catch (InterruptedException e) {
}
}
private String getOrganizeInfo(OrganizeImportsOperation op) {
int nImportsAdded= op.getNumberOfImportsAdded();
if (nImportsAdded >= 0) {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_added", String.valueOf(nImportsAdded)); //$NON-NLS-1$
} else {
return ActionMessages.getFormattedString("OrganizeImportsAction.summary_removed", String.valueOf(-nImportsAdded)); //$NON-NLS-1$
}
}
private IChooseImportQuery createChooseImportQuery() {
return new IChooseImportQuery() {
public TypeInfo[] chooseImports(TypeInfo[][] openChoices, ISourceRange[] ranges) {
return doChooseImports(openChoices, ranges);
}
};
}
private TypeInfo[] doChooseImports(TypeInfo[][] openChoices, final ISourceRange[] ranges) {
// remember selection
ISelection sel= fEditor != null ? fEditor.getSelectionProvider().getSelection() : null;
TypeInfo[] result= null;;
ILabelProvider labelProvider= new TypeInfoLabelProvider(TypeInfoLabelProvider.SHOW_FULLYQUALIFIED);
MultiElementListSelectionDialog dialog= new MultiElementListSelectionDialog(getShell(), labelProvider) {
protected void handleSelectionChanged() {
super.handleSelectionChanged();
// show choices in editor
doListSelectionChanged(getCurrentPage(), ranges);
}
};
dialog.setTitle(ActionMessages.getString("OrganizeImportsAction.selectiondialog.title")); //$NON-NLS-1$
dialog.setMessage(ActionMessages.getString("OrganizeImportsAction.selectiondialog.message")); //$NON-NLS-1$
dialog.setElements(openChoices);
if (dialog.open() == Window.OK) {
Object[] res= dialog.getResult();
result= new TypeInfo[res.length];
for (int i= 0; i < res.length; i++) {
Object[] array= (Object[]) res[i];
if (array.length > 0)
result[i]= (TypeInfo) array[0];
}
}
// restore selection
if (sel instanceof ITextSelection) {
ITextSelection textSelection= (ITextSelection) sel;
fEditor.selectAndReveal(textSelection.getOffset(), textSelection.getLength());
}
return result;
}
private void doListSelectionChanged(int page, ISourceRange[] ranges) {
if (page >= 0 && page < ranges.length) {
ISourceRange range= ranges[page];
fEditor.selectAndReveal(range.getOffset(), range.getLength());
}
}
private void setStatusBarMessage(String message) {
IEditorActionBarContributor contributor= fEditor.getEditorSite().getActionBarContributor();
if (contributor instanceof EditorActionBarContributor) {
IStatusLineManager manager= ((EditorActionBarContributor) contributor).getActionBars().getStatusLineManager();
manager.setMessage(message);
}
}
}
|
30,553 |
Bug 30553 Quick fix suggestions for unresolved type after "new" could be ordered better [quick fix]
|
(Build I20030107, GTK, Sun JDK 1.4.1-b21, Gentoo Linux 2.4.19) I often use statements like this: Map map = new HashMap(); If java.util.Map has been imported, but java.util.HashMap hasn't then there will be quick fix suggestions for 'HashMap'. The suggestions are: Change to 'Map' Import 'java.util.HashMap' ... I suggest that a better order would reverse the top two suggestions. ie: Import 'java.util.HashMap' Change to 'Map' ... I know there is an algorithm for determining the order of suggestions. When a suggestion is made to fix an unresolved type after a "new" statement, classes which can be instantiated should be shown higher than interfaces and abstract classes. Interfaces and abstract classes only make sense if an anonymous class is being created and this is much less common.
|
resolved fixed
|
02ca2a4
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T11:01:00Z | 2003-01-29T22:40:00Z |
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
|
/*******************************************************************************
* Copyright (c) 2000, 2002 International Business Machines Corp. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* Renaud Waldura <[email protected]> - New class/interface with wizard
******************************************************************************/
package org.eclipse.jdt.internal.ui.text.correction;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.graphics.Image;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit;
import org.eclipse.jdt.internal.corext.dom.Bindings;
import org.eclipse.jdt.internal.corext.textmanipulation.SimpleTextEdit;
import org.eclipse.jdt.internal.corext.textmanipulation.TextEdit;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.ui.JavaPluginImages;
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
public class UnresolvedElementsSubProcessor {
public static void getVariableProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveredNode();
if (selectedNode == null) {
return;
}
// type that defines the variable, null if local
ITypeBinding binding= null;
ITypeBinding declaringTypeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (declaringTypeBinding == null) {
return;
}
// possible kind of the node
int similarNodeKind= SimilarElementsRequestor.VARIABLES;
Name node= null;
if (selectedNode instanceof SimpleName) {
node= (SimpleName) selectedNode;
ASTNode parent= node.getParent();
if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) {
similarNodeKind |= SimilarElementsRequestor.CLASSES;
}
} else if (selectedNode instanceof QualifiedName) {
QualifiedName qualifierName= (QualifiedName) selectedNode;
ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding();
if (qualifierBinding != null) {
node= qualifierName.getName();
binding= qualifierBinding;
} else {
node= qualifierName.getQualifier();
if (node.isSimpleName()) {
similarNodeKind |= SimilarElementsRequestor.REF_TYPES;
} else {
similarNodeKind= SimilarElementsRequestor.REF_TYPES;
}
}
} else if (selectedNode instanceof FieldAccess) {
FieldAccess access= (FieldAccess) selectedNode;
Expression expression= access.getExpression();
if (expression != null) {
binding= expression.resolveTypeBinding();
if (binding != null) {
node= access.getName();
}
}
} else if (selectedNode instanceof SuperFieldAccess) {
binding= declaringTypeBinding.getSuperclass();
} else if (selectedNode instanceof SimpleType) {
similarNodeKind= SimilarElementsRequestor.REF_TYPES;
node= ((SimpleType) selectedNode).getName();
}
if (node == null) {
return;
}
// avoid corrections like int i= i;
String assignedName= null;
ASTNode parent= node.getParent();
if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) {
assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier();
}
// corrections
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, similarNodeKind);
for (int i= 0; i < elements.length; i++) {
SimilarElement curr= elements[i];
if ((curr.getKind() & SimilarElementsRequestor.VARIABLES) != 0 && !curr.getName().equals(assignedName)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", curr.getName()); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), curr.getName(), 3));
}
}
// add type proposals
if ((similarNodeKind & SimilarElementsRequestor.ALL_TYPES) != 0) {
int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0;
addSimilarTypeProposals(elements, cu, node, relevance + 1, proposals);
addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals);
}
if ((similarNodeKind & SimilarElementsRequestor.VARIABLES) == 0) {
return;
}
SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName();
// new variables
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding;
if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label;
Image image;
if (binding == null) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
}
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image));
if (binding == null && senderBinding.isAnonymous()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding);
if (anonymDecl != null) {
senderBinding= ASTResolving.getBindingOfParentType(anonymDecl.getParent());
if (!senderBinding.isAnonymous()) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC);
proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 2, image));
}
}
}
}
if (binding == null) {
BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node);
int type= bodyDeclaration.getNodeType();
if (type == ASTNode.METHOD_DECLARATION) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 1, image));
}
if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 3, image));
}
}
}
public static void getTypeProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
int kind= SimilarElementsRequestor.ALL_TYPES;
ASTNode parent= selectedNode.getParent();
switch (parent.getNodeType()) {
case ASTNode.TYPE_DECLARATION:
TypeDeclaration typeDeclaration=(TypeDeclaration) parent;
if (typeDeclaration.superInterfaces().contains(selectedNode)) {
kind= SimilarElementsRequestor.INTERFACES;
} else if (selectedNode.equals(typeDeclaration.getSuperclass())) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
case ASTNode.METHOD_DECLARATION:
MethodDeclaration methodDeclaration= (MethodDeclaration) parent;
if (methodDeclaration.thrownExceptions().contains(selectedNode)) {
kind= SimilarElementsRequestor.CLASSES;
} else if (selectedNode.equals(methodDeclaration.getReturnType())) {
kind= SimilarElementsRequestor.REF_TYPES | SimilarElementsRequestor.VOIDTYPE;
}
break;
case ASTNode.INSTANCEOF_EXPRESSION:
kind= SimilarElementsRequestor.REF_TYPES;
break;
case ASTNode.THROW_STATEMENT:
case ASTNode.CLASS_INSTANCE_CREATION:
kind= SimilarElementsRequestor.CLASSES;
break;
case ASTNode.SINGLE_VARIABLE_DECLARATION:
int superParent= parent.getParent().getNodeType();
if (superParent == ASTNode.CATCH_CLAUSE) {
kind= SimilarElementsRequestor.CLASSES;
}
break;
default:
}
Name node= null;
if (selectedNode instanceof SimpleType) {
node= ((SimpleType) selectedNode).getName();
} else if (selectedNode instanceof ArrayType) {
Type elementType= ((ArrayType) selectedNode).getElementType();
if (elementType.isSimpleType()) {
node= ((SimpleType) elementType).getName();
}
} else if (selectedNode instanceof Name) {
node= (Name) selectedNode;
} else {
return;
}
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind);
addSimilarTypeProposals(elements, cu, node, 3, proposals);
// add type
addNewTypeProposals(cu, node, kind, 0, proposals);
}
private static void addSimilarTypeProposals(SimilarElement[] elements, ICompilationUnit cu, Name node, int relevance, List proposals) throws JavaModelException {
// try to resolve type in context -> highest severity
String resolvedTypeName= null;
ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node);
if (binding != null) {
if (binding.isArray()) {
binding= binding.getElementType();
}
resolvedTypeName= Bindings.getFullyQualifiedName(binding);
proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2));
}
// add all similar elements
for (int i= 0; i < elements.length; i++) {
SimilarElement elem= elements[i];
if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) {
String fullName= elem.getName();
if (!fullName.equals(resolvedTypeName)) {
proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance));
}
}
}
}
private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws JavaModelException {
CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
String simpleName= importEdit.addImport(fullName);
TextEdit root= proposal.getRootTextEdit();
if (!importEdit.isEmpty()) {
root.add(importEdit); //$NON-NLS-1$
}
if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only
proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL));
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", fullName)); //$NON-NLS-1$
proposal.setRelevance(relevance + 2);
} else {
root.add(SimpleTextEdit.createReplace(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$
proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", simpleName)); //$NON-NLS-1$
proposal.setRelevance(relevance);
}
return proposal;
}
private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, List proposals) throws JavaModelException {
Name node= refNode;
do {
String typeName= ASTResolving.getSimpleName(node);
Name qualifier= null;
// only propose to create types for qualifiers when the name starts with upper case
boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode);
if (isPossibleName) {
IPackageFragment enclosingPackage= null;
IType enclosingType= null;
if (node.isSimpleName()) {
enclosingPackage= (IPackageFragment) cu.getParent();
// don't sugest member type, user can select it in wizard
} else {
Name qualifierName= ((QualifiedName) node).getQualifier();
// 24347
// IBinding binding= qualifierName.resolveBinding();
// if (binding instanceof ITypeBinding) {
// enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject());
IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength());
if (res!= null && res.length > 0 && res[0] instanceof IType) {
enclosingType= (IType) res[0];
} else {
qualifier= qualifierName;
enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName));
}
}
// new top level type
if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance));
}
}
// new member type
if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) {
if ((kind & SimilarElementsRequestor.CLASSES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance));
}
if ((kind & SimilarElementsRequestor.INTERFACES) != 0) {
proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance));
}
}
}
node= qualifier;
} while (node != null);
}
public static void getMethodProposals(ICorrectionContext context, boolean needsNewName, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (!(selectedNode instanceof SimpleName)) {
return;
}
SimpleName nameNode= (SimpleName) selectedNode;
List arguments;
Expression sender;
boolean isSuperInvocation;
ASTNode invocationNode= nameNode.getParent();
if (invocationNode instanceof MethodInvocation) {
MethodInvocation methodImpl= (MethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getExpression();
isSuperInvocation= false;
} else if (invocationNode instanceof SuperMethodInvocation) {
SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode;
arguments= methodImpl.arguments();
sender= methodImpl.getQualifier();
isSuperInvocation= true;
} else {
return;
}
String methodName= nameNode.getIdentifier();
// corrections
SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, nameNode, SimilarElementsRequestor.METHODS);
ArrayList parameterMismatchs= new ArrayList();
for (int i= 0; i < elements.length; i++) {
String curr= elements[i].getName();
if (curr.equals(methodName) && needsNewName) {
//parameterMismatchs.add(elements[i]);
continue;
}
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$
proposals.add(new ReplaceCorrectionProposal(label, context.getCompilationUnit(), context.getOffset(), context.getLength(), curr, 2));
}
if (parameterMismatchs.size() == 1) {
SimilarElement elem= (SimilarElement) parameterMismatchs.get(0);
String[] paramTypes= elem.getParameterTypes();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (paramTypes != null && argTypes != null) {
}
}
// new method
ITypeBinding binding= null;
if (sender != null) {
binding= sender.resolveTypeBinding();
} else {
binding= ASTResolving.getBindingOfParentType(invocationNode);
if (isSuperInvocation && binding != null) {
binding= binding.getSuperclass();
}
}
if (binding != null && binding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding);
if (targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label;
Image image;
if (cu.equals(targetCU)) {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", methodName); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE);
} else {
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { methodName, targetCU.getElementName() } ); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
}
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image));
if (binding.isAnonymous() && cu.equals(targetCU)) {
ASTNode anonymDecl= astRoot.findDeclaringNode(binding);
if (anonymDecl != null) {
binding= ASTResolving.getBindingOfParentType(anonymDecl.getParent());
if (!binding.isAnonymous()) {
String[] args= new String[] { methodName, binding.getName() };
label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$
image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED);
proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 1, image));
}
}
}
}
}
}
private static ITypeBinding[] getArgumentTypes(List arguments) {
ITypeBinding[] res= new ITypeBinding[arguments.size()];
for (int i= 0; i < res.length; i++) {
Expression expression= (Expression) arguments.get(i);
ITypeBinding curr= expression.resolveTypeBinding();
if (curr == null) {
return null;
}
curr= ASTResolving.normalizeTypeBinding(curr);
if (curr == null) {
curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
res[i]= curr;
}
return res;
}
public static void getConstructorProposals(ICorrectionContext context, List proposals) throws CoreException {
ICompilationUnit cu= context.getCompilationUnit();
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= context.getCoveringNode();
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding= null;
List arguments= null;
int type= selectedNode.getNodeType();
if (type == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode;
IBinding binding= creation.getName().resolveBinding();
if (binding instanceof ITypeBinding) {
targetBinding= (ITypeBinding) binding;
arguments= creation.arguments();
}
} else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding.getSuperclass();
arguments= ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding= ASTResolving.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding= typeBinding;
arguments= ((ConstructorInvocation) selectedNode).arguments();
}
}
if (targetBinding != null && targetBinding.isFromSource()) {
ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding);
if (targetCU != null && JavaModelUtil.isEditable(targetCU)) {
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", targetBinding.getName()); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC);
proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 1, image));
}
}
}
public static void getAmbiguosTypeReferenceProposals(ICorrectionContext context, List proposals) throws CoreException {
final ICompilationUnit cu= context.getCompilationUnit();
int offset= context.getOffset();
int len= context.getLength();
IJavaElement[] elements= cu.codeSelect(offset, len);
for (int i= 0; i < elements.length; i++) {
IJavaElement curr= elements[i];
if (curr instanceof IType) {
String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr);
String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$
Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL);
CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 1, image);
ImportEdit importEdit= new ImportEdit(cu, JavaPreferencesSettings.getCodeGenerationSettings());
importEdit.addImport(qualifiedTypeName);
importEdit.setFindAmbiguosImports(true);
proposal.getRootTextEdit().add(importEdit);
proposals.add(proposal);
}
}
}
}
|
30,940 |
Bug 30940 Convert nest to top level doesn't honor organize import settings [refactoring]
|
The new compilation unit generated by this refactoring doesn't honor the code templates nor does it honor the organize import settings. Adam, can you please comment on this.
|
resolved fixed
|
03a526c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T11:54:25Z | 2003-02-05T10:13:20Z |
org.eclipse.jdt.ui/core
| |
30,940 |
Bug 30940 Convert nest to top level doesn't honor organize import settings [refactoring]
|
The new compilation unit generated by this refactoring doesn't honor the code templates nor does it honor the organize import settings. Adam, can you please comment on this.
|
resolved fixed
|
03a526c
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T11:54:25Z | 2003-02-05T10:13:20Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/MoveInnerToTopRefactoring.java
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestLocalInitializer.java
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
org.eclipse.jdt.ui.tests.refactoring/test
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
cases/org/eclipse/jdt/ui/tests/refactoring/InlineMethodTests.java
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
org.eclipse.jdt.ui/core
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/base/RefactoringStatusCodes.java
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
org.eclipse.jdt.ui/core
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/CallInliner.java
| |
25,501 |
Bug 25501 inline method: syntax errors after
|
public class A { void g(){ int i= y(); } int y(){ if (true) return 4; else return 3; } } inline the call to y() - you get syntax errors
|
resolved fixed
|
40e2847
|
JDT
|
https://github.com/eclipse-jdt/eclipse.jdt.ui
|
eclipse-jdt/eclipse.jdt.ui
|
java
| null | null | null | 2003-02-13T14:31:05Z | 2002-10-29T16:46:40Z |
org.eclipse.jdt.ui/core
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.