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
45,680
Bug 45680 Add Import corner case [code manipulation]
I'm using M4. I have a source file which imports java.awt.* and java.util.*. Now, I need a method parameter of type java.util.List. I type 'List', highlight it, and press Ctrl+Shift+m; the Add Import dialog appears asking me to choose between java.awt.List and java.util.List. I select the proper one and OK, but my imports do not get updated. Seems like it realizes the java.util.* import should cover me, but it doesn't take into consideration the ambiguous aspect.
resolved fixed
dc996e9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-29T16:49:30Z
2003-10-28T19:40:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddImportsOperation.java
47,762
Bug 47762 ProgressDialog appears before Open Type dialog
M5 - start Eclipse with a populated workspace - do nothing for 10 seconds - open AllTypesDialog Observe: Sometimes you get a ProgressDialog before the Open Types dialog opens. This should never happend if Eclipse had been idle for at least 5 seconds because then the background caching thread should have started.
resolved fixed
afe057b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-29T21:06:30Z
2003-11-29T21:06:40Z
org.eclipse.jdt.ui/core
47,762
Bug 47762 ProgressDialog appears before Open Type dialog
M5 - start Eclipse with a populated workspace - do nothing for 10 seconds - open AllTypesDialog Observe: Sometimes you get a ProgressDialog before the Open Types dialog opens. This should never happend if Eclipse had been idle for at least 5 seconds because then the background caching thread should have started.
resolved fixed
afe057b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-29T21:06:30Z
2003-11-29T21:06:40Z
extension/org/eclipse/jdt/internal/corext/util/AllTypesCache.java
47,394
Bug 47394 Significant performance degradation in 3.x builds
I am currently using M5 we have a fairly large project approx 7000 source files split into about 250 packages plus about 20 jar files containing about 3MB of code. I am running on windows NT Service pack 6 with a 2Ghz processor and 1GB of RAM with vm params =-Xmx640m -Xms640m. Eclipse is running using JDK1.4.2_02. The problem I am facing is that build performance seems to have drastically slowed down in the 3.x builds compared to a 2.1 build. The entire UI and the machine seems to come to a stop when a build is occurring or when updating from a cvs sync. Keeping the progress view open I notice that there seems to be (too frequently) updates to the decorations during a build and the decoration update seems to take a very long time before the next task becomes active in the progress view. I notice that this also occurs when doing long operations like organize imports on an entire source tree. Maybe the decoration update could be delayed till the long operation is complete. The package explorer also seems to have slowed down. I have a package with about 80 sub packages each of which have 4 sub packages themselves. Just clicking on the expand of the package node of this package takes more than 35 secs.
resolved fixed
06c09ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-11-30T21:02:31Z
2003-11-25T08:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/WorkingSetFilterActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.workingsets; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IContributionItem; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IMemento; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetManager; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.jdt.internal.ui.search.WorkingSetComparator; /** * Working set filter actions (set / clear) * * @since 2.0 * */ public class WorkingSetFilterActionGroup extends ActionGroup { private static final String TAG_WORKING_SET_NAME= "workingSetName"; //$NON-NLS-1$ private static final String SEPARATOR_ID= "workingSetGroupSeparator"; //$NON-NLS-1$ private StructuredViewer fViewer; private WorkingSetFilter fWorkingSetFilter; private IWorkingSet fWorkingSet= null; private ClearWorkingSetAction fClearWorkingSetAction; private SelectWorkingSetAction fSelectWorkingSetAction; private EditWorkingSetAction fEditWorkingSetAction; private IPropertyChangeListener fTitleUpdater; private int fLRUMenuCount; private IMenuManager fMenuManager; private IMenuListener fMenuListener; public WorkingSetFilterActionGroup(StructuredViewer viewer, String viewId, Shell shell, IPropertyChangeListener titleUpdater) { Assert.isNotNull(viewer); Assert.isNotNull(viewId); Assert.isNotNull(shell); fViewer= viewer; fTitleUpdater= titleUpdater; fClearWorkingSetAction= new ClearWorkingSetAction(this); fSelectWorkingSetAction= new SelectWorkingSetAction(this, shell); fEditWorkingSetAction= new EditWorkingSetAction(this, shell); addWorkingSetChangeSupport(); } /** * Returns the working set which is used by the filter. * * @return the working set */ public IWorkingSet getWorkingSet() { return fWorkingSet; } /** * Sets this filter's working set. * * @param workingSet the working set * @param refreshViewer Indiactes if the viewer should be refreshed. */ public void setWorkingSet(IWorkingSet workingSet, boolean refreshViewer){ // Update action fClearWorkingSetAction.setEnabled(workingSet != null); fEditWorkingSetAction.setEnabled(workingSet != null); fWorkingSet= workingSet; // Update viewer if (fWorkingSetFilter != null) { fWorkingSetFilter.setWorkingSet(workingSet); if (refreshViewer) { fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } if (fTitleUpdater != null) fTitleUpdater.propertyChange(new PropertyChangeEvent(this, IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE, null, workingSet)); } } /** * Saves the state of the filter actions in a memento. */ public void saveState(IMemento memento) { String workingSetName= ""; //$NON-NLS-1$ if (fWorkingSet != null) workingSetName= fWorkingSet.getName(); memento.putString(TAG_WORKING_SET_NAME, workingSetName); } /** * Restores the state of the filter actions from a memento. * <p> * Note: This method does not refresh the viewer. * </p> * @param memento */ public void restoreState(IMemento memento) { String workingSetName= memento.getString(TAG_WORKING_SET_NAME); IWorkingSet ws= PlatformUI.getWorkbench().getWorkingSetManager().getWorkingSet(workingSetName); setWorkingSet(ws, false); } /* (non-Javadoc) * @see ActionGroup#fillActionBars(IActionBars) */ public void fillActionBars(IActionBars actionBars) { contributeToToolBar(actionBars.getToolBarManager()); contributeToMenu(actionBars.getMenuManager()); } /** * Adds the filter actions to the tool bar */ public void contributeToToolBar(IToolBarManager tbm) { // do nothing } /** * Adds the filter actions to the menu */ public void contributeToMenu(IMenuManager mm) { mm.add(fSelectWorkingSetAction); mm.add(fClearWorkingSetAction); mm.add(fEditWorkingSetAction); mm.add(new Separator()); mm.add(new Separator(SEPARATOR_ID)); addLRUWorkingSetActions(mm); fMenuManager= mm; fMenuListener= new IMenuListener() { public void menuAboutToShow(IMenuManager manager) { removePreviousLRUWorkingSetActions(manager); addLRUWorkingSetActions(manager); } }; fMenuManager.addMenuListener(fMenuListener); } private void removePreviousLRUWorkingSetActions(IMenuManager mm) { for (int i= 1; i <= fLRUMenuCount; i++) mm.remove(WorkingSetMenuContributionItem.getId(i)); } private void addLRUWorkingSetActions(IMenuManager mm) { IWorkingSet[] workingSets= PlatformUI.getWorkbench().getWorkingSetManager().getRecentWorkingSets(); List sortedWorkingSets= Arrays.asList(workingSets); Collections.sort(sortedWorkingSets, new WorkingSetComparator()); Iterator iter= sortedWorkingSets.iterator(); int i= 0; while (iter.hasNext()) { IWorkingSet workingSet= (IWorkingSet)iter.next(); if (workingSet != null) { IContributionItem item= new WorkingSetMenuContributionItem(++i, this, workingSet); mm.insertBefore(SEPARATOR_ID, item); } } fLRUMenuCount= i; } /* (non-Javadoc) * @see ActionGroup#dispose() */ public void dispose() { if (fMenuManager != null) fMenuManager.removeMenuListener(fMenuListener); super.dispose(); } private IPropertyChangeListener addWorkingSetChangeSupport() { final IPropertyChangeListener propertyChangeListener= createWorkingSetChangeListener(); fWorkingSetFilter= new WorkingSetFilter(); fViewer.addFilter(fWorkingSetFilter); // Register listener on working set manager PlatformUI.getWorkbench().getWorkingSetManager().addPropertyChangeListener(propertyChangeListener); // Register dispose listener which removes the listeners fViewer.getControl().addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { PlatformUI.getWorkbench().getWorkingSetManager().removePropertyChangeListener(propertyChangeListener); } }); return propertyChangeListener; } private IPropertyChangeListener createWorkingSetChangeListener() { return new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property= event.getProperty(); if (IWorkbenchPage.CHANGE_WORKING_SET_REPLACE.equals(property)) { IWorkingSet newWorkingSet= (IWorkingSet) event.getNewValue(); fWorkingSetFilter.setWorkingSet(newWorkingSet); fViewer.getControl().setRedraw(false); fViewer.refresh(); if (fTitleUpdater != null) fTitleUpdater.propertyChange(new PropertyChangeEvent(this, IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE, null, newWorkingSet)); fViewer.getControl().setRedraw(true); } else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) { if (fTitleUpdater != null) fTitleUpdater.propertyChange(event); } else if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } } }; } }
47,731
Bug 47731 JUnit view leaks 2 Colors
M5 Repeated opening and closing of the JUnit view leaks 2 SWT Colors each time
verified fixed
65a3a7a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T15:27:04Z
2003-11-28T20:06:40Z
org.eclipse.jdt.junit/src/org/eclipse/jdt/internal/junit/ui/JUnitProgressBar.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.junit.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ControlAdapter; import org.eclipse.swt.events.ControlEvent; import org.eclipse.swt.events.PaintEvent; import org.eclipse.swt.events.PaintListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; /** * A progress bar with a red/green indication for success or failure. */ public class JUnitProgressBar extends Canvas { private static final int DEFAULT_WIDTH = 160; private static final int DEFAULT_HEIGHT = 18; private int fCurrentTickCount= 0; private int fMaxTickCount= 0; private int fColorBarWidth= 0; private Color fOKColor; private Color fFailureColor; private boolean fError; public JUnitProgressBar(Composite parent) { super(parent, SWT.NONE); addControlListener(new ControlAdapter() { public void controlResized(ControlEvent e) { fColorBarWidth= scale(fCurrentTickCount); redraw(); } }); addPaintListener(new PaintListener() { public void paintControl(PaintEvent e) { paint(e); } }); Display display= parent.getDisplay(); fFailureColor= new Color(display, 223, 63, 63); fOKColor= new Color(display, 63, 127, 63); } public void setMaximum(int max) { fMaxTickCount= max; } public void reset() { fError= false; fCurrentTickCount= 0; fColorBarWidth= 0; fMaxTickCount= 0; redraw(); } private void paintStep(int startX, int endX) { GC gc = new GC(this); setStatusColor(gc); Rectangle rect= getClientArea(); startX= Math.max(1, startX); gc.fillRectangle(startX, 1, endX-startX, rect.height-2); gc.dispose(); } public void dispose() { super.dispose(); fFailureColor.dispose(); fOKColor.dispose(); } private void setStatusColor(GC gc) { if (fError) gc.setBackground(fFailureColor); else gc.setBackground(fOKColor); } private int scale(int value) { if (fMaxTickCount > 0) { Rectangle r= getClientArea(); if (r.width != 0) return Math.max(0, value*(r.width-2)/fMaxTickCount); } return value; } private void drawBevelRect(GC gc, int x, int y, int w, int h, Color topleft, Color bottomright) { gc.setForeground(topleft); gc.drawLine(x, y, x+w-1, y); gc.drawLine(x, y, x, y+h-1); gc.setForeground(bottomright); gc.drawLine(x+w, y, x+w, y+h); gc.drawLine(x, y+h, x+w, y+h); } private void paint(PaintEvent event) { GC gc = event.gc; Display disp= getDisplay(); Rectangle rect= getClientArea(); gc.fillRectangle(rect); drawBevelRect(gc, rect.x, rect.y, rect.width-1, rect.height-1, disp.getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW), disp.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW)); setStatusColor(gc); fColorBarWidth= Math.min(rect.width-2, fColorBarWidth); gc.fillRectangle(1, 1, fColorBarWidth, rect.height-2); } public Point computeSize(int wHint, int hHint, boolean changed) { checkWidget(); Point size= new Point(DEFAULT_WIDTH, DEFAULT_HEIGHT); if (wHint != SWT.DEFAULT) size.x= wHint; if (hHint != SWT.DEFAULT) size.y= hHint; return size; } public void step(int failures) { fCurrentTickCount++; int x= fColorBarWidth; fColorBarWidth= scale(fCurrentTickCount); if (!fError && failures > 0) { fError= true; x= 1; } if (fCurrentTickCount == fMaxTickCount) fColorBarWidth= getClientArea().width-1; paintStep(x, fColorBarWidth); } public void refresh(boolean hasErrors) { fError= hasErrors; redraw(); } }
42,068
Bug 42068 Pref Pages button order
The button order of: New.../Add... Edit... Remove Should be the same on the following preference pages: Classpath Variables Debug/Detail Formatter Editor/Templates Installed JREs Organize Imports Task Tags @@@ There should be no extra space on: Classpath Variables Task Tags @@@@ The "Up" and "Down" Buttons on Organize Imports should be placed after "New...", "Edit...", and "Remove" for consistency. There should be an extra space between "Remove" and "Enable All" on Debug/Step Filtering for consistency. There should be an extra space between "Remove" and "Search" on Installed JREs for consistency.
verified fixed
463cf6f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:27:54Z
2003-08-27T02:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/ImportOrganizePreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /* * The page for setting the organize import settings */ public class ImportOrganizePreferencePage extends PreferencePage implements IWorkbenchPreferencePage { private static final String PREF_IMPORTORDER= PreferenceConstants.ORGIMPORTS_IMPORTORDER; private static final String PREF_ONDEMANDTHRESHOLD= PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD; private static final String PREF_IGNORELOWERCASE= PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE; private static final String PREF_LASTLOADPATH= JavaUI.ID_PLUGIN + ".importorder.loadpath"; //$NON-NLS-1$ private static final String PREF_LASTSAVEPATH= JavaUI.ID_PLUGIN + ".importorder.savepath"; //$NON-NLS-1$ /** * @deprecated Inline to avoid reference to preference page */ public static String[] getImportOrderPreference() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); String str= prefs.getString(PREF_IMPORTORDER); if (str != null) { return unpackOrderList(str); } return new String[0]; } private static String[] unpackOrderList(String str) { StringTokenizer tok= new StringTokenizer(str, ";"); //$NON-NLS-1$ int nTokens= tok.countTokens(); String[] res= new String[nTokens]; for (int i= 0; i < nTokens; i++) { res[i]= tok.nextToken(); } return res; } private static String packOrderList(List orderList) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < orderList.size(); i++) { buf.append((String) orderList.get(i)); buf.append(';'); } return buf.toString(); } /** * @deprecated Inline to avoid reference to preference page */ public static int getImportNumberThreshold() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); int threshold= prefs.getInt(PREF_ONDEMANDTHRESHOLD); if (threshold < 0) { threshold= Integer.MAX_VALUE; } return threshold; } /** * @deprecated Inline to avoid reference to preference page */ public static boolean doIgnoreLowerCaseNames() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); return prefs.getBoolean(PREF_IGNORELOWERCASE); } private static class ImportOrganizeLabelProvider extends LabelProvider { private static final Image PCK_ICON= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_PACKAGE); public Image getImage(Object element) { return PCK_ICON; } } private class ImportOrganizeAdapter implements IListAdapter, IDialogFieldListener { private boolean canEdit(ListDialogField field) { return field.getSelectedElements().size() == 1; } public void customButtonPressed(ListDialogField field, int index) { doButtonPressed(index); } public void selectionChanged(ListDialogField field) { fOrderListField.enableButton(1, canEdit(field)); } public void dialogFieldChanged(DialogField field) { if (field == fThresholdField) { doThresholdChanged(); } } public void doubleClicked(ListDialogField field) { if (canEdit(field)) { doButtonPressed(1); } } } private ListDialogField fOrderListField; private StringDialogField fThresholdField; private SelectionButtonDialogField fIgnoreLowerCaseTypesField; public ImportOrganizePreferencePage() { super(); setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(PreferencesMessages.getString("ImportOrganizePreferencePage.description")); //$NON-NLS-1$ String[] buttonLabels= new String[] { /* 0 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.add.button"), //$NON-NLS-1$ /* 1 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.edit.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.up.button"), //$NON-NLS-1$ /* 4 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.down.button"), //$NON-NLS-1$ /* 5 */ null, /* 6 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.remove.button"), //$NON-NLS-1$ /* 7 */ null, /* 8 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.load.button"), //$NON-NLS-1$ /* 9 */ PreferencesMessages.getString("ImportOrganizePreferencePage.order.save.button") //$NON-NLS-1$ }; ImportOrganizeAdapter adapter= new ImportOrganizeAdapter(); fOrderListField= new ListDialogField(adapter, buttonLabels, new ImportOrganizeLabelProvider()); fOrderListField.setDialogFieldListener(adapter); fOrderListField.setLabelText(PreferencesMessages.getString("ImportOrganizePreferencePage.order.label")); //$NON-NLS-1$ fOrderListField.setUpButtonIndex(3); fOrderListField.setDownButtonIndex(4); fOrderListField.setRemoveButtonIndex(6); fOrderListField.enableButton(1, false); fThresholdField= new StringDialogField(); fThresholdField.setDialogFieldListener(adapter); fThresholdField.setLabelText(PreferencesMessages.getString("ImportOrganizePreferencePage.threshold.label")); //$NON-NLS-1$ fIgnoreLowerCaseTypesField= new SelectionButtonDialogField(SWT.CHECK); fIgnoreLowerCaseTypesField.setLabelText(PreferencesMessages.getString("ImportOrganizePreferencePage.ignoreLowerCase.label")); //$NON-NLS-1$ } /** * @see PreferencePage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.ORGANIZE_IMPORTS_PREFERENCE_PAGE); } protected Control createContents(Composite parent) { initializeDialogUnits(parent); initialize(getImportOrderPreference(), getImportNumberThreshold(), doIgnoreLowerCaseNames()); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.marginWidth= 0; layout.marginHeight= 0; composite.setLayout(layout); fOrderListField.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fOrderListField.getLabelControl(null), 2); LayoutUtil.setWidthHint(fOrderListField.getLabelControl(null), convertWidthInCharsToPixels(40)); LayoutUtil.setHorizontalGrabbing(fOrderListField.getListControl(null)); fThresholdField.doFillIntoGrid(composite, 2); ((GridData) fThresholdField.getTextControl(null).getLayoutData()).grabExcessHorizontalSpace= false; fIgnoreLowerCaseTypesField.doFillIntoGrid(composite, 2); Dialog.applyDialogFont(composite); return composite; } private void initialize(String[] importOrder, int threshold, boolean ignoreLowerCase) { fOrderListField.removeAllElements(); for (int i= 0; i < importOrder.length; i++) { fOrderListField.addElement(importOrder[i]); } fThresholdField.setText(String.valueOf(threshold)); fIgnoreLowerCaseTypesField.setSelection(ignoreLowerCase); } private void doThresholdChanged() { StatusInfo status= new StatusInfo(); String thresholdString= fThresholdField.getText(); try { int threshold= Integer.parseInt(thresholdString); if (threshold < 0) { status.setError(PreferencesMessages.getString("ImportOrganizePreferencePage.error.invalidthreshold")); //$NON-NLS-1$ } } catch (NumberFormatException e) { status.setError(PreferencesMessages.getString("ImportOrganizePreferencePage.error.invalidthreshold")); //$NON-NLS-1$ } updateStatus(status); } private void doButtonPressed(int index) { if (index == 0) { // add new List existing= fOrderListField.getElements(); ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing); if (dialog.open() == Window.OK) { fOrderListField.addElement(dialog.getResult()); } } else if (index == 1) { // edit List selected= fOrderListField.getSelectedElements(); if (selected.isEmpty()) { return; } String editedEntry= (String) selected.get(0); List existing= fOrderListField.getElements(); existing.remove(editedEntry); ImportOrganizeInputDialog dialog= new ImportOrganizeInputDialog(getShell(), existing); dialog.setInitialString(editedEntry); if (dialog.open() == Window.OK) { fOrderListField.replaceElement(editedEntry, dialog.getResult()); } } else if (index == 8) { // load List order= loadImportOrder(); if (order != null) { fOrderListField.setElements(order); } } else if (index == 9) { // save saveImportOrder(fOrderListField.getElements()); } } /** * The import order file is a property file. The keys are * "0", "1" ... last entry. The values must be valid package names. */ private List loadFromProperties(Properties properties) { ArrayList res= new ArrayList(); int nEntries= properties.size(); for (int i= 0 ; i < nEntries; i++) { String curr= properties.getProperty(String.valueOf(i)); if (curr != null) { if (!JavaConventions.validatePackageName(curr).matches(IStatus.ERROR)) { res.add(curr); } else { return null; } } else { return res; } } return res; } private List loadImportOrder() { FileDialog dialog= new FileDialog(getShell(), SWT.OPEN); dialog.setText(PreferencesMessages.getString("ImportOrganizePreferencePage.loadDialog.title")); //$NON-NLS-1$) dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ String lastPath= getPreferenceStore().getString(PREF_LASTLOADPATH); if (lastPath != null) { dialog.setFilterPath(lastPath); } String fileName= dialog.open(); if (fileName != null) { getPreferenceStore().putValue(PREF_LASTLOADPATH, dialog.getFilterPath()); Properties properties= new Properties(); FileInputStream fis= null; try { fis= new FileInputStream(fileName); properties.load(fis); List res= loadFromProperties(properties); if (res != null) { return res; } } catch (IOException e) { JavaPlugin.log(e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) {} } } String title= PreferencesMessages.getString("ImportOrganizePreferencePage.loadDialog.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("ImportOrganizePreferencePage.loadDialog.error.message"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); } return null; } private void saveImportOrder(List elements) { FileDialog dialog= new FileDialog(getShell(), SWT.SAVE); dialog.setText(PreferencesMessages.getString("ImportOrganizePreferencePage.saveDialog.title")); //$NON-NLS-1$) dialog.setFilterExtensions(new String[] {"*.importorder", "*.*"}); //$NON-NLS-1$ //$NON-NLS-2$ dialog.setFileName("example.importorder"); //$NON-NLS-1$ String lastPath= getPreferenceStore().getString(PREF_LASTSAVEPATH); if (lastPath != null) { dialog.setFilterPath(lastPath); } String fileName= dialog.open(); if (fileName != null) { getPreferenceStore().putValue(PREF_LASTSAVEPATH, dialog.getFilterPath()); Properties properties= new Properties(); for (int i= 0; i < elements.size(); i++) { properties.setProperty(String.valueOf(i), (String) elements.get(i)); } FileOutputStream fos= null; try { fos= new FileOutputStream(fileName); properties.store(fos, "Organize Import Order"); //$NON-NLS-1$ } catch (IOException e) { JavaPlugin.log(e); String title= PreferencesMessages.getString("ImportOrganizePreferencePage.saveDialog.error.title"); //$NON-NLS-1$ String message= PreferencesMessages.getString("ImportOrganizePreferencePage.saveDialog.error.message"); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) {} } } } } public void init(IWorkbench workbench) { } private void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } /** * @see PreferencePage#performDefaults() */ protected void performDefaults() { String[] order; IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); String str= prefs.getDefaultString(PREF_IMPORTORDER); if (str != null) { order= unpackOrderList(str); } else { order= new String[0]; } int threshold= prefs.getDefaultInt(PREF_ONDEMANDTHRESHOLD); if (threshold < 0) { threshold= Integer.MAX_VALUE; } boolean ignoreLowerCase= prefs.getDefaultBoolean(PREF_IGNORELOWERCASE); initialize(order, threshold, ignoreLowerCase); super.performDefaults(); } /** * @see org.eclipse.jface.preference.IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); prefs.setValue(PREF_IMPORTORDER, packOrderList(fOrderListField.getElements())); prefs.setValue(PREF_ONDEMANDTHRESHOLD, fThresholdField.getText()); prefs.setValue(PREF_IGNORELOWERCASE, fIgnoreLowerCaseTypesField.isSelected()); JavaPlugin.getDefault().savePluginPreferences(); return true; } }
42,068
Bug 42068 Pref Pages button order
The button order of: New.../Add... Edit... Remove Should be the same on the following preference pages: Classpath Variables Debug/Detail Formatter Editor/Templates Installed JREs Organize Imports Task Tags @@@ There should be no extra space on: Classpath Variables Task Tags @@@@ The "Up" and "Down" Buttons on Organize Imports should be placed after "New...", "Edit...", and "Remove" for consistency. There should be an extra space between "Remove" and "Enable All" on Debug/Step Filtering for consistency. There should be an extra space between "Remove" and "Search" on Installed JREs for consistency.
verified fixed
463cf6f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:27:54Z
2003-08-27T02:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/TodoTaskConfigurationBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; /** */ public class TodoTaskConfigurationBlock extends OptionsConfigurationBlock { private static final String PREF_COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String PREF_COMPILER_TASK_PRIORITIES= JavaCore.COMPILER_TASK_PRIORITIES; private static final String PRIORITY_HIGH= JavaCore.COMPILER_TASK_PRIORITY_HIGH; private static final String PRIORITY_NORMAL= JavaCore.COMPILER_TASK_PRIORITY_NORMAL; private static final String PRIORITY_LOW= JavaCore.COMPILER_TASK_PRIORITY_LOW; public static class TodoTask { public String name; public String priority; } private static class TodoTaskLabelProvider extends LabelProvider implements ITableLabelProvider { /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { return null; // JavaPluginImages.get(JavaPluginImages.IMG_OBJS_REFACTORING_INFO); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { return getColumnText(element, 0); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { return null; } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) */ public String getColumnText(Object element, int columnIndex) { TodoTask task= (TodoTask) element; if (columnIndex == 0) { return task.name; } else { if (PRIORITY_HIGH.equals(task.priority)) { return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.high.priority"); //$NON-NLS-1$ } else if (PRIORITY_NORMAL.equals(task.priority)) { return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.normal.priority"); //$NON-NLS-1$ } else if (PRIORITY_LOW.equals(task.priority)) { return PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.low.priority"); //$NON-NLS-1$ } return ""; //$NON-NLS-1$ } } } private IStatus fTaskTagsStatus; private ListDialogField fTodoTasksList; public TodoTaskConfigurationBlock(IStatusChangeListener context, IJavaProject project) { super(context, project); TaskTagAdapter adapter= new TaskTagAdapter(); String[] buttons= new String[] { /* 0 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.add.button"), //$NON-NLS-1$ /* 1 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.remove.button"), //$NON-NLS-1$ null, /* 3 */ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.edit.button"), //$NON-NLS-1$ }; fTodoTasksList= new ListDialogField(adapter, buttons, new TodoTaskLabelProvider()); fTodoTasksList.setDialogFieldListener(adapter); fTodoTasksList.setLabelText(PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.label")); //$NON-NLS-1$ fTodoTasksList.setRemoveButtonIndex(1); String[] columnsHeaders= new String[] { PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.name.column"), //$NON-NLS-1$ PreferencesMessages.getString("TodoTaskConfigurationBlock.markers.tasks.priority.column"), //$NON-NLS-1$ }; fTodoTasksList.setTableColumns(new ListDialogField.ColumnsDescription(columnsHeaders, true)); unpackTodoTasks(); if (fTodoTasksList.getSize() > 0) { fTodoTasksList.selectFirstElement(); } else { fTodoTasksList.enableButton(3, false); } fTaskTagsStatus= new StatusInfo(); } protected final String[] getAllKeys() { return new String[] { PREF_COMPILER_TASK_TAGS, PREF_COMPILER_TASK_PRIORITIES }; } public class TaskTagAdapter implements IListAdapter, IDialogFieldListener { private boolean canEdit(ListDialogField field) { return field.getSelectedElements().size() == 1; } public void customButtonPressed(ListDialogField field, int index) { doTodoButtonPressed(index); } public void selectionChanged(ListDialogField field) { field.enableButton(3, canEdit(field)); } public void doubleClicked(ListDialogField field) { if (canEdit(field)) { doTodoButtonPressed(3); } } public void dialogFieldChanged(DialogField field) { validateSettings(PREF_COMPILER_TASK_TAGS, null); } } protected Control createContents(Composite parent) { setShell(parent.getShell()); Composite markersComposite= createMarkersTabContent(parent); validateSettings(null, null); return markersComposite; } private Composite createMarkersTabContent(Composite folder) { GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; Composite markersComposite= new Composite(folder, SWT.NULL); markersComposite.setLayout(layout); fTodoTasksList.doFillIntoGrid(markersComposite, 3); LayoutUtil.setHorizontalSpan(fTodoTasksList.getLabelControl(null), 2); GridData data= (GridData)fTodoTasksList.getListControl(null).getLayoutData(); data.grabExcessHorizontalSpace= true; data.grabExcessVerticalSpace= true; data.verticalAlignment= GridData.FILL; //data.heightHint= SWTUtil.getTableHeightHint(table, 6); return markersComposite; } protected void validateSettings(String changedKey, String newValue) { if (changedKey != null) { if (PREF_COMPILER_TASK_TAGS.equals(changedKey)) { fTaskTagsStatus= validateTaskTags(); } else { return; } } else { fTaskTagsStatus= validateTaskTags(); } IStatus status= fTaskTagsStatus; //StatusUtil.getMostSevere(new IStatus[] { fTaskTagsStatus }); fContext.statusChanged(status); } private IStatus validateTaskTags() { return new StatusInfo(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean) */ public boolean performOk(boolean enabled) { packTodoTasks(); return super.performOk(enabled); } protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { String title= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsbuild.title"); //$NON-NLS-1$ String message; if (fProject == null) { message= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsfullbuild.message"); //$NON-NLS-1$ } else { message= PreferencesMessages.getString("TodoTaskConfigurationBlock.needsprojectbuild.message"); //$NON-NLS-1$ } return new String[] { title, message }; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls() */ protected void updateControls() { unpackTodoTasks(); } private void unpackTodoTasks() { String currTags= (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS); String currPrios= (String) fWorkingValues.get(PREF_COMPILER_TASK_PRIORITIES); String[] tags= getTokens(currTags, ","); //$NON-NLS-1$ String[] prios= getTokens(currPrios, ","); //$NON-NLS-1$ ArrayList elements= new ArrayList(tags.length); for (int i= 0; i < tags.length; i++) { TodoTask task= new TodoTask(); task.name= tags[i].trim(); task.priority= (i < prios.length) ? prios[i] : PRIORITY_NORMAL; elements.add(task); } fTodoTasksList.setElements(elements); } private void packTodoTasks() { StringBuffer tags= new StringBuffer(); StringBuffer prios= new StringBuffer(); List list= fTodoTasksList.getElements(); for (int i= 0; i < list.size(); i++) { if (i > 0) { tags.append(','); prios.append(','); } TodoTask elem= (TodoTask) list.get(i); tags.append(elem.name); prios.append(elem.priority); } fWorkingValues.put(PREF_COMPILER_TASK_TAGS, tags.toString()); fWorkingValues.put(PREF_COMPILER_TASK_PRIORITIES, prios.toString()); } private void doTodoButtonPressed(int index) { TodoTask edited= null; if (index != 0) { edited= (TodoTask) fTodoTasksList.getSelectedElements().get(0); } TodoTaskInputDialog dialog= new TodoTaskInputDialog(getShell(), edited, fTodoTasksList.getElements()); if (dialog.open() == Window.OK) { if (edited != null) { fTodoTasksList.replaceElement(edited, dialog.getResult()); } else { fTodoTasksList.addElement(dialog.getResult()); } } } }
42,068
Bug 42068 Pref Pages button order
The button order of: New.../Add... Edit... Remove Should be the same on the following preference pages: Classpath Variables Debug/Detail Formatter Editor/Templates Installed JREs Organize Imports Task Tags @@@ There should be no extra space on: Classpath Variables Task Tags @@@@ The "Up" and "Down" Buttons on Organize Imports should be placed after "New...", "Edit...", and "Remove" for consistency. There should be an extra space between "Remove" and "Enable All" on Debug/Step Filtering for consistency. There should be an extra space between "Remove" and "Search" on Installed JREs for consistency.
verified fixed
463cf6f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:27:54Z
2003-08-27T02:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariableBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.SubProgressMonitor; 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.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class VariableBlock { private ListDialogField fVariablesList; private Control fControl; private List fSelectedElements; private boolean fAskToBuild; private boolean fInPreferencePage; /** * Constructor for VariableBlock */ public VariableBlock(boolean inPreferencePage, String initSelection) { fSelectedElements= new ArrayList(0); fInPreferencePage= inPreferencePage; fAskToBuild= true; String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("VariableBlock.vars.add.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("VariableBlock.vars.edit.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("VariableBlock.vars.remove.button") //$NON-NLS-1$ }; VariablesAdapter adapter= new VariablesAdapter(); CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(!inPreferencePage); fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider); fVariablesList.setDialogFieldListener(adapter); fVariablesList.setLabelText(NewWizardMessages.getString("VariableBlock.vars.label")); //$NON-NLS-1$ fVariablesList.setRemoveButtonIndex(3); fVariablesList.enableButton(1, false); fVariablesList.setViewerSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) { return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName()); } return super.compare(viewer, e1, e2); } }); CPVariableElement initSelectedElement= null; String[] reservedName= getReservedVariableNames(); ArrayList reserved= new ArrayList(reservedName.length); addAll(reservedName, reserved); String[] entries= JavaCore.getClasspathVariableNames(); ArrayList elements= new ArrayList(entries.length); for (int i= 0; i < entries.length; i++) { String name= entries[i]; CPVariableElement elem; IPath entryPath= JavaCore.getClasspathVariable(name); if (entryPath != null) { elem= new CPVariableElement(name, entryPath, reserved.contains(name)); elements.add(elem); if (name.equals(initSelection)) { initSelectedElement= elem; } } else { JavaPlugin.logErrorMessage("VariableBlock: Classpath variable with null value: " + name); //$NON-NLS-1$ } } fVariablesList.setElements(elements); if (initSelectedElement != null) { ISelection sel= new StructuredSelection(initSelectedElement); fVariablesList.selectElements(sel); } else { fVariablesList.selectFirstElement(); } } private String[] getReservedVariableNames() { return new String[] { JavaRuntime.JRELIB_VARIABLE, JavaRuntime.JRESRC_VARIABLE, JavaRuntime.JRESRCROOT_VARIABLE, }; } public Control createContents(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fVariablesList }, true, 0, 0); LayoutUtil.setHorizontalGrabbing(fVariablesList.getListControl(null)); fControl= composite; return composite; } public void addDoubleClickListener(IDoubleClickListener listener) { fVariablesList.getTableViewer().addDoubleClickListener(listener); } public void addSelectionChangedListener(ISelectionChangedListener listener) { fVariablesList.getTableViewer().addSelectionChangedListener(listener); } private Shell getShell() { if (fControl != null) { return fControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class VariablesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(ListDialogField field, int index) { switch (index) { case 0: /* add */ editEntries(null); break; case 1: /* edit */ List selected= field.getSelectedElements(); editEntries((CPVariableElement)selected.get(0)); break; } } public void selectionChanged(ListDialogField field) { doSelectionChanged(field); } public void doubleClicked(ListDialogField field) { if (fInPreferencePage) { List selected= field.getSelectedElements(); if (canEdit(selected, containsReserved(selected))) { editEntries((CPVariableElement) selected.get(0)); } } } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { } } private boolean containsReserved(List selected) { for (int i= selected.size()-1; i >= 0; i--) { if (((CPVariableElement)selected.get(i)).isReserved()) { return true; } } return false; } private static void addAll(Object[] objs, Collection dest) { for (int i= 0; i < objs.length; i++) { dest.add(objs[i]); } } private boolean canEdit(List selected, boolean containsReserved) { return selected.size() == 1 && !containsReserved; } private void doSelectionChanged(DialogField field) { List selected= fVariablesList.getSelectedElements(); boolean containsReserved= containsReserved(selected); // edit fVariablesList.enableButton(1, canEdit(selected, containsReserved)); // remove button fVariablesList.enableButton(3, !containsReserved); fSelectedElements= selected; } private void editEntries(CPVariableElement entry) { List existingEntries= fVariablesList.getElements(); VariableCreationDialog dialog= new VariableCreationDialog(getShell(), entry, existingEntries); if (dialog.open() != Window.OK) { return; } CPVariableElement newEntry= dialog.getClasspathElement(); if (entry == null) { fVariablesList.addElement(newEntry); entry= newEntry; } else { entry.setName(newEntry.getName()); entry.setPath(newEntry.getPath()); fVariablesList.refresh(); } fVariablesList.selectElements(new StructuredSelection(entry)); } public List getSelectedElements() { return fSelectedElements; } public void performDefaults() { fVariablesList.removeAllElements(); String[] reservedName= getReservedVariableNames(); for (int i= 0; i < reservedName.length; i++) { CPVariableElement elem= new CPVariableElement(reservedName[i], Path.EMPTY, true); elem.setReserved(true); fVariablesList.addElement(elem); } } public boolean performOk() { ArrayList removedVariables= new ArrayList(); ArrayList changedVariables= new ArrayList(); removedVariables.addAll(Arrays.asList(JavaCore.getClasspathVariableNames())); // remove all unchanged List changedElements= fVariablesList.getElements(); for (int i= changedElements.size()-1; i >= 0; i--) { CPVariableElement curr= (CPVariableElement) changedElements.get(i); if (curr.isReserved()) { changedElements.remove(curr); } else { IPath path= curr.getPath(); IPath prevPath= JavaCore.getClasspathVariable(curr.getName()); if (prevPath != null && prevPath.equals(path)) { changedElements.remove(curr); } else { changedVariables.add(curr.getName()); } } removedVariables.remove(curr.getName()); } int steps= changedElements.size() + removedVariables.size(); if (steps > 0) { boolean needsBuild= false; if (fAskToBuild && doesChangeRequireFullBuild(removedVariables, changedVariables)) { String title= NewWizardMessages.getString("VariableBlock.needsbuild.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("VariableBlock.needsbuild.message"); //$NON-NLS-1$ MessageDialog buildDialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); int res= buildDialog.open(); if (res != 0 && res != 1) { return false; } needsBuild= (res == 0); } IRunnableWithProgress runnable= new VariableBlockRunnable(removedVariables, changedElements, needsBuild); ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, runnable); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), NewWizardMessages.getString("VariableBlock.operation_errror.title"), NewWizardMessages.getString("VariableBlock.operation_errror.message")); //$NON-NLS-1$ //$NON-NLS-2$ return false; } catch (InterruptedException e) { return true; } } return true; } private boolean doesChangeRequireFullBuild(List removed, List changed) { try { IJavaModel model= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); IJavaProject[] projects= model.getJavaProjects(); for (int i= 0; i < projects.length; i++) { IClasspathEntry[] entries= projects[i].getRawClasspath(); for (int k= 0; k < entries.length; k++) { IClasspathEntry curr= entries[k]; if (curr.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { String var= curr.getPath().segment(0); if (removed.contains(var) || changed.contains(var)) { return true; } } } } } catch (JavaModelException e) { return true; } return false; } private class VariableBlockRunnable implements IRunnableWithProgress { private List fToRemove; private List fToChange; private boolean fDoBuild; public VariableBlockRunnable(List toRemove, List toChange, boolean doBuild) { fToRemove= toRemove; fToChange= toChange; fDoBuild= doBuild; } /* * @see IRunnableWithProgress#run(IProgressMonitor) */ public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("VariableBlock.operation_desc"), fDoBuild ? 2 : 1); //$NON-NLS-1$ try { int nVariables= fToChange.size() + fToRemove.size(); String[] names= new String[nVariables]; IPath[] paths= new IPath[nVariables]; int k= 0; for (int i= 0; i < fToChange.size(); i++) { CPVariableElement curr= (CPVariableElement) fToChange.get(i); names[k]= curr.getName(); paths[k]= curr.getPath(); k++; } for (int i= 0; i < fToRemove.size(); i++) { names[k]= (String) fToRemove.get(i); paths[k]= null; k++; } JavaCore.setClasspathVariables(names, paths, new SubProgressMonitor(monitor, 1)); if (fDoBuild) { JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, new SubProgressMonitor(monitor, 1)); } } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } } /** * If set to true, a dialog will ask the user to build on variable changed * @param askToBuild The askToBuild to set */ public void setAskToBuild(boolean askToBuild) { fAskToBuild= askToBuild; } /** * */ public void refresh() { int nElements= fVariablesList.getSize(); for (int i= 0; i < nElements; i++) { CPVariableElement curr= (CPVariableElement) fVariablesList.getElement(i); IPath entryPath= JavaCore.getClasspathVariable(curr.getName()); if (entryPath != null) { curr.setPath(entryPath); } else { curr.setPath(Path.EMPTY); } } fVariablesList.refresh(); } }
42,068
Bug 42068 Pref Pages button order
The button order of: New.../Add... Edit... Remove Should be the same on the following preference pages: Classpath Variables Debug/Detail Formatter Editor/Templates Installed JREs Organize Imports Task Tags @@@ There should be no extra space on: Classpath Variables Task Tags @@@@ The "Up" and "Down" Buttons on Organize Imports should be placed after "New...", "Edit...", and "Remove" for consistency. There should be an extra space between "Remove" and "Enable All" on Debug/Step Filtering for consistency. There should be an extra space between "Remove" and "Search" on Installed JREs for consistency.
verified fixed
463cf6f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:27:54Z
2003-08-27T02:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/dialogfields/ListDialogField.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.dialogfields; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ColumnLayoutData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredContentProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.TableLayout; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.util.TableLayoutComposite; /** * A list with a button bar. * Typical buttons are 'Add', 'Remove', 'Up' and 'Down'. * List model is independend of widget creation. * DialogFields controls are: Label, List and Composite containing buttons. */ public class ListDialogField extends DialogField { public static class ColumnsDescription { private ColumnLayoutData[] columns; private String[] headers; private boolean drawLines; public ColumnsDescription(ColumnLayoutData[] columns, String[] headers, boolean drawLines) { this.columns= columns; this.headers= headers; this.drawLines= drawLines; } public ColumnsDescription(String[] headers, boolean drawLines) { this(createColumnWeightData(headers.length), headers, drawLines); } public ColumnsDescription(int nColumns, boolean drawLines) { this(createColumnWeightData(nColumns), null, drawLines); } private static ColumnLayoutData[] createColumnWeightData(int nColumns) { ColumnLayoutData[] data= new ColumnLayoutData[nColumns]; for (int i= 0; i < nColumns; i++) { data[i]= new ColumnWeightData(1); } return data; } } protected TableViewer fTable; protected ILabelProvider fLabelProvider; protected ListViewerAdapter fListViewerAdapter; protected List fElements; protected ViewerSorter fViewerSorter; protected String[] fButtonLabels; private Button[] fButtonControls; private boolean[] fButtonsEnabled; private int fRemoveButtonIndex; private int fUpButtonIndex; private int fDownButtonIndex; private Label fLastSeparator; private Control fTableControl; private Composite fButtonsControl; private ISelection fSelectionWhenEnabled; private IListAdapter fListAdapter; private Object fParentElement; private ColumnsDescription fTableColumns; /** * Creates the <code>ListDialogField</code>. * @param adapter A listener for button invocation, selection changes. Can * be <code>null</code>. * @param buttonLabels The labels of all buttons: <code>null</code> is a valid array entry and * marks a separator. * @param lprovider The label provider to render the table entries */ public ListDialogField(IListAdapter adapter, String[] buttonLabels, ILabelProvider lprovider) { super(); fListAdapter= adapter; fLabelProvider= lprovider; fListViewerAdapter= new ListViewerAdapter(); fParentElement= this; fElements= new ArrayList(10); fButtonLabels= buttonLabels; if (fButtonLabels != null) { int nButtons= fButtonLabels.length; fButtonsEnabled= new boolean[nButtons]; for (int i= 0; i < nButtons; i++) { fButtonsEnabled[i]= true; } } fTable= null; fTableControl= null; fButtonsControl= null; fTableColumns= null; fRemoveButtonIndex= -1; fUpButtonIndex= -1; fDownButtonIndex= -1; } /** * Sets the index of the 'remove' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'remove' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setRemoveButtonIndex(int removeButtonIndex) { Assert.isTrue(removeButtonIndex < fButtonLabels.length); fRemoveButtonIndex= removeButtonIndex; } /** * Sets the index of the 'up' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'up' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setUpButtonIndex(int upButtonIndex) { Assert.isTrue(upButtonIndex < fButtonLabels.length); fUpButtonIndex= upButtonIndex; } /** * Sets the index of the 'down' button in the button label array passed in the constructor. * The behaviour of the button marked as the 'down' button will then be handled internally. * (enable state, button invocation behaviour) */ public void setDownButtonIndex(int downButtonIndex) { Assert.isTrue(downButtonIndex < fButtonLabels.length); fDownButtonIndex= downButtonIndex; } /** * Sets the viewerSorter. * @param viewerSorter The viewerSorter to set */ public void setViewerSorter(ViewerSorter viewerSorter) { fViewerSorter= viewerSorter; } public void setTableColumns(ColumnsDescription column) { fTableColumns= column; } // ------ adapter communication private void buttonPressed(int index) { if (!managedButtonPressed(index) && fListAdapter != null) { fListAdapter.customButtonPressed(this, index); } } /** * Checks if the button pressed is handled internally * @return Returns true if button has been handled. */ protected boolean managedButtonPressed(int index) { if (index == fRemoveButtonIndex) { remove(); } else if (index == fUpButtonIndex) { up(); } else if (index == fDownButtonIndex) { down(); } else { return false; } return true; } // ------ layout helpers /* * @see DialogField#doFillIntoGrid */ public Control[] doFillIntoGrid(Composite parent, int nColumns) { PixelConverter converter= new PixelConverter(parent); assertEnoughColumns(nColumns); Label label= getLabelControl(parent); GridData gd= gridDataForLabel(1); gd.verticalAlignment= GridData.BEGINNING; label.setLayoutData(gd); Control list= getListControl(parent); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= GridData.FILL; gd.grabExcessVerticalSpace= true; gd.horizontalSpan= nColumns - 2; gd.widthHint= converter.convertWidthInCharsToPixels(50); gd.heightHint= converter.convertHeightInCharsToPixels(6); list.setLayoutData(gd); Composite buttons= getButtonBox(parent); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= false; gd.verticalAlignment= GridData.FILL; gd.grabExcessVerticalSpace= true; gd.horizontalSpan= 1; buttons.setLayoutData(gd); return new Control[] { label, list, buttons }; } /* * @see DialogField#getNumberOfControls */ public int getNumberOfControls() { return 3; } /** * Sets the minimal width of the buttons. Must be called after widget creation. */ public void setButtonsMinWidth(int minWidth) { if (fLastSeparator != null) { ((GridData)fLastSeparator.getLayoutData()).widthHint= minWidth; } } // ------ ui creation /** * Returns the list control. When called the first time, the control will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Control getListControl(Composite parent) { if (fTableControl == null) { assertCompositeNotNull(parent); if (fTableColumns == null) { fTable= createTableViewer(parent); Table tableControl= fTable.getTable(); fTableControl= tableControl; tableControl.setLayout(new TableLayout()); } else { TableLayoutComposite composite= new TableLayoutComposite(parent, SWT.NONE); fTableControl= composite; fTable= createTableViewer(composite); Table tableControl= fTable.getTable(); tableControl.setHeaderVisible(fTableColumns.headers != null); tableControl.setLinesVisible(fTableColumns.drawLines); ColumnLayoutData[] columns= fTableColumns.columns; for (int i= 0; i < columns.length; i++) { composite.addColumnData(columns[i]); TableColumn column= new TableColumn(tableControl, SWT.NONE); //tableLayout.addColumnData(columns[i]); if (fTableColumns.headers != null) { column.setText(fTableColumns.headers[i]); } } } fTable.getTable().addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { handleKeyPressed(e); } }); //fTableControl.setLayout(tableLayout); fTable.setContentProvider(fListViewerAdapter); fTable.setLabelProvider(fLabelProvider); fTable.addSelectionChangedListener(fListViewerAdapter); fTable.addDoubleClickListener(fListViewerAdapter); fTable.setInput(fParentElement); if (fViewerSorter != null) { fTable.setSorter(fViewerSorter); } fTableControl.setEnabled(isEnabled()); if (fSelectionWhenEnabled != null) { postSetSelection(fSelectionWhenEnabled); } } return fTableControl; } /** * Returns the internally used table viewer. */ public TableViewer getTableViewer() { return fTable; } /* * Subclasses may override to specify a different style. */ protected int getListStyle(){ int style= SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL ; if (fTableColumns != null) { style |= SWT.FULL_SELECTION; } return style; } protected TableViewer createTableViewer(Composite parent) { Table table= new Table(parent, getListStyle()); return new TableViewer(table); } protected Button createButton(Composite parent, String label, SelectionListener listener) { Button button= new Button(parent, SWT.PUSH); button.setText(label); button.addSelectionListener(listener); GridData gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.grabExcessHorizontalSpace= true; gd.verticalAlignment= GridData.BEGINNING; gd.heightHint = SWTUtil.getButtonHeightHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); return button; } private Label createSeparator(Composite parent) { Label separator= new Label(parent, SWT.NONE); separator.setVisible(false); GridData gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.verticalAlignment= GridData.BEGINNING; gd.heightHint= 4; separator.setLayoutData(gd); return separator; } /** * Returns the composite containing the buttons. When called the first time, the control * will be created. * @param The parent composite when called the first time, or <code>null</code> * after. */ public Composite getButtonBox(Composite parent) { if (fButtonsControl == null) { assertCompositeNotNull(parent); SelectionListener listener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { doButtonSelected(e); } public void widgetSelected(SelectionEvent e) { doButtonSelected(e); } }; Composite contents= new Composite(parent, SWT.NULL); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; contents.setLayout(layout); if (fButtonLabels != null) { fButtonControls= new Button[fButtonLabels.length]; for (int i= 0; i < fButtonLabels.length; i++) { String currLabel= fButtonLabels[i]; if (currLabel != null) { fButtonControls[i]= createButton(contents, currLabel, listener); fButtonControls[i].setEnabled(isEnabled() && fButtonsEnabled[i]); } else { fButtonControls[i]= null; createSeparator(contents); } } } fLastSeparator= createSeparator(contents); updateButtonState(); fButtonsControl= contents; } return fButtonsControl; } private void doButtonSelected(SelectionEvent e) { if (fButtonControls != null) { for (int i= 0; i < fButtonControls.length; i++) { if (e.widget == fButtonControls[i]) { buttonPressed(i); return; } } } } /** * Handles key events in the table viewer. Specifically * when the delete key is pressed. */ protected void handleKeyPressed(KeyEvent event) { if (event.character == SWT.DEL && event.stateMask == 0) { if (fRemoveButtonIndex != -1 && isButtonEnabled(fTable.getSelection(), fRemoveButtonIndex)) { managedButtonPressed(fRemoveButtonIndex); } } } // ------ enable / disable management /* * @see DialogField#dialogFieldChanged */ public void dialogFieldChanged() { super.dialogFieldChanged(); updateButtonState(); } /* * Updates the enable state of the all buttons */ protected void updateButtonState() { if (fButtonControls != null) { ISelection sel= fTable.getSelection(); for (int i= 0; i < fButtonControls.length; i++) { Button button= fButtonControls[i]; if (isOkToUse(button)) { button.setEnabled(isButtonEnabled(sel, i)); } } } } protected boolean getManagedButtonState(ISelection sel, int index) { if (index == fRemoveButtonIndex) { return !sel.isEmpty(); } else if (index == fUpButtonIndex) { return !sel.isEmpty() && canMoveUp(); } else if (index == fDownButtonIndex) { return !sel.isEmpty() && canMoveDown(); } return true; } /* * @see DialogField#updateEnableState */ protected void updateEnableState() { super.updateEnableState(); boolean enabled= isEnabled(); if (isOkToUse(fTableControl)) { if (!enabled) { fSelectionWhenEnabled= fTable.getSelection(); selectElements(null); } else { selectElements(fSelectionWhenEnabled); fSelectionWhenEnabled= null; } fTableControl.setEnabled(enabled); } updateButtonState(); } /** * Sets a button enabled or disabled. */ public void enableButton(int index, boolean enable) { if (fButtonsEnabled != null && index < fButtonsEnabled.length) { fButtonsEnabled[index]= enable; updateButtonState(); } } private boolean isButtonEnabled(ISelection sel, int index) { boolean extraState= getManagedButtonState(sel, index); return isEnabled() && extraState && fButtonsEnabled[index]; } // ------ model access /** * Sets the elements shown in the list. */ public void setElements(List elements) { fElements= new ArrayList(elements); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } /** * Gets the elements shown in the list. * The list returned is a copy, so it can be modified by the user. */ public List getElements() { return new ArrayList(fElements); } /** * Gets the elements shown at the given index. */ public Object getElement(int index) { return fElements.get(index); } /** * Gets the index of an element in the list or -1 if element is not in list. */ public int getIndexOfElement(Object elem) { return fElements.indexOf(elem); } /** * Replace an element. */ public void replaceElement(Object oldElement, Object newElement) throws IllegalArgumentException { int idx= fElements.indexOf(oldElement); if (idx != -1) { fElements.set(idx, newElement); if (fTable != null) { List selected= getSelectedElements(); if (selected.remove(oldElement)) { selected.add(newElement); } fTable.refresh(); selectElements(new StructuredSelection(selected)); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Adds an element at the end of the list. */ public void addElement(Object element) { if (fElements.contains(element)) { return; } fElements.add(element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds elements at the end of the list. */ public void addElements(List elements) { int nElements= elements.size(); if (nElements > 0) { // filter duplicated ArrayList elementsToAdd= new ArrayList(nElements); for (int i= 0; i < nElements; i++) { Object elem= elements.get(i); if (!fElements.contains(elem)) { elementsToAdd.add(elem); } } fElements.addAll(elementsToAdd); if (fTable != null) { fTable.add(elementsToAdd.toArray()); } dialogFieldChanged(); } } /** * Adds an element at a position. */ public void insertElementAt(Object element, int index) { if (fElements.contains(element)) { return; } fElements.add(index, element); if (fTable != null) { fTable.add(element); } dialogFieldChanged(); } /** * Adds an element at a position. */ public void removeAllElements() { if (fElements.size() > 0) { fElements.clear(); if (fTable != null) { fTable.refresh(); } dialogFieldChanged(); } } /** * Removes an element from the list. */ public void removeElement(Object element) throws IllegalArgumentException { if (fElements.remove(element)) { if (fTable != null) { fTable.remove(element); } dialogFieldChanged(); } else { throw new IllegalArgumentException(); } } /** * Removes elements from the list. */ public void removeElements(List elements) { if (elements.size() > 0) { fElements.removeAll(elements); if (fTable != null) { fTable.remove(elements.toArray()); } dialogFieldChanged(); } } /** * Gets the number of elements */ public int getSize() { return fElements.size(); } public void selectElements(ISelection selection) { fSelectionWhenEnabled= selection; if (fTable != null) { fTable.setSelection(selection, true); } } public void selectFirstElement() { Object element= null; if (fViewerSorter != null) { Object[] arr= fElements.toArray(); fViewerSorter.sort(fTable, arr); if (arr.length > 0) { element= arr[0]; } } else { if (fElements.size() > 0) { element= fElements.get(0); } } if (element != null) { selectElements(new StructuredSelection(element)); } } public void postSetSelection(final ISelection selection) { if (isOkToUse(fTableControl)) { Display d= fTableControl.getDisplay(); d.asyncExec(new Runnable() { public void run() { if (isOkToUse(fTableControl)) { selectElements(selection); } } }); } } /** * Refreshes the table. */ public void refresh() { if (fTable != null) { fTable.refresh(); } } // ------- list maintenance private List moveUp(List elements, List move) { int nElements= elements.size(); List res= new ArrayList(nElements); Object floating= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (move.contains(curr)) { res.add(curr); } else { if (floating != null) { res.add(floating); } floating= curr; } } if (floating != null) { res.add(floating); } return res; } private void moveUp(List toMoveUp) { if (toMoveUp.size() > 0) { setElements(moveUp(fElements, toMoveUp)); fTable.reveal(toMoveUp.get(0)); } } private void moveDown(List toMoveDown) { if (toMoveDown.size() > 0) { setElements(reverse(moveUp(reverse(fElements), toMoveDown))); fTable.reveal(toMoveDown.get(toMoveDown.size() - 1)); } } private List reverse(List p) { List reverse= new ArrayList(p.size()); for (int i= p.size()-1; i >= 0; i--) { reverse.add(p.get(i)); } return reverse; } private void remove() { removeElements(getSelectedElements()); } private void up() { moveUp(getSelectedElements()); } private void down() { moveDown(getSelectedElements()); } private boolean canMoveUp() { if (isOkToUse(fTableControl)) { int[] indc= fTable.getTable().getSelectionIndices(); for (int i= 0; i < indc.length; i++) { if (indc[i] != i) { return true; } } } return false; } private boolean canMoveDown() { if (isOkToUse(fTableControl)) { int[] indc= fTable.getTable().getSelectionIndices(); int k= fElements.size() - 1; for (int i= indc.length - 1; i >= 0 ; i--, k--) { if (indc[i] != k) { return true; } } } return false; } /** * Returns the selected elements. */ public List getSelectedElements() { List result= new ArrayList(); if (fTable != null) { ISelection selection= fTable.getSelection(); if (selection instanceof IStructuredSelection) { Iterator iter= ((IStructuredSelection)selection).iterator(); while (iter.hasNext()) { result.add(iter.next()); } } } return result; } // ------- ListViewerAdapter private class ListViewerAdapter implements IStructuredContentProvider, ISelectionChangedListener, IDoubleClickListener { // ------- ITableContentProvider Interface ------------ public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { // will never happen } public boolean isDeleted(Object element) { return false; } public void dispose() { } public Object[] getElements(Object obj) { return fElements.toArray(); } // ------- ISelectionChangedListener Interface ------------ public void selectionChanged(SelectionChangedEvent event) { doListSelected(event); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.IDoubleClickListener#doubleClick(org.eclipse.jface.viewers.DoubleClickEvent) */ public void doubleClick(DoubleClickEvent event) { doDoubleClick(event); } } protected void doListSelected(SelectionChangedEvent event) { updateButtonState(); if (fListAdapter != null) { fListAdapter.selectionChanged(this); } } protected void doDoubleClick(DoubleClickEvent event) { if (fListAdapter != null) { fListAdapter.doubleClicked(this); } } }
42,214
Bug 42214 New template variable that gets replaced by file name w/o extension [code manipulation]
I would like there to be a template variable, for example "filename", that works like the "file" variable, except the variable's value doesn't contain the file extension. This would allow me to create template such as the following: public final class ${filename} extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(${filename}.class); ... } ... }
resolved fixed
74443d8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:33:13Z
2003-08-28T14:13:20Z
org.eclipse.jdt.ui/core
42,214
Bug 42214 New template variable that gets replaced by file name w/o extension [code manipulation]
I would like there to be a template variable, for example "filename", that works like the "file" variable, except the variable's value doesn't contain the file extension. This would allow me to create template such as the following: public final class ${filename} extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(${filename}.class); ... } ... }
resolved fixed
74443d8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:33:13Z
2003-08-28T14:13:20Z
extension/org/eclipse/jdt/internal/corext/template/java/CompilationUnitContextType.java
42,214
Bug 42214 New template variable that gets replaced by file name w/o extension [code manipulation]
I would like there to be a template variable, for example "filename", that works like the "file" variable, except the variable's value doesn't contain the file extension. This would allow me to create template such as the following: public final class ${filename} extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(${filename}.class); ... } ... }
resolved fixed
74443d8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:33:13Z
2003-08-28T14:13:20Z
org.eclipse.jdt.ui/core
42,214
Bug 42214 New template variable that gets replaced by file name w/o extension [code manipulation]
I would like there to be a template variable, for example "filename", that works like the "file" variable, except the variable's value doesn't contain the file extension. This would allow me to create template such as the following: public final class ${filename} extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(${filename}.class); ... } ... }
resolved fixed
74443d8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:33:13Z
2003-08-28T14:13:20Z
extension/org/eclipse/jdt/internal/corext/template/java/JavaContextType.java
42,214
Bug 42214 New template variable that gets replaced by file name w/o extension [code manipulation]
I would like there to be a template variable, for example "filename", that works like the "file" variable, except the variable's value doesn't contain the file extension. This would allow me to create template such as the following: public final class ${filename} extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(${filename}.class); ... } ... }
resolved fixed
74443d8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:33:13Z
2003-08-28T14:13:20Z
org.eclipse.jdt.ui/core
42,214
Bug 42214 New template variable that gets replaced by file name w/o extension [code manipulation]
I would like there to be a template variable, for example "filename", that works like the "file" variable, except the variable's value doesn't contain the file extension. This would allow me to create template such as the following: public final class ${filename} extends TestCase { public static Test suite() { final TestSuite suite = new TestSuite(${filename}.class); ... } ... }
resolved fixed
74443d8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-01T19:33:13Z
2003-08-28T14:13:20Z
extension/org/eclipse/jdt/internal/corext/template/java/JavaDocContextType.java
47,873
Bug 47873 Extract Method: should generate Javadoc [refactoring]
I20031126 Title says it all.
resolved fixed
1d8f5d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:15:41Z
2003-12-02T10:13:20Z
org.eclipse.jdt.ui/core
47,873
Bug 47873 Extract Method: should generate Javadoc [refactoring]
I20031126 Title says it all.
resolved fixed
1d8f5d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:15:41Z
2003-12-02T10:13:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/code/ExtractMethodRefactoring.java
47,873
Bug 47873 Extract Method: should generate Javadoc [refactoring]
I20031126 Title says it all.
resolved fixed
1d8f5d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:15:41Z
2003-12-02T10:13:20Z
org.eclipse.jdt.ui/ui
47,873
Bug 47873 Extract Method: should generate Javadoc [refactoring]
I20031126 Title says it all.
resolved fixed
1d8f5d2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:15:41Z
2003-12-02T10:13:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java
46,923
Bug 46923 Introduce Factory: Preview doesn't work sometimes
I20031119 The preview doesn't work when introducing a factory method on this example: public class HelloWorld { private static HelloWorld instance; public static void main(String [] args) { instance= new HelloWorld(); instance.run(); } private HelloWorld() { } private void run() { } } The factory method is introduced correctly, though. It must have something to do with the constructor being private; if it is public, the preview appears as expected.
resolved fixed
955406c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:51:42Z
2003-11-19T11:06:40Z
org.eclipse.jdt.ui/core
46,923
Bug 46923 Introduce Factory: Preview doesn't work sometimes
I20031119 The preview doesn't work when introducing a factory method on this example: public class HelloWorld { private static HelloWorld instance; public static void main(String [] args) { instance= new HelloWorld(); instance.run(); } private HelloWorld() { } private void run() { } } The factory method is introduced correctly, though. It must have something to do with the constructor being private; if it is public, the preview appears as expected.
resolved fixed
955406c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:51:42Z
2003-11-19T11:06:40Z
extension/org/eclipse/jdt/internal/corext/textmanipulation/GroupDescription.java
46,923
Bug 46923 Introduce Factory: Preview doesn't work sometimes
I20031119 The preview doesn't work when introducing a factory method on this example: public class HelloWorld { private static HelloWorld instance; public static void main(String [] args) { instance= new HelloWorld(); instance.run(); } private HelloWorld() { } private void run() { } } The factory method is introduced correctly, though. It must have something to do with the constructor being private; if it is public, the preview appears as expected.
resolved fixed
955406c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:51:42Z
2003-11-19T11:06:40Z
org.eclipse.jdt.ui/core
46,923
Bug 46923 Introduce Factory: Preview doesn't work sometimes
I20031119 The preview doesn't work when introducing a factory method on this example: public class HelloWorld { private static HelloWorld instance; public static void main(String [] args) { instance= new HelloWorld(); instance.run(); } private HelloWorld() { } private void run() { } } The factory method is introduced correctly, though. It must have something to do with the constructor being private; if it is public, the preview appears as expected.
resolved fixed
955406c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:51:42Z
2003-11-19T11:06:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/changes/TextChange.java
46,923
Bug 46923 Introduce Factory: Preview doesn't work sometimes
I20031119 The preview doesn't work when introducing a factory method on this example: public class HelloWorld { private static HelloWorld instance; public static void main(String [] args) { instance= new HelloWorld(); instance.run(); } private HelloWorld() { } private void run() { } } The factory method is introduced correctly, though. It must have something to do with the constructor being private; if it is public, the preview appears as expected.
resolved fixed
955406c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:51:42Z
2003-11-19T11:06:40Z
org.eclipse.jdt.ui/ui
46,923
Bug 46923 Introduce Factory: Preview doesn't work sometimes
I20031119 The preview doesn't work when introducing a factory method on this example: public class HelloWorld { private static HelloWorld instance; public static void main(String [] args) { instance= new HelloWorld(); instance.run(); } private HelloWorld() { } private void run() { } } The factory method is introduced correctly, though. It must have something to do with the constructor being private; if it is public, the preview appears as expected.
resolved fixed
955406c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T13:51:42Z
2003-11-19T11:06:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeElementContentProvider.java
47,922
Bug 47922 Double-click does not go into resource folders [package explorer]
build I20031121 - In a self-hosting workspace with UI in source, - On the Java pref page, change the double-click behavior for the package explorer to Go Into. - In the Package Explorer, double-click on org.eclipse.ui. - It goes into the project. - Double-click on the schema folder. - It has no effect. It should go into it. - Choose Go Into from the context menu. - It goes into it OK
resolved fixed
34080e8
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T14:04:45Z
2003-12-02T21:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.swt.SWT; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Shell; 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.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.ActionFactory; 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.FrameAction; import org.eclipse.ui.views.framelist.FrameList; import org.eclipse.ui.views.framelist.GoIntoAction; import org.eclipse.ui.views.framelist.UpAction; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IOpenable; 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.NavigateActionGroup; import org.eclipse.jdt.ui.actions.ProjectActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup; 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 ToggleLinkingAction fToggleLinkingAction; private NavigateActionGroup fNavigateActionGroup; private BuildActionGroup fBuildActionGroup; private CCPActionGroup fCCPActionGroup; private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup; 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; TreeViewer viewer= part.getViewer(); IPropertyChangeListener workingSetListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doWorkingSetChanged(event); } }; 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 GenerateActionGroup(fPart), new RefactorActionGroup(fPart), new ImportActionGroup(fPart), fBuildActionGroup= new BuildActionGroup(fPart), new JavaSearchActionGroup(fPart), new ProjectActionGroup(fPart), fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(JavaUI.ID_PACKAGES, shell, workingSetListener), fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, viewer), new LayoutActionGroup(part)}); viewer.addFilter(fWorkingSetFilterActionGroup.getWorkingSetFilter()); 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); fToggleLinkingAction = new ToggleLinkingAction(fPart); provider.addSelectionChangedListener(this); update(selection); fLastElement= INIT; } public void dispose() { 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(ActionFactory.RENAME.getId(), fRenameResourceAction); actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), fMoveResourceAction); actionBars.updateActionBars(); fLastElement= RESOURCE; } } else { if (fLastElement != REST) { actionBars.setGlobalActionHandler(ActionFactory.RENAME.getId(), null); actionBars.setGlobalActionHandler(ActionFactory.MOVE.getId(), null); actionBars.updateActionBars(); fLastElement= REST; } } } //---- Persistent state ----------------------------------------------------------------------- /* package */ void restoreFilterAndSorterState(IMemento memento) { fWorkingSetFilterActionGroup.restoreState(memento); fCustomFiltersActionGroup.restoreState(memento); } /* package */ void saveFilterAndSorterState(IMemento 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(); fZoomInAction.setEnabled(true); } private void setGlobalActionHandlers(IActionBars actionBars) { // Navigate Go Into and Go To actions. actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction); actionBars.setGlobalActionHandler(ActionFactory.BACK.getId(), fBackAction); actionBars.setGlobalActionHandler(ActionFactory.FORWARD.getId(), 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); toolBar.add(fToggleLinkingAction); } /* package */ void fillViewMenu(IMenuManager menu) { menu.add(fToggleLinkingAction); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ } /* package */ void handleSelectionChanged(SelectionChangedEvent event) { } //---- 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) { boolean enabled= size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer); fZoomInAction.setEnabled(enabled); if (enabled) 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 { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled() && 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 void doWorkingSetChanged(PropertyChangeEvent event) { IWorkingSet workingSet= (IWorkingSet) event.getNewValue(); String workingSetName= null; if (workingSet != null) workingSetName= workingSet.getName(); fPart.setWorkingSetName(workingSetName); fPart.updateTitle(); String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { TreeViewer viewer= fPart.getViewer(); viewer.getControl().setRedraw(false); viewer.refresh(); viewer.getControl().setRedraw(true); } } private boolean doubleClickGoesInto() { return PreferenceConstants.DOUBLE_CLICK_GOES_INTO.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.DOUBLE_CLICK)); } public FrameAction getUpAction() { return fUpAction; } public FrameAction getBackAction() { return fBackAction; } public FrameAction getForwardAction() { return fForwardAction; } }
47,971
Bug 47971 java formatter preferences: IllegalArgumentException when opening new formatter page
I20031202 0. Have old formatter preferences specifying to use spaces instead of tabs 1. Create a new formatting style based on "Java Conventions" 2. Set Indentation -> Use Tab character 3. Format some code so its indentation gets changed -> Note that spaces get inserted instead of tabs 4. Go to the Preferences, Java->Code Formatter -> IllegalArgumentException, stack trace below !ENTRY org.eclipse.jface 4 2 Dec 03, 2003 11:53:48.224 !MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface". !STACK 0 java.lang.IllegalArgumentException at org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock$ControlData.getSelection(OptionsConfigurationBlock.java:83) at org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock.addCheckBox(OptionsConfigurationBlock.java:172) at org.eclipse.jdt.internal.ui.preferences.CodeFormatterConfigurationBlock.createContents(CodeFormatterConfigurationBlock.java:210) at org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage.createContents(CodeFormatterPreferencePage.java:96) at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:217) at org.eclipse.jdt.internal.ui.preferences.CodeFormatterPreferencePage.createControl(CodeFormatterPreferencePage.java:84) at org.eclipse.jface.preference.PreferenceDialog$12.run(PreferenceDialog.java:986) at org.eclipse.core.internal.runtime.InternalPlatform.run(InternalPlatform.java:824) at org.eclipse.core.runtime.Platform.run(Platform.java:479) at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:984) at org.eclipse.jface.preference.PreferenceDialog.selectSavedItem(PreferenceDialog.java:670) at org.eclipse.jface.preference.PreferenceDialog$3.run(PreferenceDialog.java:297) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:84) at org.eclipse.jface.preference.PreferenceDialog.createContents(PreferenceDialog.java:292) at org.eclipse.jface.window.Window.create(Window.java:305) at org.eclipse.jface.dialogs.Dialog.create(Dialog.java:883) at org.eclipse.ui.internal.OpenPreferencesAction.run(OpenPreferencesAction.java:70) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:535) at org.eclipse.jface.action.ActionContributionItem.access$4(ActionContributionItem.java:487) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent(ActionContributionItem.java:459) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1839) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1619) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
79f0f9b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T14:18:51Z
2003-12-03T14:00:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/formatter/IndentationTabPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences.formatter; import java.util.Map; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Group; import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants; public class IndentationTabPage extends ModifyDialogTabPage { private final String PREVIEW= "/**\n" + "* Indentation\n" + "*/\n\n" + "class Example {" + " void foo(int parameter) {" + " switch(parameter) {" + " case 0: " + " o.doFoo();" + " break;" + " default:" + " o.doBaz();" + " }" + " }" + " void bar(Vector v) {" + " for (int i= 0; i < 10; i++) {" + " v.add(new Integer(i));" + " }" + " }" + "}"; private final int numColumns= 4; public IndentationTabPage(Map workingValues) { super(workingValues); fJavaPreview.setPreviewText(PREVIEW); } protected Composite doCreatePreferences(Composite parent) { final Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(createGridLayout(numColumns, false)); final Group generalGroup= createGroup(numColumns, composite, "General settings"); createNumberPref(generalGroup, numColumns, "Tab si&ze:", DefaultCodeFormatterConstants.FORMATTER_TAB_SIZE, 0, Integer.MAX_VALUE); createNumberPref(generalGroup, numColumns, "Initi&al indentation level:", DefaultCodeFormatterConstants.FORMATTER_INITIAL_INDENTATION_LEVEL, 0, Integer.MAX_VALUE); createNumberPref(generalGroup, numColumns, "De&fault indentation for wrapped lines:", DefaultCodeFormatterConstants.FORMATTER_CONTINUATION_INDENTATION, 0, Integer.MAX_VALUE); createCheckboxPref(generalGroup, numColumns, "U&se tab character", DefaultCodeFormatterConstants.FORMATTER_TAB_CHAR, falseTrue); final Group classGroup = createGroup(numColumns, composite, "Class body"); createCheckboxPref(classGroup, numColumns, "Indent de&clarations within class body", DefaultCodeFormatterConstants.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER, falseTrue); final Group blockGroup= createGroup(numColumns, composite, "Block body"); createCheckboxPref(blockGroup, numColumns, "Indent statements wit&hin blocks and methods", DefaultCodeFormatterConstants.FORMATTER_INDENT_BLOCK_STATEMENTS, falseTrue); final Group switchGroup= createGroup(numColumns, composite, "Switch statement"); createCheckboxPref(switchGroup, numColumns, "Indent statements within 's&witch' body", DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_CASES, falseTrue); createCheckboxPref(switchGroup, numColumns, "Indent statements within 'case' bod&y", DefaultCodeFormatterConstants.FORMATTER_INDENT_SWITCHSTATEMENTS_COMPARE_TO_SWITCH, falseTrue); createCheckboxPref(switchGroup, numColumns, "Indent 'brea&k' statements", DefaultCodeFormatterConstants.FORMATTER_INDENT_BREAKS_COMPARE_TO_CASES, falseTrue); return composite; } }
48,001
Bug 48001 Don't want 'e' as variable name in throw clause
M5 'Surround with' refactoring and quick fix use 'e' as exception variable name. It should be possible to configure this
resolved fixed
25a25f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:09:37Z
2003-12-03T16:46:40Z
org.eclipse.jdt.ui/core
48,001
Bug 48001 Don't want 'e' as variable name in throw clause
M5 'Surround with' refactoring and quick fix use 'e' as exception variable name. It should be possible to configure this
resolved fixed
25a25f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:09:37Z
2003-12-03T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/surround/SurroundWithTryCatchRefactoring.java
48,001
Bug 48001 Don't want 'e' as variable name in throw clause
M5 'Surround with' refactoring and quick fix use 'e' as exception variable name. It should be possible to configure this
resolved fixed
25a25f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:09:37Z
2003-12-03T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/NameConventionConfigurationBlock.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Table; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.viewers.ColumnLayoutData; import org.eclipse.jface.viewers.ColumnWeightData; import org.eclipse.jface.viewers.ITableLabelProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /* * The page to configure name conventions */ public class NameConventionConfigurationBlock extends OptionsConfigurationBlock { private final static int FIELD= 1; private final static int STATIC= 2; private final static int ARGUMENT= 3; private final static int LOCAL= 4; // Preference store keys, see JavaCore.getOptions private static final String PREF_FIELD_PREFIXES= JavaCore.CODEASSIST_FIELD_PREFIXES; private static final String PREF_FIELD_SUFFIXES= JavaCore.CODEASSIST_FIELD_SUFFIXES; private static final String PREF_STATIC_FIELD_PREFIXES= JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES; private static final String PREF_STATIC_FIELD_SUFFIXES= JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES; private static final String PREF_ARGUMENT_PREFIXES= JavaCore.CODEASSIST_ARGUMENT_PREFIXES; private static final String PREF_ARGUMENT_SUFFIXES= JavaCore.CODEASSIST_ARGUMENT_SUFFIXES; private static final String PREF_LOCAL_PREFIXES= JavaCore.CODEASSIST_LOCAL_PREFIXES; private static final String PREF_LOCAL_SUFFIXES= JavaCore.CODEASSIST_LOCAL_SUFFIXES; private static class NameConventionEntry { public int kind; public String prefix; public String suffix; public String prefixkey; public String suffixkey; } private class NameConventionInputDialog extends StatusDialog implements IDialogFieldListener { private StringDialogField fPrefixField; private StringDialogField fSuffixField; private NameConventionEntry fEntry; private DialogField fMessageField; public NameConventionInputDialog(Shell parent, String title, String message, NameConventionEntry entry) { super(parent); fEntry= entry; setTitle(title); fMessageField= new DialogField(); fMessageField.setLabelText(message); fPrefixField= new StringDialogField(); fPrefixField.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.dialog.prefix")); //$NON-NLS-1$ fPrefixField.setDialogFieldListener(this); fSuffixField= new StringDialogField(); fSuffixField.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.dialog.suffix")); //$NON-NLS-1$ fSuffixField.setDialogFieldListener(this); fPrefixField.setText(entry.prefix); fSuffixField.setText(entry.suffix); } public NameConventionEntry getResult() { NameConventionEntry res= new NameConventionEntry(); res.prefix= fPrefixField.getText(); res.suffix= fSuffixField.getText(); res.prefixkey= fEntry.prefixkey; res.suffixkey= fEntry.suffixkey; res.kind= fEntry.kind; return res; } protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; inner.setLayout(layout); fMessageField.doFillIntoGrid(inner, 2); fPrefixField.doFillIntoGrid(inner, 2); fSuffixField.doFillIntoGrid(inner, 2); LayoutUtil.setHorizontalGrabbing(fPrefixField.getTextControl(null)); LayoutUtil.setWidthHint(fPrefixField.getTextControl(null), convertWidthInCharsToPixels(45)); LayoutUtil.setWidthHint(fSuffixField.getTextControl(null), convertWidthInCharsToPixels(45)); fPrefixField.postSetFocusOnDialogField(parent.getDisplay()); applyDialogFont(composite); return composite; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener#dialogFieldChanged(org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField) */ public void dialogFieldChanged(DialogField field) { // validate IStatus prefixStatus= validateIdentifiers(getTokens(fPrefixField.getText(), ","), true); //$NON-NLS-1$ IStatus suffixStatus= validateIdentifiers(getTokens(fSuffixField.getText(), ","), false); //$NON-NLS-1$ updateStatus(StatusUtil.getMoreSevere(suffixStatus, prefixStatus)); } private IStatus validateIdentifiers(String[] values, boolean prefix) { for (int i= 0; i < values.length; i++) { String val= values[i]; if (val.length() == 0) { if (prefix) { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("NameConventionConfigurationBlock.error.emptyprefix")); //$NON-NLS-1$ } else { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getString("NameConventionConfigurationBlock.error.emptysuffix")); //$NON-NLS-1$ } } String name= prefix ? val + "x" : "x" + val; //$NON-NLS-2$ //$NON-NLS-1$ IStatus status= JavaConventions.validateFieldName(name); if (status.matches(IStatus.ERROR)) { if (prefix) { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("NameConventionConfigurationBlock.error.invalidprefix", val)); //$NON-NLS-1$ } else { return new StatusInfo(IStatus.ERROR, PreferencesMessages.getFormattedString("NameConventionConfigurationBlock.error.invalidsuffix", val)); //$NON-NLS-1$ } } } return new StatusInfo(); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); //WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.IMPORT_ORGANIZE_INPUT_DIALOG); } } private static class NameConventionLabelProvider extends LabelProvider implements ITableLabelProvider { /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { return getColumnImage(element, 0); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) */ public String getText(Object element) { return getColumnText(element, 0); } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int) */ public Image getColumnImage(Object element, int columnIndex) { if (columnIndex != 0) { return null; } NameConventionEntry entry= (NameConventionEntry) element; ImageDescriptorRegistry registry= JavaPlugin.getImageDescriptorRegistry(); switch (entry.kind) { case FIELD: return registry.get(JavaPluginImages.DESC_FIELD_PUBLIC); case STATIC: return registry.get(new JavaElementImageDescriptor(JavaPluginImages.DESC_FIELD_PUBLIC, JavaElementImageDescriptor.STATIC, JavaElementImageProvider.SMALL_SIZE)); case ARGUMENT: return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE); default: return registry.get(JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE); } } /* (non-Javadoc) * @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int) */ public String getColumnText(Object element, int columnIndex) { NameConventionEntry entry= (NameConventionEntry) element; if (columnIndex == 0) { switch (entry.kind) { case FIELD: return PreferencesMessages.getString("NameConventionConfigurationBlock.field.label"); //$NON-NLS-1$ case STATIC: return PreferencesMessages.getString("NameConventionConfigurationBlock.static.label"); //$NON-NLS-1$ case ARGUMENT: return PreferencesMessages.getString("NameConventionConfigurationBlock.arg.label"); //$NON-NLS-1$ default: return PreferencesMessages.getString("NameConventionConfigurationBlock.local.label"); //$NON-NLS-1$ } } else if (columnIndex == 1) { return entry.prefix; } else { return entry.suffix; } } } private class NameConventionAdapter implements IListAdapter, IDialogFieldListener { private boolean canEdit(ListDialogField field) { return field.getSelectedElements().size() == 1; } public void customButtonPressed(ListDialogField field, int index) { doEditButtonPressed(); } public void selectionChanged(ListDialogField field) { field.enableButton(0, canEdit(field)); } public void doubleClicked(ListDialogField field) { if (canEdit(field)) { doEditButtonPressed(); } } public void dialogFieldChanged(DialogField field) { validateSettings(null, null); } } private ListDialogField fNameConventionList; private SelectionButtonDialogField fUseKeywordThisBox; private SelectionButtonDialogField fUseIsForBooleanGettersBox; private static final String PREF_KEYWORD_THIS= PreferenceConstants.CODEGEN_KEYWORD_THIS; private static final String PREF_IS_FOR_GETTERS= PreferenceConstants.CODEGEN_IS_FOR_GETTERS; public NameConventionConfigurationBlock(IStatusChangeListener context, IJavaProject project) { super(context, project); NameConventionAdapter adapter= new NameConventionAdapter(); String[] buttons= new String[] { /* 0 */ PreferencesMessages.getString("NameConventionConfigurationBlock.list.edit.button") //$NON-NLS-1$ }; fNameConventionList= new ListDialogField(adapter, buttons, new NameConventionLabelProvider()); fNameConventionList.setDialogFieldListener(adapter); fNameConventionList.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.list.label")); //$NON-NLS-1$ String[] columnsHeaders= new String[] { PreferencesMessages.getString("NameConventionConfigurationBlock.list.name.column"), //$NON-NLS-1$ PreferencesMessages.getString("NameConventionConfigurationBlock.list.prefix.column"), //$NON-NLS-1$ PreferencesMessages.getString("NameConventionConfigurationBlock.list.suffix.column"), //$NON-NLS-1$ }; ColumnLayoutData[] data= new ColumnLayoutData[] { new ColumnWeightData(3), new ColumnWeightData(2), new ColumnWeightData(2) }; fNameConventionList.setTableColumns(new ListDialogField.ColumnsDescription(data, columnsHeaders, true)); unpackEntries(); if (fNameConventionList.getSize() > 0) { fNameConventionList.selectFirstElement(); } else { fNameConventionList.enableButton(0, false); } // https://bugs.eclipse.org/bugs/show_bug.cgi?id=38879 fUseKeywordThisBox= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); fUseKeywordThisBox.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.keywordthis.label")); //$NON-NLS-1$ fUseKeywordThisBox.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_KEYWORD_THIS)); // https://bugs.eclipse.org/bugs/show_bug.cgi?id=39044 fUseIsForBooleanGettersBox= new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); fUseIsForBooleanGettersBox.setLabelText(PreferencesMessages.getString("NameConventionConfigurationBlock.isforbooleangetters.label")); //$NON-NLS-1$ fUseIsForBooleanGettersBox.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_IS_FOR_GETTERS)); } protected String[] getAllKeys() { return new String[] { PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES, PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES }; } protected Control createContents(Composite parent) { setShell(parent.getShell()); GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite composite= new Composite(parent, SWT.NONE); composite.setLayout(layout); fNameConventionList.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fNameConventionList.getLabelControl(null), 2); Table table= fNameConventionList.getTableViewer().getTable(); GridData data= (GridData)fNameConventionList.getListControl(null).getLayoutData(); data.heightHint= SWTUtil.getTableHeightHint(table, 5); data.grabExcessHorizontalSpace= true; data.verticalAlignment= GridData.BEGINNING; data.grabExcessVerticalSpace= false; data= (GridData)fNameConventionList.getButtonBox(null).getLayoutData(); data.grabExcessVerticalSpace= false; data.verticalAlignment= GridData.BEGINNING; fUseKeywordThisBox.doFillIntoGrid(composite, 2); fUseIsForBooleanGettersBox.doFillIntoGrid(composite, 2); return composite; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#validateSettings(java.lang.String, java.lang.String) */ protected void validateSettings(String changedKey, String newValue) { // no validation } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#updateControls() */ protected void updateControls() { unpackEntries(); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#getFullBuildDialogStrings(boolean) */ protected String[] getFullBuildDialogStrings(boolean workspaceSettings) { return null; // no build required } private void createEntry(List list, String prefixKey, String suffixKey, int kind) { NameConventionEntry entry= new NameConventionEntry(); entry.kind= kind; entry.suffixkey= suffixKey; entry.prefixkey= prefixKey; entry.suffix= (String) fWorkingValues.get(suffixKey); entry.prefix= (String) fWorkingValues.get(prefixKey); list.add(entry); } private void unpackEntries() { ArrayList list= new ArrayList(4); createEntry(list, PREF_FIELD_PREFIXES, PREF_FIELD_SUFFIXES, FIELD); createEntry(list, PREF_STATIC_FIELD_PREFIXES, PREF_STATIC_FIELD_SUFFIXES, STATIC); createEntry(list, PREF_ARGUMENT_PREFIXES, PREF_ARGUMENT_SUFFIXES, ARGUMENT); createEntry(list, PREF_LOCAL_PREFIXES, PREF_LOCAL_SUFFIXES, LOCAL); fNameConventionList.setElements(list); } private void packEntries() { for (int i= 0; i < fNameConventionList.getSize(); i++) { NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getElement(i); fWorkingValues.put(entry.suffixkey, entry.suffix); fWorkingValues.put(entry.prefixkey, entry.prefix); } } private void doEditButtonPressed() { NameConventionEntry entry= (NameConventionEntry) fNameConventionList.getSelectedElements().get(0); String title; String message; switch (entry.kind) { case FIELD: title= PreferencesMessages.getString("NameConventionConfigurationBlock.field.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.field.dialog.message"); //$NON-NLS-1$ break; case STATIC: title= PreferencesMessages.getString("NameConventionConfigurationBlock.static.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.static.dialog.message"); //$NON-NLS-1$ break; case ARGUMENT: title= PreferencesMessages.getString("NameConventionConfigurationBlock.arg.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.arg.dialog.message"); //$NON-NLS-1$ break; default: title= PreferencesMessages.getString("NameConventionConfigurationBlock.local.dialog.title"); //$NON-NLS-1$ message= PreferencesMessages.getString("NameConventionConfigurationBlock.local.dialog.message"); //$NON-NLS-1$ } NameConventionInputDialog dialog= new NameConventionInputDialog(getShell(), title, message, entry); if (dialog.open() == Window.OK) { fNameConventionList.replaceElement(entry, dialog.getResult()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performDefaults() */ public void performDefaults() { super.performDefaults(); IPreferenceStore prefs= JavaPlugin.getDefault().getPreferenceStore(); fUseKeywordThisBox.setSelection(prefs.getDefaultBoolean(PREF_KEYWORD_THIS)); fUseIsForBooleanGettersBox.setSelection(prefs.getDefaultBoolean(PREF_IS_FOR_GETTERS)); } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.preferences.OptionsConfigurationBlock#performOk(boolean) */ public boolean performOk(boolean enabled) { IPreferenceStore prefs= PreferenceConstants.getPreferenceStore(); prefs.setValue(PREF_KEYWORD_THIS, fUseKeywordThisBox.isSelected()); prefs.setValue(PREF_IS_FOR_GETTERS, fUseIsForBooleanGettersBox.isSelected()); JavaPlugin.getDefault().savePluginPreferences(); packEntries(); return super.performOk(enabled); } }
48,001
Bug 48001 Don't want 'e' as variable name in throw clause
M5 'Surround with' refactoring and quick fix use 'e' as exception variable name. It should be possible to configure this
resolved fixed
25a25f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:09:37Z
2003-12-03T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - Access to static proposal ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.Collection; import java.util.List; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.PrimitiveType.Code; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.NewASTRewrite; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil; import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; 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.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter; import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard; /** */ public class LocalCorrectionsSubProcessor { public static void addCastProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { String[] args= problem.getProblemArguments(); if (args.length != 2) { return; } ICompilationUnit cu= context.getCompilationUnit(); String castType= args[1]; CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (!(selectedNode instanceof Expression)) { return; } Expression nodeToCast= (Expression) selectedNode; int parentNodeType= selectedNode.getParent().getNodeType(); if (parentNodeType == ASTNode.ASSIGNMENT) { Assignment assign= (Assignment) selectedNode.getParent(); if (selectedNode.equals(assign.getLeftHandSide())) { nodeToCast= assign.getRightHandSide(); } } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent(); if (selectedNode.equals(frag.getName())) { nodeToCast= frag.getInitializer(); } } ITypeBinding binding= nodeToCast.resolveTypeBinding(); if (binding == null || canCast(castType, binding)) { proposals.add(createCastProposal(context, castType, nodeToCast, 5)); } ITypeBinding currBinding= nodeToCast.resolveTypeBinding(); if (currBinding == null || "void".equals(currBinding.getName())) { //$NON-NLS-1$ return; } // change method return statement to actual type if (parentNodeType == ASTNode.RETURN_STATEMENT) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) decl; currBinding= Bindings.normalizeTypeBinding(currBinding); if (currBinding == null) { currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } ASTRewrite rewrite= new ASTRewrite(methodDeclaration); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", currBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); String returnTypeName= proposal.addImport(currBinding); Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName); rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType); String returnKey= "return"; //$NON-NLS-1$ proposal.markAsLinked(rewrite, newReturnType, true, returnKey); ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(astRoot.getAST(), currBinding); for (int i= 0; i < typeSuggestions.length; i++) { proposal.addLinkedModeProposal(returnKey, typeSuggestions[i]); } proposal.ensureNoModifications(); proposals.add(proposal); } } if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent(); ASTNode parent= fragment.getParent(); Type typeNode= null; if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent; if (stmt.fragments().size() == 1) { typeNode= stmt.getType(); } } else if (parent instanceof FieldDeclaration) { FieldDeclaration decl= (FieldDeclaration) parent; if (decl.fragments().size() == 1) { typeNode= decl.getType(); } } if (typeNode != null) { currBinding= Bindings.normalizeTypeBinding(currBinding); if (currBinding == null) { currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } TextBuffer buffer= null; try { buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource()); ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String typeName= importRewrite.addImport(currBinding); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changevartype.description", typeName); //$NON-NLS-1$ ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, typeNode.getStartPosition(), typeNode.getLength(), typeName, 5); varProposal.getRootTextEdit().addChild(importRewrite.createEdit(buffer)); proposals.add(varProposal); } finally { if (buffer != null) TextBuffer.release(buffer); } } } } private static boolean canCast(String castTarget, ITypeBinding bindingToCast) { bindingToCast= Bindings.normalizeTypeBinding(bindingToCast); if (bindingToCast == null) { return false; } int arrStart= castTarget.indexOf('['); if (arrStart != -1) { if (!bindingToCast.isArray()) { return "java.lang.Object".equals(bindingToCast.getQualifiedName()); //$NON-NLS-1$ } castTarget= castTarget.substring(0, arrStart); bindingToCast= bindingToCast.getElementType(); if (bindingToCast.isPrimitive() && !castTarget.equals(bindingToCast.getName())) { return false; // can't cast arrays of primitive types into each other } } Code targetCode= PrimitiveType.toCode(castTarget); if (bindingToCast.isPrimitive()) { Code castCode= PrimitiveType.toCode(bindingToCast.getName()); if (castCode == targetCode) { return true; } return (targetCode != null && targetCode != PrimitiveType.BOOLEAN && castCode != PrimitiveType.BOOLEAN); } else { return targetCode == null; // can not check } } public static ASTRewriteCorrectionProposal createCastProposal(IInvocationContext context, String castType, Expression nodeToCast, int relevance) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent()); String label; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, relevance, image); //$NON-NLS-1$ String simpleCastType= proposal.addImport(castType); if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) { label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$ CastExpression expression= (CastExpression) nodeToCast; rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, NewASTRewrite.TYPE)); } else { label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$ Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast); int nodeType= nodeToCast.getNodeType(); if (nodeType == ASTNode.INFIX_EXPRESSION || nodeType == ASTNode.CONDITIONAL_EXPRESSION || nodeType == ASTNode.ASSIGNMENT || nodeType == ASTNode.INSTANCEOF_EXPRESSION) { // nodes have weaker precedence than cast ParenthesizedExpression parenthesizedExpression= astRoot.getAST().newParenthesizedExpression(); parenthesizedExpression.setExpression(expressionCopy); expressionCopy= parenthesizedExpression; } Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, NewASTRewrite.TYPE); CastExpression castExpression= astRoot.getAST().newCastExpression(); castExpression.setExpression(expressionCopy); castExpression.setType(typeCopy); rewrite.markAsReplaced(nodeToCast, castExpression); } proposal.setDisplayName(label); proposal.ensureNoModifications(); return proposal; } public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } while (selectedNode != null && !(selectedNode instanceof Statement)) { selectedNode= selectedNode.getParent(); } if (selectedNode == null) { return; } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null); if (refactoring == null) return; refactoring.setSaveChanges(false); if (refactoring.checkActivationBasics(astRoot, null).isOK()) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image); proposals.add(proposal); } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl == null) { return; } ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength())); if (uncaughtExceptions.length == 0) { return; } TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode); if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) { ASTRewrite rewrite= new ASTRewrite(surroundingTry); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 5, image); AST ast= astRoot.getAST(); List catchClauses= surroundingTry.catchClauses(); for (int i= 0; i < uncaughtExceptions.length; i++) { ITypeBinding excBinding= uncaughtExceptions[i]; String varName= "e"; //$NON-NLS-1$ String imp= proposal.addImport(excBinding); Name name= ASTNodeFactory.newName(ast, imp); SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); var.setName(ast.newSimpleName(varName)); var.setType(ast.newSimpleType(name)); CatchClause newClause= ast.newCatchClause(); newClause.setException(var); String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, String.valueOf('\n')); if (catchBody != null) { ASTNode node= rewrite.createPlaceholder(catchBody, NewASTRewrite.STATEMENT); newClause.getBody().statements().add(node); } rewrite.markAsInserted(newClause); catchClauses.add(newClause); String typeKey= "type" + i; //$NON-NLS-1$ String nameKey= "name" + i; //$NON-NLS-1$ proposal.markAsLinked(rewrite, var.getType(), false, typeKey); //$NON-NLS-1$ proposal.markAsLinked(rewrite, var.getName(), false, nameKey); //$NON-NLS-1$ addExceptionTypeLinkProposals(proposal, excBinding, typeKey); } proposal.ensureNoModifications(); proposals.add(proposal); } if (decl instanceof MethodDeclaration) { ASTRewrite rewrite= new ASTRewrite(astRoot); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); AST ast= astRoot.getAST(); MethodDeclaration methodDecl= (MethodDeclaration) decl; List exceptions= methodDecl.thrownExceptions(); for (int i= 0; i < uncaughtExceptions.length; i++) { String imp= proposal.addImport(uncaughtExceptions[i]); Name name= ASTNodeFactory.newName(ast, imp); rewrite.markAsInserted(name); exceptions.add(name); String typeKey= "type" + i; //$NON-NLS-1$ proposal.markAsLinked(rewrite, name, false, typeKey); //$NON-NLS-1$ addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], typeKey); } for (int i= 0; i < exceptions.size(); i++) { Name elem= (Name) exceptions.get(i); if (canRemoveException(elem.resolveTypeBinding(), uncaughtExceptions)) { rewrite.markAsRemoved(elem); } } proposal.ensureNoModifications(); proposals.add(proposal); } } private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String key) { // all superclasses except Object while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$ proposal.addLinkedModeProposal(key, exc); exc= exc.getSuperclass(); } } private static boolean canRemoveException(ITypeBinding curr, ITypeBinding[] addedExceptions) { while (curr != null) { for (int i= 0; i < addedExceptions.length; i++) { if (curr == addedExceptions[i]) { return true; } } curr= curr.getSuperclass(); } return false; } public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } QuickAssistProcessor.getCatchClauseToThrowsProposals(context, selectedNode, proposals); } public static void addNLSProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); if (! NLSRefactoring.isAvailable(cu)){ return; } String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$ ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5) { public void apply(IDocument document) { try { NLSRefactoring refactoring= NLSRefactoring.create(cu, JavaPreferencesSettings.getCodeGenerationSettings()); if (refactoring == null) return; ExternalizeWizard wizard= new ExternalizeWizard(refactoring); String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$ new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true); } catch (JavaModelException e) { JavaPlugin.log(e); } } }; proposals.add(proposal); TextEdit edit= NLSUtil.createNLSEdit(cu, problem.getOffset()); if (edit != null) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE); CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image); nlsProposal.getRootTextEdit().addChild(edit); proposals.add(nlsProposal); } } /** * Fix instance accesses and indirect (static) accesses to static fields/methods */ public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } Expression qualifier= null; IBinding accessBinding= null; if (selectedNode instanceof QualifiedName) { QualifiedName name= (QualifiedName) selectedNode; qualifier= name.getQualifier(); accessBinding= name.resolveBinding(); } else if (selectedNode instanceof SimpleName) { ASTNode parent= selectedNode.getParent(); if (parent instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) parent; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); } } else if (selectedNode instanceof MethodInvocation) { MethodInvocation methodInvocation= (MethodInvocation) selectedNode; qualifier= methodInvocation.getExpression(); accessBinding= methodInvocation.getName().resolveBinding(); } else if (selectedNode instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) selectedNode; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); } if (problem.getProblemId() == IProblem.IndirectAccessToStaticField || problem.getProblemId() == IProblem.IndirectAccessToStaticMethod) { // indirectAccessToStaticProposal if (accessBinding != null) { ITypeBinding declaringTypeBinding= getDeclaringTypeBinding(accessBinding); if (declaringTypeBinding != null) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.indirectaccesstostatic.description", declaringTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); String typeName= proposal.addImport(declaringTypeBinding); rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName)); proposal.ensureNoModifications(); proposals.add(proposal); } } return; } ITypeBinding declaringTypeBinding= null; if (accessBinding != null) { declaringTypeBinding= getDeclaringTypeBinding(accessBinding); if (declaringTypeBinding != null) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); String typeName= proposal.addImport(declaringTypeBinding); rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName)); proposal.ensureNoModifications(); proposals.add(proposal); } } if (qualifier != null) { ITypeBinding instanceTypeBinding= Bindings.normalizeTypeBinding(qualifier.resolveTypeBinding()); if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image); String typeName= proposal.addImport(instanceTypeBinding); rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName)); proposal.ensureNoModifications(); proposals.add(proposal); } } ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC, 4); } private static ITypeBinding getDeclaringTypeBinding(IBinding accessBinding) { if (accessBinding instanceof IMethodBinding) { return ((IMethodBinding) accessBinding).getDeclaringClass(); } else if (accessBinding instanceof IVariableBinding) { return ((IVariableBinding) accessBinding).getDeclaringClass(); } return null; } public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } ASTNode typeNode= null; if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) { typeNode= selectedNode.getParent(); } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; typeNode= creation.getAnonymousClassDeclaration(); } if (typeNode != null) { UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10); proposals.add(proposal); } if (typeNode instanceof TypeDeclaration) { TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode; ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration, 5); proposals.add(proposal); } } public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof Name)) { return; } Name name= (Name) selectedNode; IBinding binding= name.resolveBinding(); if (!(binding instanceof IVariableBinding)) { return; } IVariableBinding varBinding= (IVariableBinding) binding; CompilationUnit astRoot= context.getASTRoot(); ASTNode node= astRoot.findDeclaringNode(binding); if (node instanceof VariableDeclarationFragment) { ASTRewrite rewrite= new ASTRewrite(node.getParent()); VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; if (fragment.getInitializer() != null) { return; } Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType()); if (expression == null) { return; } rewrite.markAsInsert(fragment, ASTNodeConstants.INITIALIZER, expression, null); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); proposal.markAsLinked(rewrite, expression, false, "initializer"); //$NON-NLS-1$ proposal.ensureNoModifications(); proposals.add(proposal); } } public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) { return; } TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent(); ITypeBinding binding= typeDeclaration.resolveBinding(); if (binding == null || binding.getSuperclass() == null) { return; } ICompilationUnit cu= context.getCompilationUnit(); IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) { proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 5)); } } } public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); SimpleName name= null; if (selectedNode instanceof MethodDeclaration) { name= ((MethodDeclaration) selectedNode).getName(); } else if (selectedNode instanceof SimpleName) { name= (SimpleName) selectedNode; } if (name != null) { IBinding binding= name.resolveBinding(); if (binding != null) { proposals.add(new RemoveDeclarationCorrectionProposal(context.getCompilationUnit(), name, 5)); } } } public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removesemicolon.description"); //$NON-NLS-1$ ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", 6); //$NON-NLS-1$ proposals.add(proposal); } public static void addUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); ASTNode curr= selectedNode; while (curr instanceof ParenthesizedExpression) { curr= ((ParenthesizedExpression) curr).getExpression(); } if (curr instanceof CastExpression) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); CastExpression cast= (CastExpression) curr; Expression expression= cast.getExpression(); ASTNode placeholder= rewrite.createCopy(expression); if (ASTNodes.needsParentheses(expression)) { rewrite.markAsReplaced(curr, placeholder); } else { rewrite.markAsReplaced(selectedNode, placeholder); } String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarycast.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); } } public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); ASTNode curr= selectedNode; while (curr instanceof ParenthesizedExpression) { curr= ((ParenthesizedExpression) curr).getExpression(); } if (curr instanceof InstanceofExpression) { ASTRewrite rewrite= new ASTRewrite(curr.getParent()); InstanceofExpression inst= (InstanceofExpression) curr; AST ast= inst.getAST(); InfixExpression expression= ast.newInfixExpression(); expression.setLeftOperand((Expression) rewrite.createCopy(inst.getLeftOperand())); expression.setOperator(InfixExpression.Operator.NOT_EQUALS); expression.setRightOperand(ast.newNullLiteral()); if (false/*ASTNodes.needsParentheses(expression)*/) { ParenthesizedExpression parents= ast.newParenthesizedExpression(); parents.setExpression(expression); rewrite.markAsReplaced(inst, parents); } else { rewrite.markAsReplaced(inst, expression); } String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessaryinstanceof.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); } } public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } if (selectedNode.getParent() instanceof MethodDeclaration) { MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent(); List thrownExceptions= decl.thrownExceptions(); if (!thrownExceptions.contains(selectedNode)) { return; } ASTRewrite rewrite= new ASTRewrite(decl); rewrite.markAsRemoved(selectedNode); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarythrow.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); } } public static void addUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); while (selectedNode instanceof QualifiedName) { selectedNode= ((QualifiedName) selectedNode).getQualifier(); } if (!(selectedNode instanceof SimpleName)) { return; } SimpleName name = (SimpleName) selectedNode; IBinding binding= name.resolveBinding(); if (binding.getKind() != IBinding.VARIABLE) { return; } ASTRewrite rewrite= new ASTRewrite(name.getParent()); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", context.getCompilationUnit(), rewrite, 5, image); //$NON-NLS-1$ ITypeBinding declaringClass= ((IVariableBinding) binding).getDeclaringClass(); String qualifier; if (Modifier.isStatic(binding.getModifiers())) { qualifier= proposal.addImport(declaringClass); } else { ITypeBinding currType= Bindings.getBindingOfParentType(name); if (Bindings.isSuperType(currType, declaringClass)) { qualifier= "this"; //$NON-NLS-1$ } else { String outer= proposal.addImport(declaringClass); qualifier= outer + ".this"; //$NON-NLS-1$ } } String replacement= qualifier + '.' + name.getIdentifier(); rewrite.markAsReplaced(name, rewrite.createPlaceholder(replacement, NewASTRewrite.NAME)); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.unqualifiedfieldaccess.description", qualifier); //$NON-NLS-1$ proposal.setDisplayName(label); proposals.add(proposal); } }
48,001
Bug 48001 Don't want 'e' as variable name in throw clause
M5 'Surround with' refactoring and quick fix use 'e' as exception variable name. It should be possible to configure this
resolved fixed
25a25f1
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:09:37Z
2003-12-03T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/PreferenceConstants.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.action.Action; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.ui.texteditor.AbstractTextEditor; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.ui.text.IJavaColorConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.preferences.WorkInProgressPreferencePage; import org.eclipse.jdt.internal.ui.preferences.formatter.ProfileManager; /** * Preference constants used in the JDT-UI preference store. Clients should only read the * JDT-UI preference store using these values. Clients are not allowed to modify the * preference store programmatically. * * @since 2.0 */ public class PreferenceConstants { private PreferenceConstants() { } /** * A named preference that controls return type rendering of methods in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> return types * are rendered * </p> */ public static final String APPEARANCE_METHOD_RETURNTYPE= "org.eclipse.jdt.ui.methodreturntype";//$NON-NLS-1$ /** * A named preference that controls if override indicators are rendered in the UI. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> override * indicators are rendered * </p> */ public static final String APPEARANCE_OVERRIDE_INDICATOR= "org.eclipse.jdt.ui.overrideindicator";//$NON-NLS-1$ /** * A named preference that controls if quick assist light bulbs are shown. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> light bulbs are shown * for quick assists. * </p> */ public static final String APPEARANCE_QUICKASSIST_LIGHTBULB="org.eclipse.jdt.quickassist.lightbulb"; //$NON-NLS-1$ /** * A named preference that defines the pattern used for package name compression. * <p> * Value is of type <code>String</code>. For example foe the given package name 'org.eclipse.jdt' pattern * '.' will compress it to '..jdt', '1~' to 'o~.e~.jdt'. * </p> */ public static final String APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW= "PackagesView.pkgNamePatternForPackagesView";//$NON-NLS-1$ /** * A named preference that controls if package name compression is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW */ public static final String APPEARANCE_COMPRESS_PACKAGE_NAMES= "org.eclipse.jdt.ui.compresspackagenames";//$NON-NLS-1$ /** * A named preference that controls if empty inner packages are folded in * the hierarchical mode of the package explorer. * <p> * Value is of type <code>Boolean</code>: if <code>true</code> empty * inner packages are folded. * </p> * @since 2.1 */ public static final String APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER= "org.eclipse.jdt.ui.flatPackagesInPackageExplorer";//$NON-NLS-1$ /** * A named preference that defines how member elements are ordered by the * Java views using the <code>JavaElementSorter</code>. * <p> * Value is of type <code>String</code>: A comma separated list of the * following entries. Each entry must be in the list, no duplication. List * order defines the sort order. * <ul> * <li><b>T</b>: Types</li> * <li><b>C</b>: Constructors</li> * <li><b>I</b>: Initializers</li> * <li><b>M</b>: Methods</li> * <li><b>F</b>: Fields</li> * <li><b>SI</b>: Static Initializers</li> * <li><b>SM</b>: Static Methods</li> * <li><b>SF</b>: Static Fields</li> * </ul> * </p> * @since 2.1 */ public static final String APPEARANCE_MEMBER_SORT_ORDER= "outlinesortoption"; //$NON-NLS-1$ /** * A named preference that controls if prefix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of prefixes to be removed from a local variable to compute setter * and gettter names. * <p> * Value is of type <code>String</code>: comma separated list of prefixed * </p> * * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_GETTERSETTER_PREFIX= "org.eclipse.jdt.ui.gettersetter.prefix.list";//$NON-NLS-1$ /** * A named preference that controls if suffix removal during setter/getter generation is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_PREFIXES and CODEASSIST_STATIC_FIELD_PREFIXES) */ public static final String CODEGEN_USE_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.enable";//$NON-NLS-1$ /** * A named preference that holds a list of suffixes to be removed from a local variable to compute setter * and getter names. * <p> * Value is of type <code>String</code>: comma separated list of suffixes * </p> * @deprecated Use setting from JavaCore preference store (key JavaCore. * CODEASSIST_FIELD_SUFFIXES and CODEASSIST_STATIC_FIELD_SUFFIXES) */ public static final String CODEGEN_GETTERSETTER_SUFFIX= "org.eclipse.jdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ /** * A named preference that controls whether the keyword "this" will be added * automatically to field accesses in autogenerated methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String CODEGEN_KEYWORD_THIS= "org.eclipse.jdt.ui.keywordthis"; //$NON-NLS-1$ /** * A named preference that controls whether to use the prefix "is" or the prefix "get" for * automatically created getters which return a boolean field. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public static final String CODEGEN_IS_FOR_GETTERS= "org.eclipse.jdt.ui.gettersetter.use.is"; //$NON-NLS-1$ /** * A named preference that controls if comment stubs will be added * automatically to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String CODEGEN_ADD_COMMENTS= "org.eclipse.jdt.ui.javadoc"; //$NON-NLS-1$ /** * A named preference that controls if a comment stubs will be added * automatocally to newly created types and methods. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precice). */ public static final String CODEGEN__JAVADOC_STUBS= CODEGEN_ADD_COMMENTS; /** * A named preference that controls if a non-javadoc comment gets added to methods generated via the * "Override Methods" operation. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the overriding method comment. */ public static final String CODEGEN__NON_JAVADOC_COMMENTS= "org.eclipse.jdt.ui.seecomments"; //$NON-NLS-1$ /** * A named preference that controls if a file comment gets added to newly created files. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated New code template story: user can * specify the new type code template. */ public static final String CODEGEN__FILE_COMMENTS= "org.eclipse.jdt.ui.filecomments"; //$NON-NLS-1$ /** * A named preference that holds a list of comma separated package names. The list specifies the import order used by * the "Organize Imports" opeation. * <p> * Value is of type <code>String</code>: semicolon separated list of package * names * </p> */ public static final String ORGIMPORTS_IMPORTORDER= "org.eclipse.jdt.ui.importorder"; //$NON-NLS-1$ /** * A named preference that specifies the number of imports added before a star-import declaration is used. * <p> * Value is of type <code>Int</code>: positive value specifing the number of non star-import is used * </p> */ public static final String ORGIMPORTS_ONDEMANDTHRESHOLD= "org.eclipse.jdt.ui.ondemandthreshold"; //$NON-NLS-1$ /** * A named preferences that controls if types that start with a lower case letters get added by the * "Organize Import" operation. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String ORGIMPORTS_IGNORELOWERCASE= "org.eclipse.jdt.ui.ignorelowercasenames"; //$NON-NLS-1$ /** * A named preference that speficies whether children of a compilation unit are shown in the package explorer. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String SHOW_CU_CHILDREN= "org.eclipse.jdt.ui.packages.cuchildren"; //$NON-NLS-1$ /** * A named preference that controls whether the package explorer's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the hierarchy view's selection is linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String LINK_TYPEHIERARCHY_TO_EDITOR= "org.eclipse.jdt.ui.packages.linktypehierarchytoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the projects view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PROJECTS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.projectstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the packages view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_PACKAGES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.packagestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the types view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_TYPES_TO_EDITOR= "org.eclipse.jdt.ui.browsing.typestoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether the members view's selection is * linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public static final String LINK_BROWSING_MEMBERS_TO_EDITOR= "org.eclipse.jdt.ui.browsing.memberstoeditor"; //$NON-NLS-1$ /** * A named preference that controls whether new projects are generated using source and output folder. * <p> * Value is of type <code>Boolean</code>. if <code>true</code> new projects are created with a source and * output folder. If <code>false</code> source and output folder equals to the project. * </p> */ public static final String SRCBIN_FOLDERS_IN_NEWPROJ= "org.eclipse.jdt.ui.wizards.srcBinFoldersInNewProjects"; //$NON-NLS-1$ /** * A named preference that specifies the source folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_SRCNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersSrcName"; //$NON-NLS-1$ /** * A named preference that specifies the output folder name used when creating a new Java project. Value is inactive * if <code>SRCBIN_FOLDERS_IN_NEWPROJ</code> is set to <code>false</code>. * <p> * Value is of type <code>String</code>. * </p> * * @see #SRCBIN_FOLDERS_IN_NEWPROJ */ public static final String SRCBIN_BINNAME= "org.eclipse.jdt.ui.wizards.srcBinFoldersBinName"; //$NON-NLS-1$ /** * A named preference that holds a list of possible JRE libraries used by the New Java Project wizard. An library * consists of a description and an arbitrary number of <code>IClasspathEntry</code>s, that will represent the * JRE on the new project's classpath. * <p> * Value is of type <code>String</code>: a semicolon separated list of encoded JRE libraries. * <code>NEWPROJECT_JRELIBRARY_INDEX</code> defines the currently used library. Clients * should use the method <code>encodeJRELibrary</code> to encode a JRE library into a string * and the methods <code>decodeJRELibraryDescription(String)</code> and <code> * decodeJRELibraryClasspathEntries(String)</code> to decode the description and the array * of classpath entries from an encoded string. * </p> * * @see #NEWPROJECT_JRELIBRARY_INDEX * @see #encodeJRELibrary(String, IClasspathEntry[]) * @see #decodeJRELibraryDescription(String) * @see #decodeJRELibraryClasspathEntries(String) */ public static final String NEWPROJECT_JRELIBRARY_LIST= "org.eclipse.jdt.ui.wizards.jre.list"; //$NON-NLS-1$ /** * A named preferences that specifies the current active JRE library. * <p> * Value is of type <code>Int</code>: an index into the list of possible JRE libraries. * </p> * * @see #NEWPROJECT_JRELIBRARY_LIST */ public static final String NEWPROJECT_JRELIBRARY_INDEX= "org.eclipse.jdt.ui.wizards.jre.index"; //$NON-NLS-1$ /** * A named preference that controls if a new type hierarchy gets opened in a * new type hierarchy perspective or inside the type hierarchy view part. * <p> * Value is of type <code>String</code>: possible values are <code> * OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE</code> or <code> * OPEN_TYPE_HIERARCHY_IN_VIEW_PART</code>. * </p> * * @see #OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE * @see #OPEN_TYPE_HIERARCHY_IN_VIEW_PART */ public static final String OPEN_TYPE_HIERARCHY= "org.eclipse.jdt.ui.openTypeHierarchy"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_PERSPECTIVE= "perspective"; //$NON-NLS-1$ /** * A string value used by the named preference <code>OPEN_TYPE_HIERARCHY</code>. * * @see #OPEN_TYPE_HIERARCHY */ public static final String OPEN_TYPE_HIERARCHY_IN_VIEW_PART= "viewPart"; //$NON-NLS-1$ /** * A named preference that controls the behaviour when double clicking on a container in the packages view. * <p> * Value is of type <code>String</code>: possible values are <code> * DOUBLE_CLICK_GOES_INTO</code> or <code> * DOUBLE_CLICK_EXPANDS</code>. * </p> * * @see #DOUBLE_CLICK_EXPANDS * @see #DOUBLE_CLICK_GOES_INTO */ public static final String DOUBLE_CLICK= "packageview.doubleclick"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_GOES_INTO= "packageview.gointo"; //$NON-NLS-1$ /** * A string value used by the named preference <code>DOUBLE_CLICK</code>. * * @see #DOUBLE_CLICK */ public static final String DOUBLE_CLICK_EXPANDS= "packageview.doubleclick.expands"; //$NON-NLS-1$ /** * A named preference that controls whether Java views update their presentation while editing or when saving the * content of an editor. * <p> * Value is of type <code>String</code>: possible values are <code> * UPDATE_ON_SAVE</code> or <code> * UPDATE_WHILE_EDITING</code>. * </p> * * @see #UPDATE_ON_SAVE * @see #UPDATE_WHILE_EDITING */ public static final String UPDATE_JAVA_VIEWS= "JavaUI.update"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_ON_SAVE= "JavaUI.update.onSave"; //$NON-NLS-1$ /** * A string value used by the named preference <code>UPDATE_JAVA_VIEWS</code> * * @see #UPDATE_JAVA_VIEWS */ public static final String UPDATE_WHILE_EDITING= "JavaUI.update.whileEditing"; //$NON-NLS-1$ /** * A named preference that holds the path of the Javadoc command used by the Javadoc creation wizard. * <p> * Value is of type <code>String</code>. * </p> */ public static final String JAVADOC_COMMAND= "command"; //$NON-NLS-1$ /** * A named preference that defines whether hint to make hover sticky should be shown. * * @see JavaUI * @since 3.0 */ public static String EDITOR_SHOW_TEXT_HOVER_AFFORDANCE= "PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE"; //$NON-NLS-1$ /** * A named preference that defines the key for the hover modifiers. * * @see JavaUI * @since 2.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIERS= "hoverModifiers"; //$NON-NLS-1$ /** * A named preference that defines the key for the hover modifier state masks. * The value is only used if the value of <code>EDITOR_TEXT_HOVER_MODIFIERS</code> * cannot be resolved to valid SWT modifier bits. * * @see JavaUI * @see #EDITOR_TEXT_HOVER_MODIFIERS * @since 2.1.1 */ public static final String EDITOR_TEXT_HOVER_MODIFIER_MASKS= "hoverModifierMasks"; //$NON-NLS-1$ /** * 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$ /** * A named preference that controls whether bracket matching highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_MATCHING_BRACKETS= "matchingBrackets"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight matching brackets. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MATCHING_BRACKETS_COLOR= "matchingBracketsColor"; //$NON-NLS-1$ /** * A named preference that controls whether the current line highlighting is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_CURRENT_LINE= "currentLine"; //$NON-NLS-1$ /** * A named preference that holds the color used to highlight the current line. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_CURRENT_LINE_COLOR= "currentLineColor"; //$NON-NLS-1$ /** * A named preference that controls whether the print margin is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN= "printMargin"; //$NON-NLS-1$ /** * A named preference that holds the color used to render the print margin. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN_COLOR= "printMarginColor"; //$NON-NLS-1$ /** * Print margin column. Int value. * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_PRINT_MARGIN_COLUMN= "printMarginColumn"; //$NON-NLS-1$ /** * A named preference that holds the color used for the find/replace scope. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FIND_SCOPE_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FIND_SCOPE; /** * A named preference that specifies if the editor uses spaces for tabs. * <p> * Value is of type <code>Boolean</code>. If <code>true</code>spaces instead of tabs are used * in the editor. If <code>false</code> the editor inserts a tab character when pressing the tab * key. * </p> */ public final static String EDITOR_SPACES_FOR_TABS= "spacesForTabs"; //$NON-NLS-1$ /** * A named preference that holds the number of spaces used per tab in the editor. * <p> * Value is of type <code>Int</code>: positive int value specifying the number of * spaces per tab. * </p> */ public final static String EDITOR_TAB_WIDTH= "org.eclipse.jdt.ui.editor.tab.width"; //$NON-NLS-1$ /** * A named preference that controls whether the outline view selection * should stay in sync with with the element at the current cursor position. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE= "JavaEditor.SyncOutlineOnCursorMove"; //$NON-NLS-1$ /** * A named preference that controls if correction indicators are shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_CORRECTION_INDICATION= "JavaEditor.ShowTemporaryProblem"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows problem indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_PROBLEM_INDICATION= "problemIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render problem indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_PROBLEM_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_PROBLEM_INDICATION_COLOR= "problemIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows warning indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_WARNING_INDICATION= "warningIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render warning indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_WARNING_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_WARNING_INDICATION_COLOR= "warningIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows task indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_TASK_INDICATION= "taskIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render task indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_TASK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_TASK_INDICATION_COLOR= "taskIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows bookmark * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_BOOKMARK_INDICATION= "bookmarkIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render bookmark indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_BOOKMARK_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_BOOKMARK_INDICATION_COLOR= "bookmarkIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows search * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_SEARCH_RESULT_INDICATION= "searchResultIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render search indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_SEARCH_RESULT_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_SEARCH_RESULT_INDICATION_COLOR= "searchResultIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the editor shows unknown * indicators in text (squiggly lines). * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_UNKNOWN_INDICATION= "othersIndication"; //$NON-NLS-1$ /** * A named preference that holds the color used to render unknown * indicators. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see #EDITOR_UNKNOWN_INDICATION * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 * @deprecated * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_UNKNOWN_INDICATION_COLOR= "othersIndicationColor"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows error * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_ERROR_INDICATION_IN_OVERVIEW_RULER= "errorIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows warning * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_WARNING_INDICATION_IN_OVERVIEW_RULER= "warningIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows task * indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_TASK_INDICATION_IN_OVERVIEW_RULER= "taskIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * bookmark indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_BOOKMARK_INDICATION_IN_OVERVIEW_RULER= "bookmarkIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * search result indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_SEARCH_RESULT_INDICATION_IN_OVERVIEW_RULER= "searchResultIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the overview ruler shows * unknown indicators. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.MarkerAnnotationPreferences} */ public final static String EDITOR_UNKNOWN_INDICATION_IN_OVERVIEW_RULER= "othersIndicationInOverviewRuler"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close strings' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_STRINGS= "closeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'wrap strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_WRAP_STRINGS= "wrapStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'escape strings' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 3.0 */ public final static String EDITOR_ESCAPE_STRINGS= "escapeStrings"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close brackets' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACKETS= "closeBrackets"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close braces' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_BRACES= "closeBraces"; //$NON-NLS-1$ /** * A named preference that controls whether the 'close java docs' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_CLOSE_JAVADOCS= "closeJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'add JavaDoc tags' feature * is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_ADD_JAVADOC_TAGS= "addJavaDocTags"; //$NON-NLS-1$ /** * A named preference that controls whether the 'format Javadoc tags' * feature is enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_FORMAT_JAVADOCS= "autoFormatJavaDocs"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart paste' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_PASTE= "smartPaste"; //$NON-NLS-1$ /** * A named preference that controls whether the 'smart home-end' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SMART_HOME_END= AbstractTextEditor.PREFERENCE_NAVIGATION_SMART_HOME_END; /** * A named preference that controls whether the 'sub-word navigation' feature is * enabled. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_SUB_WORD_NAVIGATION= "subWordNavigation"; //$NON-NLS-1$ /** * A named preference that controls if temporary problems are evaluated and shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_EVALUTE_TEMPORARY_PROBLEMS= "handleTemporaryProblems"; //$NON-NLS-1$ /** * A named preference that controls if the overview ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_OVERVIEW_RULER= "overviewRuler"; //$NON-NLS-1$ /** * A named preference that controls if the line number ruler is shown in the UI. * <p> * Value is of type <code>Boolean</code>. * </p> * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_LINE_NUMBER_RULER= "lineNumberRuler"; //$NON-NLS-1$ /** * A named preference that holds the color used to render line numbers inside the line number ruler. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @see #EDITOR_LINE_NUMBER_RULER * @deprecated as of 3.0 replaced by {@link org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants} */ public final static String EDITOR_LINE_NUMBER_RULER_COLOR= "lineNumberColor"; //$NON-NLS-1$ /** * A named preference that holds the color used to render linked positions inside code templates. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_LINKED_POSITION_COLOR= "linkedPositionColor"; //$NON-NLS-1$ /** * A named preference that holds the color used as the text foreground. * This value has not effect if the system default color is used. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_FOREGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND; /** * A named preference that describes if the system default foreground color * is used as the text foreground. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_FOREGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_FOREGROUND_SYSTEM_DEFAULT; /** * A named preference that holds the color used as the text background. * This value has not effect if the system default color is used. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_BACKGROUND_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND; /** * A named preference that describes if the system default background color * is used as the text background. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_BACKGROUND_DEFAULT_COLOR= AbstractTextEditor.PREFERENCE_COLOR_BACKGROUND_SYSTEM_DEFAULT; /** * Preference key suffix for bold text style preference keys. * * @since 2.1 */ public static final String EDITOR_BOLD_SUFFIX= "_bold"; //$NON-NLS-1$ /** * A named preference that holds the color used to render multi line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_MULTI_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT; /** * The symbolic font name for the Java editor text font * (value <code>"org.eclipse.jdt.ui.editors.textfont"</code>). * * @since 2.1 */ public final static String EDITOR_TEXT_FONT= "org.eclipse.jdt.ui.editors.textfont"; //$NON-NLS-1$ /** * A named preference that controls whether multi line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> multi line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_MULTI_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_MULTI_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render single line comments. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_SINGLE_LINE_COMMENT_COLOR= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT; /** * A named preference that controls whether sinle line comments are rendered in bold. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> single line comments are rendered * in bold. If <code>false</code> the are rendered using no font style attribute. * </p> */ public final static String EDITOR_SINGLE_LINE_COMMENT_BOLD= IJavaColorConstants.JAVA_SINGLE_LINE_COMMENT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_KEYWORD_COLOR= IJavaColorConstants.JAVA_KEYWORD; /** * A named preference that controls whether keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_KEYWORD_BOLD= IJavaColorConstants.JAVA_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render string constants. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_STRING_COLOR= IJavaColorConstants.JAVA_STRING; /** * A named preference that controls whether string constants are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_STRING_BOLD= IJavaColorConstants.JAVA_STRING + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render method names. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_COLOR= IJavaColorConstants.JAVA_METHOD_NAME; /** * A named preference that controls whether method names are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_METHOD_NAME_BOLD= IJavaColorConstants.JAVA_METHOD_NAME + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render operators and brackets. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_COLOR= IJavaColorConstants.JAVA_OPERATOR; /** * A named preference that controls whether operators and brackets are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String EDITOR_JAVA_OPERATOR_BOLD= IJavaColorConstants.JAVA_OPERATOR + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render java default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVA_DEFAULT_COLOR= IJavaColorConstants.JAVA_DEFAULT; /** * A named preference that controls whether Java default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVA_DEFAULT_BOLD= IJavaColorConstants.JAVA_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render task tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_TASK_TAG_COLOR= IJavaColorConstants.TASK_TAG; /** * A named preference that controls whether task tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String EDITOR_TASK_TAG_BOLD= IJavaColorConstants.TASK_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc keywords. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_KEYWORD_COLOR= IJavaColorConstants.JAVADOC_KEYWORD; /** * A named preference that controls whether javadoc keywords are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_KEYWORD_BOLD= IJavaColorConstants.JAVADOC_KEYWORD + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc tags. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_TAG_COLOR= IJavaColorConstants.JAVADOC_TAG; /** * A named preference that controls whether javadoc tags are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_TAG_BOLD= IJavaColorConstants.JAVADOC_TAG + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc links. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_LINKS_COLOR= IJavaColorConstants.JAVADOC_LINK; /** * A named preference that controls whether javadoc links are rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_LINKS_BOLD= IJavaColorConstants.JAVADOC_LINK + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used to render javadoc default text. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String EDITOR_JAVADOC_DEFAULT_COLOR= IJavaColorConstants.JAVADOC_DEFAULT; /** * A named preference that controls whether javadoc default text is rendered in bold. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String EDITOR_JAVADOC_DEFAULT_BOLD= IJavaColorConstants.JAVADOC_DEFAULT + EDITOR_BOLD_SUFFIX; /** * A named preference that holds the color used for 'linked-mode' underline. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String EDITOR_LINK_COLOR= "linkColor"; //$NON-NLS-1$ /** * A named preference that controls whether hover tooltips in the editor are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_HOVER= "org.eclipse.jdt.ui.editor.showHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when no control key is * pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_NONE_HOVER= "noneHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_CTRL_HOVER= "ctrlHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>SHIFT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_SHIFT_HOVER= "shiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_HOVER= "ctrlAltHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + ALT + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 */ public static final String EDITOR_CTRL_ALT_SHIFT_HOVER= "ctrlAltShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>CTRL + SHIFT</code> modifier keys is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @since 2.1 * @deprecated Will be removed in one of the next builds. */ public static final String EDITOR_CTRL_SHIFT_HOVER= "ctrlShiftHover"; //$NON-NLS-1$ /** * A named preference that defines the hover shown when the * <code>ALT</code> modifier key is pressed. * <p>Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code>, * <code>EDITOR_DEFAULT_HOVER_CONFIGURED_ID</code> or the hover id of a * hover contributed as <code>javaEditorTextHovers</code>. * </p> * @see #EDITOR_NO_HOVER_CONFIGURED_ID * @see #EDITOR_DEFAULT_HOVER_CONFIGURED_ID * @see JavaUI ID_*_HOVER * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_ALT_SHIFT_HOVER= "altShiftHover"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that no hover should be shown for the given key modifiers. * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} * @since 2.1 */ public static final String EDITOR_NO_HOVER_CONFIGURED_ID= "noHoverConfiguredId"; //$NON-NLS-1$ /** * A string value used by the named preferences for hover configuration to * descibe that the default hover should be shown for the given key * modifiers. The default hover is described by the * <code>EDITOR_DEFAULT_HOVER</code> property. * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER_CONFIGURED_ID= "defaultHoverConfiguredId"; //$NON-NLS-1$ /** * A named preference that defines the hover named the 'default hover'. * Value is of type <code>String</code>: possible values are <code> * EDITOR_NO_HOVER_CONFIGURED_ID</code> or <code> the hover id of a hover * contributed as <code>javaEditorTextHovers</code>. * </p> * @since 2.1 * @deprecated Will soon be removed - replaced by {@link #EDITOR_TEXT_HOVER_MODIFIERS} */ public static final String EDITOR_DEFAULT_HOVER= "defaultHover"; //$NON-NLS-1$ /** * A named preference that controls if segmented view (show selected element only) is turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String EDITOR_SHOW_SEGMENTS= "org.eclipse.jdt.ui.editor.showSegments"; //$NON-NLS-1$ /** * A named preference that controls if browser like links are turned on or off. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS= "browserLikeLinks"; //$NON-NLS-1$ /** * A named preference that controls the key modifier for browser like links. * <p> * Value is of type <code>String</code>. * </p> * * @since 2.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER= "browserLikeLinksKeyModifier"; //$NON-NLS-1$ /** * A named preference that controls the key modifier mask for browser like links. * The value is only used if the value of <code>EDITOR_BROWSER_LIKE_LINKS</code> * cannot be resolved to valid SWT modifier bits. * <p> * Value is of type <code>String</code>. * </p> * * @see #EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER * @since 2.1.1 */ public static final String EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK= "browserLikeLinksKeyModifierMask"; //$NON-NLS-1$ /** * A named preference that controls whether occurrences are marked in the editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_MARK_OCCURRENCES= "markOccurrences"; //$NON-NLS-1$ /** * A named preference that controls disabling of the overwrite mode. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_DISABLE_OVERWRITE_MODE= "disable_overwrite_mode"; //$NON-NLS-1$ /** * A named preference that controls the "smart semicolon" smart typing handler * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_SMART_SEMICOLON= "smart_semicolon"; //$NON-NLS-1$ /** * A named preference that controls the "smart opening brace" smart typing handler * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public static final String EDITOR_SMART_OPENING_BRACE= "smart_opening_brace"; //$NON-NLS-1$ /** * A named preference that controls the smart tab behaviour. * <p> * Value is of type <code>Boolean</code>. * * @since 3.0 */ public static final String EDITOR_SMART_TAB= "smart_tab"; //$NON-NLS-1$ /** * A named preference that controls whether code snippets are formatted * in Javadoc comments. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATSOURCE= "comment_format_source_code"; //$NON-NLS-1$ /** * A named preference that controls whether description of Javadoc * parameters are indented. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION= "comment_indent_parameter_description"; //$NON-NLS-1$ /** * A named preference that controls whether the header comment of * a Java source file is formatted. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATHEADER= "comment_format_header"; //$NON-NLS-1$ /** * A named preference that controls whether Javadoc root tags * are indented. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_INDENTROOTTAGS= "comment_indent_root_tags"; //$NON-NLS-1$ /** * A named preference that controls whether Javadoc comments * are formatted by the content formatter. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMAT= "comment_format_comments"; //$NON-NLS-1$ /** * A named preference that controls whether a new line is inserted * after Javadoc root tag parameters. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_NEWLINEFORPARAMETER= "comment_new_line_for_parameter"; //$NON-NLS-1$ /** * A named preference that controls whether an empty line is inserted before * the Javadoc root tag block. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_SEPARATEROOTTAGS= "comment_separate_root_tags"; //$NON-NLS-1$ /** * A named preference that controls whether blank lines are cleared during formatting * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_CLEARBLANKLINES= "comment_clear_blank_lines"; //$NON-NLS-1$ /** * A named preference that controls the line length of comments. * <p> * Value is of type <code>Integer</code>. The value must be at least 4 for reasonable formatting. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_LINELENGTH= "comment_line_length"; //$NON-NLS-1$ /** * A named preference that controls whether html tags are formatted. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 3.0 */ public final static String FORMATTER_COMMENT_FORMATHTML= "comment_format_html"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist gets auto activated. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION= "content_assist_autoactivation"; //$NON-NLS-1$ /** * A name preference that holds the auto activation delay time in milli seconds. * <p> * Value is of type <code>Int</code>. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_DELAY= "content_assist_autoactivation_delay"; //$NON-NLS-1$ /** * A named preference that controls if code assist contains only visible proposals. * <p> * Value is of type <code>Boolean</code>. if <code>true<code> code assist only contains visible members. If * <code>false</code> all members are included. * </p> */ public final static String CODEASSIST_SHOW_VISIBLE_PROPOSALS= "content_assist_show_visible_proposals"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist inserts a * proposal automatically if only one proposal is available. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_AUTOINSERT= "content_assist_autoinsert"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist adds import * statements. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_ADDIMPORT= "content_assist_add_import"; //$NON-NLS-1$ /** * A named preference that controls if the Java code assist only inserts * completions. If set to false the proposals can also _replace_ code. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_INSERT_COMPLETION= "content_assist_insert_completion"; //$NON-NLS-1$ /** * A named preference that controls whether code assist proposals filtering is case sensitive or not. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_CASE_SENSITIVITY= "content_assist_case_sensitivity"; //$NON-NLS-1$ /** * A named preference that defines if code assist proposals are sorted in alphabetical order. * <p> * Value is of type <code>Boolean</code>. If <code>true</code> that are sorted in alphabetical * order. If <code>false</code> that are unsorted. * </p> */ public final static String CODEASSIST_ORDER_PROPOSALS= "content_assist_order_proposals"; //$NON-NLS-1$ /** * A named preference that controls if argument names are filled in when a method is selected from as list * of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> */ public final static String CODEASSIST_FILL_ARGUMENT_NAMES= "content_assist_fill_method_arguments"; //$NON-NLS-1$ /** * A named preference that controls if method arguments are guessed when a * method is selected from as list of code assist proposal. * <p> * Value is of type <code>Boolean</code>. * </p> * @since 2.1 */ public final static String CODEASSIST_GUESS_METHOD_ARGUMENTS= "content_assist_guess_method_arguments"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Java code. * <p> * Value is of type <code>Sring</code>. All characters that trigger auto code assist in Java code. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA= "content_assist_autoactivation_triggers_java"; //$NON-NLS-1$ /** * A named preference that holds the characters that auto activate code assist in Javadoc. * <p> * Value is of type <code>Sring</code>. All characters that trigger auto code assist in Javadoc. * </p> */ public final static String CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC= "content_assist_autoactivation_triggers_javadoc"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_BACKGROUND= "content_assist_proposals_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PROPOSALS_FOREGROUND= "content_assist_proposals_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used for parameter hints. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_BACKGROUND= "content_assist_parameters_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code assist selection dialog. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter */ public final static String CODEASSIST_PARAMETERS_FOREGROUND= "content_assist_parameters_foreground"; //$NON-NLS-1$ /** * A named preference that holds the background color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_BACKGROUND= "content_assist_completion_replacement_background"; //$NON-NLS-1$ /** * A named preference that holds the foreground color used in the code * assist selection dialog to mark replaced code. * <p> * Value is of type <code>String</code>. A RGB color value encoded as a string * using class <code>PreferenceConverter</code> * </p> * * @see org.eclipse.jface.resource.StringConverter * @see org.eclipse.jface.preference.PreferenceConverter * @since 2.1 */ public final static String CODEASSIST_REPLACEMENT_FOREGROUND= "content_assist_completion_replacement_foreground"; //$NON-NLS-1$ /** * A named preference that controls the behaviour of the refactoring wizard for showing the error page. * <p> * Value is of type <code>String</code>. Valid values are: * <code>REFACTOR_FATAL_SEVERITY</code>, * <code>REFACTOR_ERROR_SEVERITY</code>, * <code>REFACTOR_WARNING_SEVERITY</code> * <code>REFACTOR_INFO_SEVERITY</code>, * <code>REFACTOR_OK_SEVERITY</code>. * </p> * * @see #REFACTOR_FATAL_SEVERITY * @see #REFACTOR_ERROR_SEVERITY * @see #REFACTOR_WARNING_SEVERITY * @see #REFACTOR_INFO_SEVERITY * @see #REFACTOR_OK_SEVERITY */ public static final String REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD= "Refactoring.ErrorPage.severityThreshold"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_FATAL_SEVERITY= "4"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_ERROR_SEVERITY= "3"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_WARNING_SEVERITY= "2"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_INFO_SEVERITY= "1"; //$NON-NLS-1$ /** * A string value used by the named preference <code>REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD</code>. * * @see #REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD */ public static final String REFACTOR_OK_SEVERITY= "0"; //$NON-NLS-1$ /** * A named preference thet controls whether all dirty editors are automatically saved before a refactoring is * executed. * <p> * Value is of type <code>Boolean</code>. * </p> */ public static final String REFACTOR_SAVE_ALL_EDITORS= "Refactoring.savealleditors"; //$NON-NLS-1$ /** * A named preference that controls if the Java Browsing views are linked to the active editor. * <p> * Value is of type <code>Boolean</code>. * </p> * * @see #LINK_PACKAGES_TO_EDITOR */ public static final String BROWSING_LINK_VIEW_TO_EDITOR= "org.eclipse.jdt.ui.browsing.linktoeditor"; //$NON-NLS-1$ /** * A named preference that controls the layout of the Java Browsing views vertically. Boolean value. * <p> * Value is of type <code>Boolean</code>. If <code>true<code> the views are stacked vertical. * If <code>false</code> they are stacked horizontal. * </p> */ public static final String BROWSING_STACK_VERTICALLY= "org.eclipse.jdt.ui.browsing.stackVertically"; //$NON-NLS-1$ /** * A named preference that controls if templates are formatted when applied. * <p> * Value is of type <code>Boolean</code>. * </p> * * @since 2.1 */ public static final String TEMPLATES_USE_CODEFORMATTER= "org.eclipse.jdt.ui.template.format"; //$NON-NLS-1$ /** * A named preference that controls which profile is used by the code formatter. * <p> * Value is of type <code>String</code>. * </p> * * @since 2.1 */ public static final String FORMATTER_PROFILE = "formatter_profile"; //$NON-NLS-1$ /** * Initializes the given preference store with the default values. * * @param store the preference store to be initialized * * @since 2.1 */ public static void initializeDefaultValues(IPreferenceStore store) { // set the default values from ExtendedTextEditor ExtendedTextEditorPreferenceConstants.initializeDefaultValues(store); store.setDefault(PreferenceConstants.EDITOR_SHOW_SEGMENTS, false); // JavaBasePreferencePage store.setDefault(PreferenceConstants.LINK_PACKAGES_TO_EDITOR, false); store.setDefault(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, false); store.setDefault(PreferenceConstants.OPEN_TYPE_HIERARCHY, PreferenceConstants.OPEN_TYPE_HIERARCHY_IN_VIEW_PART); store.setDefault(PreferenceConstants.DOUBLE_CLICK, PreferenceConstants.DOUBLE_CLICK_EXPANDS); store.setDefault(PreferenceConstants.UPDATE_JAVA_VIEWS, PreferenceConstants.UPDATE_WHILE_EDITING); store.setDefault(PreferenceConstants.LINK_BROWSING_PROJECTS_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_PACKAGES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_TYPES_TO_EDITOR, true); store.setDefault(PreferenceConstants.LINK_BROWSING_MEMBERS_TO_EDITOR, true); // AppearancePreferencePage store.setDefault(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES, false); store.setDefault(PreferenceConstants.APPEARANCE_METHOD_RETURNTYPE, false); store.setDefault(PreferenceConstants.SHOW_CU_CHILDREN, true); store.setDefault(PreferenceConstants.APPEARANCE_OVERRIDE_INDICATOR, true); store.setDefault(PreferenceConstants.BROWSING_STACK_VERTICALLY, false); store.setDefault(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW, ""); //$NON-NLS-1$ store.setDefault(PreferenceConstants.APPEARANCE_FOLD_PACKAGES_IN_PACKAGE_EXPLORER, true); // ImportOrganizePreferencePage store.setDefault(PreferenceConstants.ORGIMPORTS_IMPORTORDER, "java;javax;org;com"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.ORGIMPORTS_ONDEMANDTHRESHOLD, 99); store.setDefault(PreferenceConstants.ORGIMPORTS_IGNORELOWERCASE, true); // ClasspathVariablesPreferencePage // CodeFormatterPreferencePage // CompilerPreferencePage // no initialization needed // RefactoringPreferencePage store.setDefault(PreferenceConstants.REFACTOR_ERROR_PAGE_SEVERITY_THRESHOLD, PreferenceConstants.REFACTOR_ERROR_SEVERITY); store.setDefault(PreferenceConstants.REFACTOR_SAVE_ALL_EDITORS, false); // TemplatePreferencePage store.setDefault(PreferenceConstants.TEMPLATES_USE_CODEFORMATTER, true); // CodeGenerationPreferencePage // compatibility code if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX)) { String prefix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); if (prefix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_PREFIXES, prefix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_PREFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX); } } if (store.getBoolean(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX)) { String suffix= store.getString(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); if (suffix.length() > 0) { JavaCore.getPlugin().getPluginPreferences().setValue(JavaCore.CODEASSIST_FIELD_SUFFIXES, suffix); store.setToDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX); store.setToDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX); } } store.setDefault(PreferenceConstants.CODEGEN_KEYWORD_THIS, false); store.setDefault(PreferenceConstants.CODEGEN_IS_FOR_GETTERS, true); store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); // MembersOrderPreferencePage store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$ // must add here to guarantee that it is the first in the listener list store.addPropertyChangeListener(JavaPlugin.getDefault().getMemberOrderPreferenceCache()); // JavaEditorPreferencePage store.setDefault(PreferenceConstants.EDITOR_MATCHING_BRACKETS, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MATCHING_BRACKETS_COLOR, new RGB(192, 192,192)); store.setDefault(PreferenceConstants.EDITOR_CURRENT_LINE, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_CURRENT_LINE_COLOR, new RGB(225, 235, 224)); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN, false); store.setDefault(PreferenceConstants.EDITOR_PRINT_MARGIN_COLUMN, 80); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_PRINT_MARGIN_COLOR, new RGB(176, 180 , 185)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_FIND_SCOPE_COLOR, new RGB(185, 176 , 180)); store.setDefault(PreferenceConstants.EDITOR_CORRECTION_INDICATION, true); store.setDefault(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE, true); store.setDefault(PreferenceConstants.EDITOR_EVALUTE_TEMPORARY_PROBLEMS, true); store.setDefault(PreferenceConstants.EDITOR_OVERVIEW_RULER, true); store.setDefault(PreferenceConstants.EDITOR_LINE_NUMBER_RULER, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINE_NUMBER_RULER_COLOR, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINKED_POSITION_COLOR, new RGB(0, 200 , 100)); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_LINK_COLOR, new RGB(0, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_FOREGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_BACKGROUND_DEFAULT_COLOR, true); store.setDefault(PreferenceConstants.EDITOR_TAB_WIDTH, 4); store.setDefault(PreferenceConstants.EDITOR_SPACES_FOR_TABS, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_MULTI_LINE_COMMENT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_COLOR, new RGB(63, 127, 95)); store.setDefault(PreferenceConstants.EDITOR_SINGLE_LINE_COMMENT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_KEYWORD_COLOR, new RGB(127, 0, 85)); store.setDefault(PreferenceConstants.EDITOR_JAVA_KEYWORD_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_STRING_COLOR, new RGB(42, 0, 255)); store.setDefault(PreferenceConstants.EDITOR_STRING_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_DEFAULT_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_DEFAULT_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_METHOD_NAME_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_METHOD_NAME_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVA_OPERATOR_COLOR, new RGB(0, 0, 0)); store.setDefault(PreferenceConstants.EDITOR_JAVA_OPERATOR_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_TASK_TAG_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_TASK_TAG_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_KEYWORD_COLOR, new RGB(127, 159, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_KEYWORD_BOLD, true); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_TAG_COLOR, new RGB(127, 127, 159)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_TAG_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_LINKS_COLOR, new RGB(63, 63, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_LINKS_BOLD, false); PreferenceConverter.setDefault(store, PreferenceConstants.EDITOR_JAVADOC_DEFAULT_COLOR, new RGB(63, 95, 191)); store.setDefault(PreferenceConstants.EDITOR_JAVADOC_DEFAULT_BOLD, false); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION, true); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_DELAY, 500); store.setDefault(PreferenceConstants.CODEASSIST_AUTOINSERT, true); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PROPOSALS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_BACKGROUND, new RGB(254, 241, 233)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_PARAMETERS_FOREGROUND, new RGB(0, 0, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND, new RGB(255, 255, 0)); PreferenceConverter.setDefault(store, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND, new RGB(255, 0, 0)); store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVA, "."); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_AUTOACTIVATION_TRIGGERS_JAVADOC, "@"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEASSIST_SHOW_VISIBLE_PROPOSALS, true); store.setDefault(PreferenceConstants.CODEASSIST_CASE_SENSITIVITY, false); store.setDefault(PreferenceConstants.CODEASSIST_ORDER_PROPOSALS, false); store.setDefault(PreferenceConstants.CODEASSIST_ADDIMPORT, true); store.setDefault(PreferenceConstants.CODEASSIST_INSERT_COMPLETION, true); store.setDefault(PreferenceConstants.CODEASSIST_FILL_ARGUMENT_NAMES, false); store.setDefault(PreferenceConstants.CODEASSIST_GUESS_METHOD_ARGUMENTS, true); store.setDefault(PreferenceConstants.EDITOR_SMART_HOME_END, true); store.setDefault(PreferenceConstants.EDITOR_SUB_WORD_NAVIGATION, true); store.setDefault(PreferenceConstants.EDITOR_SMART_PASTE, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACKETS, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_BRACES, true); store.setDefault(PreferenceConstants.EDITOR_CLOSE_JAVADOCS, true); store.setDefault(PreferenceConstants.EDITOR_WRAP_STRINGS, true); store.setDefault(PreferenceConstants.EDITOR_ESCAPE_STRINGS, false); store.setDefault(PreferenceConstants.EDITOR_ADD_JAVADOC_TAGS, true); store.setDefault(PreferenceConstants.EDITOR_FORMAT_JAVADOCS, false); store.setDefault(PreferenceConstants.EDITOR_DISABLE_OVERWRITE_MODE, false); String mod1Name= Action.findModifierString(SWT.MOD1); // SWT.COMMAND on Mac; SWT.CONTROL elsewhere store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIERS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + mod1Name); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_TEXT_HOVER_MODIFIER_MASKS, "org.eclipse.jdt.ui.BestMatchHover;0;org.eclipse.jdt.ui.JavaSourceHover;" + SWT.MOD1); //$NON-NLS-1$ store.setDefault(PreferenceConstants.EDITOR_SHOW_TEXT_HOVER_AFFORDANCE, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS, true); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER, mod1Name); store.setDefault(PreferenceConstants.EDITOR_BROWSER_LIKE_LINKS_KEY_MODIFIER_MASK, SWT.MOD1); store.setDefault(PreferenceConstants.EDITOR_SMART_TAB, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMAT, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHEADER, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATSOURCE, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTPARAMETERDESCRIPTION, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_INDENTROOTTAGS, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_NEWLINEFORPARAMETER, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_SEPARATEROOTTAGS, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_CLEARBLANKLINES, false); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_FORMATHTML, true); store.setDefault(PreferenceConstants.FORMATTER_COMMENT_LINELENGTH, 80); store.setDefault(PreferenceConstants.FORMATTER_PROFILE, ProfileManager.DEFAULT_PROFILE); // work in progress WorkInProgressPreferencePage.initDefaults(store); // do more complicated stuff NewJavaProjectPreferencePage.initDefaults(store); } /** * Returns the JDT-UI preference store. * * @return the JDT-UI preference store */ public static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /** * Encodes a JRE library to be used in the named preference <code>NEWPROJECT_JRELIBRARY_LIST</code>. * * @param description a string value describing the JRE library. The description is used * to indentify the JDR library in the UI * @param entries an array of classpath entries to be encoded * * @return the encoded string. */ public static String encodeJRELibrary(String description, IClasspathEntry[] entries) { return NewJavaProjectPreferencePage.encodeJRELibrary(description, entries); } /** * Decodes an encoded JRE library and returns its description string. * * @return the description of an encoded JRE library * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static String decodeJRELibraryDescription(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryDescription(encodedLibrary); } /** * Decodes an encoded JRE library and returns its classpath entries. * * @return the array of classpath entries of an encoded JRE library. * * @see #encodeJRELibrary(String, IClasspathEntry[]) */ public static IClasspathEntry[] decodeJRELibraryClasspathEntries(String encodedLibrary) { return NewJavaProjectPreferencePage.decodeJRELibraryClasspathEntries(encodedLibrary); } /** * Returns the current configuration for the JRE to be used as default in new Java projects. * This is a convenience method to access the named preference <code>NEWPROJECT_JRELIBRARY_LIST * </code> with the index defined by <code> NEWPROJECT_JRELIBRARY_INDEX</code>. * * @return the current default set of classpath entries * * @see #NEWPROJECT_JRELIBRARY_LIST * @see #NEWPROJECT_JRELIBRARY_INDEX */ public static IClasspathEntry[] getDefaultJRELibrary() { return NewJavaProjectPreferencePage.getDefaultJRELibrary(); } }
37,913
Bug 37913 Suggest creating field instead of local variable if naming matches preferences for field [quick fix]
Eclipse has a defined list of prefixes (or suffixes) for fields when generating code. I have defined, for example, that local fields begin with _ but of course other naming conventions (e.g. f) are also possible. When I write an assignment such as: public void setThing(Object arg) { _arg = arg; } then it provides with a list of suggestions, including (a) rename to arg, (b) create local variable _arg, (c) create field _arg, and (d) create parameter _arg. Ideally, if variable name _arg matches the naming conventions for the local field as defined in the code generation window, then it should bump the priority up of (c) to first place, rather than having it down the bottom. Also, I don't think that the suggestion of renaming to 'arg' is helpful when the assignment is of the form _arg = arg, and should probably be pruned for that instance (which probably occurs a lot of the time); I'm not sure if that is worth filing as a separate suggestion or may fall out from the bugfix for this enhancement.
verified fixed
89e662e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:42:14Z
2003-05-21T12:26:40Z
org.eclipse.jdt.ui/core
37,913
Bug 37913 Suggest creating field instead of local variable if naming matches preferences for field [quick fix]
Eclipse has a defined list of prefixes (or suffixes) for fields when generating code. I have defined, for example, that local fields begin with _ but of course other naming conventions (e.g. f) are also possible. When I write an assignment such as: public void setThing(Object arg) { _arg = arg; } then it provides with a list of suggestions, including (a) rename to arg, (b) create local variable _arg, (c) create field _arg, and (d) create parameter _arg. Ideally, if variable name _arg matches the naming conventions for the local field as defined in the code generation window, then it should bump the priority up of (c) to first place, rather than having it down the bottom. Also, I don't think that the suggestion of renaming to 'arg' is helpful when the assignment is of the form _arg = arg, and should probably be pruned for that instance (which probably occurs a lot of the time); I'm not sure if that is worth filing as a separate suggestion or may fall out from the bugfix for this enhancement.
verified fixed
89e662e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:42:14Z
2003-05-21T12:26:40Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/StubUtility.java
37,913
Bug 37913 Suggest creating field instead of local variable if naming matches preferences for field [quick fix]
Eclipse has a defined list of prefixes (or suffixes) for fields when generating code. I have defined, for example, that local fields begin with _ but of course other naming conventions (e.g. f) are also possible. When I write an assignment such as: public void setThing(Object arg) { _arg = arg; } then it provides with a list of suggestions, including (a) rename to arg, (b) create local variable _arg, (c) create field _arg, and (d) create parameter _arg. Ideally, if variable name _arg matches the naming conventions for the local field as defined in the code generation window, then it should bump the priority up of (c) to first place, rather than having it down the bottom. Also, I don't think that the suggestion of renaming to 'arg' is helpful when the assignment is of the form _arg = arg, and should probably be pruned for that instance (which probably occurs a lot of the time); I'm not sure if that is worth filing as a separate suggestion or may fall out from the bugfix for this enhancement.
verified fixed
89e662e
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-03T17:42:14Z
2003-05-21T12:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/UnresolvedElementsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - New class/interface with wizard *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.ui.ISharedImages; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.ScopeAnalyzer; import org.eclipse.jdt.internal.corext.dom.TypeRules; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Strings; 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.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.ChangeDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.EditDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.InsertDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.RemoveDescription; import org.eclipse.jdt.internal.ui.text.correction.ChangeMethodSignatureProposal.SwapDescription; public class UnresolvedElementsSubProcessor { public static void getVariableProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (selectedNode == null) { return; } // type that defines the variable ITypeBinding binding= null; ITypeBinding declaringTypeBinding= Bindings.getBindingOfParentType(selectedNode); if (declaringTypeBinding == null) { return; } // possible type kind of the node boolean suggestVariablePropasals= true; int typeKind= 0; while (selectedNode instanceof ParenthesizedExpression) { selectedNode= ((ParenthesizedExpression) selectedNode).getExpression(); } Name node= null; switch (selectedNode.getNodeType()) { case ASTNode.SIMPLE_NAME: node= (SimpleName) selectedNode; ASTNode parent= node.getParent(); if (parent instanceof MethodInvocation && node.equals(((MethodInvocation)parent).getExpression())) { typeKind= SimilarElementsRequestor.CLASSES; } else if (parent instanceof SimpleType) { suggestVariablePropasals= false; typeKind= SimilarElementsRequestor.REF_TYPES; } break; case ASTNode.QUALIFIED_NAME: QualifiedName qualifierName= (QualifiedName) selectedNode; ITypeBinding qualifierBinding= qualifierName.getQualifier().resolveTypeBinding(); if (qualifierBinding != null) { node= qualifierName.getName(); binding= qualifierBinding; } else { node= qualifierName.getQualifier(); typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariablePropasals= node.isSimpleName(); } if (selectedNode.getParent() instanceof SimpleType) { typeKind= SimilarElementsRequestor.REF_TYPES; suggestVariablePropasals= false; } break; case ASTNode.FIELD_ACCESS: FieldAccess access= (FieldAccess) selectedNode; Expression expression= access.getExpression(); if (expression != null) { binding= expression.resolveTypeBinding(); if (binding != null) { node= access.getName(); } } break; case ASTNode.SUPER_FIELD_ACCESS: binding= declaringTypeBinding.getSuperclass(); node= ((SuperFieldAccess) selectedNode).getName(); break; default: } if (node == null) { return; } // add type proposals if (typeKind != 0) { int relevance= Character.isUpperCase(ASTResolving.getSimpleName(node).charAt(0)) ? 3 : 0; addSimilarTypeProposals(typeKind, cu, node, relevance + 1, proposals); addNewTypeProposals(cu, node, SimilarElementsRequestor.REF_TYPES, relevance, proposals); } if (!suggestVariablePropasals) { return; } SimpleName simpleName= node.isSimpleName() ? (SimpleName) node : ((QualifiedName) node).getName(); addSimilarVariableProposals(cu, astRoot, simpleName, proposals); // new variables ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); ITypeBinding senderBinding= binding != null ? binding : declaringTypeBinding; if (senderBinding.isFromSource() && targetCU != null && JavaModelUtil.isEditable(targetCU)) { String label; Image image; if (binding == null) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.description", simpleName.getIdentifier()); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), binding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); } proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image)); if (binding == null && senderBinding.isAnonymous()) { ASTNode anonymDecl= astRoot.findDeclaringNode(senderBinding); if (anonymDecl != null) { senderBinding= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!senderBinding.isAnonymous()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createfield.other.description", new Object[] { simpleName.getIdentifier(), senderBinding.getName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PUBLIC); proposals.add(new NewVariableCompletionProposal(label, targetCU, NewVariableCompletionProposal.FIELD, simpleName, senderBinding, 6, image)); } } } } if (binding == null) { BodyDeclaration bodyDeclaration= ASTResolving.findParentBodyDeclaration(node); int type= bodyDeclaration.getNodeType(); if (type == ASTNode.METHOD_DECLARATION) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createparameter.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.PARAM, simpleName, null, 5, image)); } if (type == ASTNode.METHOD_DECLARATION || type == ASTNode.INITIALIZER) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createlocal.description", simpleName.getIdentifier()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); proposals.add(new NewVariableCompletionProposal(label, cu, NewVariableCompletionProposal.LOCAL, simpleName, null, 7, image)); } if (node.getParent().getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) node.getParent(); if (assignment.getLeftHandSide() == node && assignment.getParent().getNodeType() == ASTNode.EXPRESSION_STATEMENT) { ASTNode statement= assignment.getParent(); ASTRewrite rewrite= new ASTRewrite(statement.getParent()); rewrite.markAsRemoved(statement); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.removestatement.description"); //$NON-NLS-1$ Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 4, image); proposal.ensureNoModifications(); proposals.add(proposal); } } } } private static void addSimilarVariableProposals(ICompilationUnit cu, CompilationUnit astRoot, SimpleName node, Collection proposals) { IBinding[] varsInScope= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(node, ScopeAnalyzer.VARIABLES); if (varsInScope.length > 0) { // avoid corrections like int i= i; String assignedName= null; ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { assignedName= ((VariableDeclarationFragment) parent).getName().getIdentifier(); } ITypeBinding guessedType= ASTResolving.guessBindingForReference(node); if (astRoot.getAST().resolveWellKnownType("java.lang.Object") == guessedType) { //$NON-NLS-1$ guessedType= null; // too many suggestions } String identifier= node.getIdentifier(); for (int i= 0; i < varsInScope.length; i++) { IVariableBinding curr= (IVariableBinding) varsInScope[i]; String currName= curr.getName(); if (!currName.equals(assignedName)) { int relevance= 0; if (NameMatcher.isSimilarName(currName, identifier)) { relevance += 3; // variable with a similar name than the unresolved variable } ITypeBinding varType= curr.getType(); if (guessedType != null && varType != null && TypeRules.canAssign(guessedType, varType)) { relevance += 2; // unresolved variable can be assign to this variable } if (relevance > 0) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changevariable.description", currName); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, cu, node.getStartPosition(), node.getLength(), currName, relevance)); } } } } } public static void getTypeProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } int kind= SimilarElementsRequestor.ALL_TYPES; ASTNode parent= selectedNode.getParent(); while (parent.getLength() == selectedNode.getLength()) { // get parent of type or variablefragment parent= parent.getParent(); } switch (parent.getNodeType()) { case ASTNode.TYPE_DECLARATION: TypeDeclaration typeDeclaration=(TypeDeclaration) parent; if (typeDeclaration.superInterfaces().contains(selectedNode)) { kind= SimilarElementsRequestor.INTERFACES; } else if (selectedNode.equals(typeDeclaration.getSuperclass())) { kind= SimilarElementsRequestor.CLASSES; } break; case ASTNode.METHOD_DECLARATION: MethodDeclaration methodDeclaration= (MethodDeclaration) parent; if (methodDeclaration.thrownExceptions().contains(selectedNode)) { kind= SimilarElementsRequestor.CLASSES; } else if (selectedNode.equals(methodDeclaration.getReturnType())) { kind= SimilarElementsRequestor.ALL_TYPES | SimilarElementsRequestor.VOIDTYPE; } break; case ASTNode.INSTANCEOF_EXPRESSION: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.THROW_STATEMENT: kind= SimilarElementsRequestor.REF_TYPES; break; case ASTNode.CLASS_INSTANCE_CREATION: if (((ClassInstanceCreation) parent).getAnonymousClassDeclaration() == null) { kind= SimilarElementsRequestor.CLASSES; } else { kind= SimilarElementsRequestor.REF_TYPES; } break; case ASTNode.SINGLE_VARIABLE_DECLARATION: int superParent= parent.getParent().getNodeType(); if (superParent == ASTNode.CATCH_CLAUSE) { kind= SimilarElementsRequestor.CLASSES; } break; default: } Name node= null; if (selectedNode instanceof SimpleType) { node= ((SimpleType) selectedNode).getName(); } else if (selectedNode instanceof ArrayType) { Type elementType= ((ArrayType) selectedNode).getElementType(); if (elementType.isSimpleType()) { node= ((SimpleType) elementType).getName(); } } else if (selectedNode instanceof Name) { node= (Name) selectedNode; } else { return; } // change to simlar type proposals addSimilarTypeProposals(kind, cu, node, 3, proposals); // add type addNewTypeProposals(cu, node, kind, 0, proposals); } private static void addSimilarTypeProposals(int kind, ICompilationUnit cu, Name node, int relevance, Collection proposals) throws CoreException { SimilarElement[] elements= SimilarElementsRequestor.findSimilarElement(cu, node, kind); // try to resolve type in context -> highest severity String resolvedTypeName= null; ITypeBinding binding= ASTResolving.guessBindingForTypeReference(node); if (binding != null) { if (binding.isArray()) { binding= binding.getElementType(); } resolvedTypeName= binding.getQualifiedName(); proposals.add(createTypeRefChangeProposal(cu, resolvedTypeName, node, relevance + 2)); } // add all similar elements for (int i= 0; i < elements.length; i++) { SimilarElement elem= elements[i]; if ((elem.getKind() & SimilarElementsRequestor.ALL_TYPES) != 0) { String fullName= elem.getName(); if (!fullName.equals(resolvedTypeName)) { proposals.add(createTypeRefChangeProposal(cu, fullName, node, relevance)); } } } } private static CUCorrectionProposal createTypeRefChangeProposal(ICompilationUnit cu, String fullName, Name node, int relevance) throws CoreException { TextBuffer buffer= null; try { buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource()); CUCorrectionProposal proposal= new CUCorrectionProposal("", cu, 0); //$NON-NLS-1$ ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String simpleName= importRewrite.addImport(fullName); TextEdit root= proposal.getRootTextEdit(); if (!importRewrite.isEmpty()) { root.addChild(importRewrite.createEdit(buffer)); //$NON-NLS-1$ } String packName= Signature.getQualifier(fullName); String[] arg= { simpleName, packName }; if (node.isSimpleName() && simpleName.equals(((SimpleName) node).getIdentifier())) { // import only proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL)); proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importtype.description", arg)); //$NON-NLS-1$ proposal.setRelevance(relevance + 20); } else { root.addChild(new ReplaceEdit(node.getStartPosition(), node.getLength(), simpleName)); //$NON-NLS-1$ if (packName.length() == 0) { proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.nopack.description", simpleName)); //$NON-NLS-1$ } else { proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetype.description", arg)); //$NON-NLS-1$ } proposal.setRelevance(relevance); } return proposal; } finally { if (buffer != null) TextBuffer.release(buffer); } } private static void addNewTypeProposals(ICompilationUnit cu, Name refNode, int kind, int relevance, Collection proposals) throws JavaModelException { Name node= refNode; do { String typeName= ASTResolving.getSimpleName(node); Name qualifier= null; // only propose to create types for qualifiers when the name starts with upper case boolean isPossibleName= Character.isUpperCase(typeName.charAt(0)) || (node == refNode); if (isPossibleName) { IPackageFragment enclosingPackage= null; IType enclosingType= null; if (node.isSimpleName()) { enclosingPackage= (IPackageFragment) cu.getParent(); // don't sugest member type, user can select it in wizard } else { Name qualifierName= ((QualifiedName) node).getQualifier(); // 24347 // IBinding binding= qualifierName.resolveBinding(); // if (binding instanceof ITypeBinding) { // enclosingType= Binding2JavaModel.find((ITypeBinding) binding, cu.getJavaProject()); IJavaElement[] res= cu.codeSelect(qualifierName.getStartPosition(), qualifierName.getLength()); if (res!= null && res.length > 0 && res[0] instanceof IType) { enclosingType= (IType) res[0]; } else { qualifier= qualifierName; enclosingPackage= JavaModelUtil.getPackageFragmentRoot(cu).getPackageFragment(ASTResolving.getFullName(qualifierName)); } } // new top level type if (enclosingPackage != null && !enclosingPackage.getCompilationUnit(typeName + ".java").exists()) { //$NON-NLS-1$ if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingPackage, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingPackage, relevance)); } } // new member type if (enclosingType != null && !enclosingType.isReadOnly() && !enclosingType.getType(typeName).exists()) { if ((kind & SimilarElementsRequestor.CLASSES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, true, enclosingType, relevance)); } if ((kind & SimilarElementsRequestor.INTERFACES) != 0) { proposals.add(new NewCUCompletionUsingWizardProposal(cu, node, false, enclosingType, relevance)); } } } node= qualifier; } while (node != null); } public static void getMethodProposals(IInvocationContext context, IProblemLocation problem, boolean needsNewName, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (!(selectedNode instanceof SimpleName)) { return; } SimpleName nameNode= (SimpleName) selectedNode; List arguments; Expression sender; boolean isSuperInvocation; ASTNode invocationNode= nameNode.getParent(); if (invocationNode instanceof MethodInvocation) { MethodInvocation methodImpl= (MethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getExpression(); isSuperInvocation= false; } else if (invocationNode instanceof SuperMethodInvocation) { SuperMethodInvocation methodImpl= (SuperMethodInvocation) invocationNode; arguments= methodImpl.arguments(); sender= methodImpl.getQualifier(); isSuperInvocation= true; } else { return; } String methodName= nameNode.getIdentifier(); int nArguments= arguments.size(); // corrections IBinding[] bindings= (new ScopeAnalyzer(astRoot)).getDeclarationsInScope(nameNode, ScopeAnalyzer.METHODS); ArrayList parameterMismatchs= new ArrayList(); for (int i= 0; i < bindings.length; i++) { IMethodBinding binding= (IMethodBinding) bindings[i]; String curr= binding.getName(); if (curr.equals(methodName) && needsNewName) { parameterMismatchs.add(binding); } else if (binding.getParameterTypes().length == nArguments && NameMatcher.isSimilarName(methodName, curr)) { String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changemethod.description", curr); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), curr, 6)); } } addParameterMissmatchProposals(context, problem, parameterMismatchs, invocationNode, arguments, proposals); // new method ITypeBinding binding= null; if (sender != null) { binding= sender.resolveTypeBinding(); } else { binding= Bindings.getBindingOfParentType(invocationNode); if (isSuperInvocation && binding != null) { binding= binding.getSuperclass(); } } if (binding != null && binding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, binding); if (targetCU != null) { String label; Image image; String sig= getMethodSignature(methodName, arguments); if (cu.equals(targetCU)) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.description", sig); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PRIVATE); } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", new Object[] { sig, targetCU.getElementName() } ); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); } proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); if (binding.isAnonymous() && cu.equals(targetCU) && sender == null && Bindings.findMethodInHierarchy(binding, methodName, null) == null) { // no covering method ASTNode anonymDecl= astRoot.findDeclaringNode(binding); if (anonymDecl != null) { binding= Bindings.getBindingOfParentType(anonymDecl.getParent()); if (!binding.isAnonymous()) { String[] args= new String[] { sig, binding.getName() }; label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createmethod.other.description", args); //$NON-NLS-1$ image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PROTECTED); proposals.add(new NewMethodCompletionProposal(label, targetCU, invocationNode, arguments, binding, 5, image)); } } } } } if (!isSuperInvocation) { ASTNode parent= invocationNode.getParent(); while (parent instanceof Expression && parent.getNodeType() != ASTNode.CAST_EXPRESSION) { parent= parent.getParent(); } if (!isSuperInvocation && parent instanceof CastExpression) { addMissingCastParentsProposal(cu, (CastExpression) parent, sender, nameNode, getArgumentTypes(arguments), proposals); } } } private static void addMissingCastParentsProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection proposals) throws CoreException { ITypeBinding castType= expression.getType().resolveBinding(); if (castType == null) { return; } if (paramTypes != null) { if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) { return; } } else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) { return; } ITypeBinding bindingToCast= accessExpression.resolveTypeBinding(); if (bindingToCast != null && !TypeRules.canCast(castType, bindingToCast)) { return; } IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes); if (res != null) { AST ast= expression.getAST(); ASTRewrite rewrite= new ASTRewrite(expression.getParent()); CastExpression newCast= ast.newCastExpression(); newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType())); newCast.setExpression((Expression) rewrite.createCopy(accessExpression)); ParenthesizedExpression parents= ast.newParenthesizedExpression(); parents.setExpression(newCast); ASTNode node= rewrite.createCopy(expression.getExpression()); rewrite.markAsReplaced(expression, node); rewrite.markAsReplaced(accessExpression, parents); String label= CorrectionMessages.getString("UnresolvedElementsSubProcessor.missingcastbrackets.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); } } private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocation problem, List similarElements, ASTNode invocationNode, List arguments, Collection proposals) throws CoreException { int nSimilarElements= similarElements.size(); ITypeBinding[] argTypes= getArgumentTypes(arguments); if (argTypes == null || nSimilarElements == 0) { return; } for (int i= 0; i < nSimilarElements; i++) { IMethodBinding elem = (IMethodBinding) similarElements.get(i); int diff= elem.getParameterTypes().length - argTypes.length; if (diff == 0) { int nProposals= proposals.size(); doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals); if (nProposals != proposals.size()) { return; // only suggest for one method (avoid duplicated proposals) } } else if (diff > 0) { doMoreParameters(context, problem, invocationNode, arguments, argTypes, elem, proposals); } else { doMoreArguments(context, problem, invocationNode, arguments, argTypes, elem, proposals); } } } private static void doMoreParameters(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= paramTypes.length - argTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < paramTypes.length; i++) { if (k < argTypes.length && TypeRules.canAssign(argTypes[k], paramTypes[i])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); // add arguments { String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addarguments.description", arg); //$NON-NLS-1$ } AddArgumentCorrectionProposal proposal= new AddArgumentCorrectionProposal(label, context.getCompilationUnit(), invocationNode, indexSkipped, paramTypes, 8); proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD)); proposal.ensureNoModifications(); proposals.add(proposal); } // remove parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; ITypeBinding[] changedTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; changeDesc[idx]= new RemoveDescription(); changedTypes[i]= paramTypes[idx]; } String[] arg= new String[] { getMethodSignature(methodBinding, !cu.equals(targetCU)), getTypeNames(changedTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image); proposals.add(proposal); } } private static String getTypeNames(ITypeBinding[] types) { StringBuffer buf= new StringBuffer(); for (int i= 0; i < types.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(types[i].getName()); } return buf.toString(); } private static String getArgumentName(ICompilationUnit cu, List arguments, int index) { String def= String.valueOf(index + 1); ASTNode expr= (ASTNode) arguments.get(index); if (expr.getLength() > 18) { return def; } try { String str= cu.getBuffer().getText(expr.getStartPosition(), expr.getLength()); for (int i= 0; i < str.length(); i++) { if (Strings.isLineDelimiterChar(str.charAt(i))) { return def; } } ASTMatcher matcher= new ASTMatcher(); for (int i= 0; i < arguments.size(); i++) { if (i != index && matcher.safeSubtreeMatch(expr, arguments.get(i))) { return def; } } return '\'' + str + '\''; } catch (JavaModelException e) { JavaPlugin.log(e); } return def; } private static void doMoreArguments(IInvocationContext context, IProblemLocation problem, ASTNode invocationNode, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int k= 0, nSkipped= 0; int diff= argTypes.length - paramTypes.length; int[] indexSkipped= new int[diff]; for (int i= 0; i < argTypes.length; i++) { if (k < paramTypes.length && TypeRules.canAssign(argTypes[i], paramTypes[k])) { k++; // match } else { if (nSkipped >= diff) { return; // too different } indexSkipped[nSkipped++]= i; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); // remove arguments { ASTNode selectedNode= problem.getCoveringNode(astRoot); ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); for (int i= diff - 1; i >= 0; i--) { rewrite.markAsRemoved((Expression) arguments.get(indexSkipped[i])); } String[] arg= new String[] { getMethodSignature(methodBinding, false) }; String label; if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removeargument.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.removearguments.description", arg); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); } // add parameters if (!declaringType.isFromSource()) { return; } ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { boolean isDifferentCU= !cu.equals(targetCU); if (isDifferentCU && isImplicitConstructor(methodBinding, targetCU)) { return; } ChangeDescription[] changeDesc= new ChangeDescription[argTypes.length]; ITypeBinding[] changeTypes= new ITypeBinding[diff]; for (int i= diff - 1; i >= 0; i--) { int idx= indexSkipped[i]; Expression arg= (Expression) arguments.get(idx); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; ITypeBinding newType= Bindings.normalizeTypeBinding(argTypes[idx]); if (newType == null) { newType= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } changeDesc[idx]= new InsertDescription(newType, name); changeTypes[i]= newType; } String[] arg= new String[] { getMethodSignature(methodBinding, isDifferentCU), getTypeNames(changeTypes) }; String label; if (methodBinding.isConstructor()) { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.constr.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.constr.description", arg); //$NON-NLS-1$ } } else { if (diff == 1) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparam.description", arg); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addparams.description", arg); //$NON-NLS-1$ } } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image); proposals.add(proposal); } } private static boolean isImplicitConstructor(IMethodBinding meth, ICompilationUnit targetCU) { if (meth.isConstructor() && meth.getParameterTypes().length == 0) { IMethodBinding[] bindings= meth.getDeclaringClass().getDeclaredMethods(); // implicit constructors must be the only constructor for (int i= 0; i < bindings.length; i++) { IMethodBinding curr= bindings[i]; if (curr.isConstructor() && curr != meth) { return false; } } CompilationUnit unit= AST.parsePartialCompilationUnit(targetCU, 0, true); return unit.findDeclaringNode(meth.getKey()) == null; } return false; } private static String getMethodSignature(IMethodBinding binding, boolean inOtherCU) { StringBuffer buf= new StringBuffer(); if (inOtherCU && !binding.isConstructor()) { buf.append(binding.getDeclaringClass().getName()).append('.'); } buf.append(binding.getName()); return getMethodSignature(buf.toString(), binding.getParameterTypes()); } private static String getMethodSignature(String name, List args) { ITypeBinding[] params= new ITypeBinding[args.size()]; for (int i= 0; i < args.size(); i++) { Expression expr= (Expression) args.get(i); ITypeBinding curr= Bindings.normalizeTypeBinding(expr.resolveTypeBinding()); if (curr == null) { curr= expr.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } params[i]= curr; } return getMethodSignature(name, params); } private static String getMethodSignature(String name, ITypeBinding[] params) { StringBuffer buf= new StringBuffer(); buf.append(name).append('('); for (int i= 0; i < params.length; i++) { if (i > 0) { buf.append(", "); //$NON-NLS-1$ } buf.append(params[i].getName()); } buf.append(')'); return buf.toString(); } private static void doEqualNumberOfParameters(IInvocationContext context, ASTNode invocationNode, IProblemLocation problem, List arguments, ITypeBinding[] argTypes, IMethodBinding methodBinding, Collection proposals) throws CoreException { ITypeBinding[] paramTypes= methodBinding.getParameterTypes(); int[] indexOfDiff= new int[paramTypes.length]; int nDiffs= 0; for (int n= 0; n < argTypes.length; n++) { if (!TypeRules.canAssign(argTypes[n], paramTypes[n])) { indexOfDiff[nDiffs++]= n; } } ITypeBinding declaringType= methodBinding.getDeclaringClass(); ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode nameNode= problem.getCoveringNode(astRoot); if (nameNode == null) { return; } if (nDiffs == 0) { if (nameNode.getParent() instanceof MethodInvocation) { MethodInvocation inv= (MethodInvocation) nameNode.getParent(); if (inv.getExpression() == null) { addQualifierToOuterProposal(context, inv, methodBinding, proposals); } } return; } if (nDiffs == 1) { // one argument missmatching: try to fix int idx= indexOfDiff[0]; Expression nodeToCast= (Expression) arguments.get(idx); ITypeBinding castType= paramTypes[idx]; ITypeBinding binding= nodeToCast.resolveTypeBinding(); if (binding == null || TypeRules.canCast(castType, binding)) { String castTypeName= castType.getQualifiedName(); ASTRewriteCorrectionProposal proposal= LocalCorrectionsSubProcessor.createCastProposal(context, castTypeName, nodeToCast, 6); String[] arg= new String[] { getArgumentName(cu, arguments, idx), castTypeName}; proposal.setDisplayName(CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.addargumentcast.description", arg)); //$NON-NLS-1$ proposal.ensureNoModifications(); proposals.add(proposal); } } if (nDiffs == 2) { // try to swap int idx1= indexOfDiff[0]; int idx2= indexOfDiff[1]; boolean canSwap= TypeRules.canAssign(argTypes[idx1], paramTypes[idx2]) && TypeRules.canAssign(argTypes[idx2], paramTypes[idx1]); if (canSwap) { Expression arg1= (Expression) arguments.get(idx1); Expression arg2= (Expression) arguments.get(idx2); ASTRewrite rewrite= new ASTRewrite(arg1.getParent()); rewrite.markAsReplaced(arg1, rewrite.createCopy(arg2)); rewrite.markAsReplaced(arg2, rewrite.createCopy(arg1)); { String[] arg= new String[] { getArgumentName(cu, arguments, idx1), getArgumentName(cu, arguments, idx2) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swaparguments.description", arg); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { changeDesc[idx1]= new SwapDescription(idx2); } ITypeBinding[] swappedTypes= new ITypeBinding[] { paramTypes[idx1], paramTypes[idx2] }; String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getTypeNames(swappedTypes) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.swapparams.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 5, image); proposals.add(proposal); } } return; } } if (declaringType.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, declaringType); if (targetCU != null) { ChangeDescription[] changeDesc= new ChangeDescription[paramTypes.length]; for (int i= 0; i < nDiffs; i++) { int diffIndex= indexOfDiff[i]; Expression arg= (Expression) arguments.get(diffIndex); String name= arg instanceof SimpleName ? ((SimpleName) arg).getIdentifier() : null; changeDesc[diffIndex]= new EditDescription(argTypes[diffIndex], name); } String[] args= new String[] { getMethodSignature(methodBinding, !targetCU.equals(cu)), getMethodSignature(methodBinding.getName(), arguments) }; String label; if (methodBinding.isConstructor()) { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.constr.description", args); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changeparamsignature.description", args); //$NON-NLS-1$ } Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ChangeMethodSignatureProposal proposal= new ChangeMethodSignatureProposal(label, targetCU, invocationNode, methodBinding, changeDesc, 7, image); proposals.add(proposal); } } } private static ITypeBinding[] getArgumentTypes(List arguments) { ITypeBinding[] res= new ITypeBinding[arguments.size()]; for (int i= 0; i < res.length; i++) { Expression expression= (Expression) arguments.get(i); ITypeBinding curr= expression.resolveTypeBinding(); if (curr == null) { return null; } curr= Bindings.normalizeTypeBinding(curr); if (curr == null) { curr= expression.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } res[i]= curr; } return res; } private static void addQualifierToOuterProposal(IInvocationContext context, MethodInvocation invocationNode, IMethodBinding binding, Collection proposals) throws CoreException { ITypeBinding declaringType= binding.getDeclaringClass(); ITypeBinding parentType= Bindings.getBindingOfParentType(invocationNode); ITypeBinding currType= parentType; boolean isInstanceMethod= !Modifier.isStatic(binding.getModifiers()); while (currType != null && !Bindings.isSuperType(declaringType, currType)) { if (isInstanceMethod && Modifier.isStatic(currType.getModifiers())) { return; } currType= currType.getDeclaringClass(); } if (currType == null || currType == parentType) { return; } ASTRewrite rewrite= new ASTRewrite(invocationNode.getParent()); AST ast= invocationNode.getAST(); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.changetoouter.description", currType.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 8, image); proposal.ensureNoModifications(); proposals.add(proposal); String qualifier= proposal.addImport(currType); Name name= ASTNodeFactory.newName(ast, qualifier); Expression newExpression; if (isInstanceMethod) { ThisExpression expr= ast.newThisExpression(); expr.setQualifier(name); newExpression= expr; } else { newExpression= name; } rewrite.markAsInsert(invocationNode, ASTNodeConstants.EXPRESSION, newExpression, null); } public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } ITypeBinding targetBinding= null; List arguments= null; IMethodBinding recursiveConstructor= null; int type= selectedNode.getNodeType(); if (type == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; IBinding binding= creation.getName().resolveBinding(); if (binding instanceof ITypeBinding) { targetBinding= (ITypeBinding) binding; arguments= creation.arguments(); } } else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding.getSuperclass(); arguments= ((SuperConstructorInvocation) selectedNode).arguments(); } } else if (type == ASTNode.CONSTRUCTOR_INVOCATION) { ITypeBinding typeBinding= Bindings.getBindingOfParentType(selectedNode); if (typeBinding != null && !typeBinding.isAnonymous()) { targetBinding= typeBinding; arguments= ((ConstructorInvocation) selectedNode).arguments(); recursiveConstructor= ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding(); } } if (targetBinding == null) { return; } IMethodBinding[] methods= targetBinding.getDeclaredMethods(); ArrayList similarElements= new ArrayList(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && recursiveConstructor != curr) { similarElements.add(curr); // similar elements can contain a implicit default constructor } } addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals); if (targetBinding.isFromSource()) { ICompilationUnit targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetBinding); if (targetCU != null) { String[] args= new String[] { getMethodSignature( targetBinding.getName(), arguments) }; String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.createconstructor.description", args); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC); proposals.add(new NewMethodCompletionProposal(label, targetCU, selectedNode, arguments, targetBinding, 5, image)); } } } public static void getAmbiguosTypeReferenceProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); int offset= problem.getOffset(); int len= problem.getLength(); IJavaElement[] elements= cu.codeSelect(offset, len); for (int i= 0; i < elements.length; i++) { IJavaElement curr= elements[i]; if (curr instanceof IType) { String qualifiedTypeName= JavaModelUtil.getFullyQualifiedName((IType) curr); String label= CorrectionMessages.getFormattedString("UnresolvedElementsSubProcessor.importexplicit.description", qualifiedTypeName); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_IMPDECL); CUCorrectionProposal proposal= new CUCorrectionProposal(label, cu, 5, image); TextBuffer buffer= null; try { buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource()); ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings()); importRewrite.addImport(qualifiedTypeName); importRewrite.setFindAmbiguosImports(true); proposal.getRootTextEdit().addChild(importRewrite.createEdit(buffer)); proposals.add(proposal); } finally { if (buffer != null) TextBuffer.release(buffer); } } } } }
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
org.eclipse.jdt.ui/ui
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/IStatusContextViewer.java
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
org.eclipse.jdt.ui/ui
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/JavaStatusContextViewer.java
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
org.eclipse.jdt.ui/ui
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/SourceContextViewer.java
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
org.eclipse.jdt.ui/ui
47,856
Bug 47856 Unusable UI due to custom colors setup for editor [misc]
I have non-default colors set for syntax highlighting in Java editor (black background, white text, yellow reserved words, green comments, ...). However this causes the some important Eclipse UI features to become unusable due to the fact they leave white (default) background but use my custom (non-default) foreground colors. For my choice of colors these features don't show anything! I've seen this problem since 2.0.0 and seems like it has not been reported and still reproducible in 2.1.2. Here is the list of "misbehaving" UI features: 1) Preferences | Java | Code Formatter | "New Lines" tab; 2) Source | Externalize Strings... | "Context: " view; 3) There may be other places that unconditionally use default background to display/preview java code.
resolved fixed
b80ecbb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:23:40Z
2003-12-02T01:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/TextStatusContextViewer.java
32,022
Bug 32022 Indirect static proposal: Wrong compiler positions
QuickFix produce wrong code while trying to fix the way class accesses field of the static member of the static class instance, i.e.: instance.staticField.flag = true; Where "instance" is the static field of the same class as caller, "staticField" its static member (instance of inner class StaticField) and the "flag" is a public field. Code is a bit meaningless, but there is no matter. Using QuickFix results in: StaticField.flag = true; while should be: InstanceClass.staticField.flag = true; or staticField.flag = true;
verified fixed
2ec6921
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:41:19Z
2003-02-17T16:40:00Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/quickfix/LocalCorrectionsQuickFixTest.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.tests.quickfix; import java.util.ArrayList; import java.util.Hashtable; import junit.framework.Test; import junit.framework.TestSuite; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.tests.core.ProjectTestSetup; import org.eclipse.jdt.internal.corext.template.CodeTemplates; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal; public class LocalCorrectionsQuickFixTest extends QuickFixTest { private static final Class THIS= LocalCorrectionsQuickFixTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public LocalCorrectionsQuickFixTest(String name) { super(name); } public static Test allTests() { return new ProjectTestSetup(new TestSuite(THIS)); } public static Test suite() { if (true) { return allTests(); } else { TestSuite suite= new TestSuite(); suite.addTest(new LocalCorrectionsQuickFixTest("testIndirectStaticAccess_bug40880")); return new ProjectTestSetup(suite); } } protected void setUp() throws Exception { Hashtable options= JavaCore.getDefaultOptions(); options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE); options.put(JavaCore.FORMATTER_TAB_SIZE, "4"); options.put(JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER, JavaCore.ERROR); JavaCore.setOptions(options); IPreferenceStore store= JavaPlugin.getDefault().getPreferenceStore(); store.setValue(PreferenceConstants.CODEGEN_ADD_COMMENTS, false); CodeTemplates.getCodeTemplate(CodeTemplates.CATCHBLOCK).setPattern(""); CodeTemplates.getCodeTemplate(CodeTemplates.CONSTRUCTORSTUB).setPattern(""); CodeTemplates.getCodeTemplate(CodeTemplates.METHODSTUB).setPattern(""); fJProject1= ProjectTestSetup.getProject(); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.clear(fJProject1, ProjectTestSetup.getDefaultClasspath()); } public void testFieldAccessToStatic() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.File;\n"); buf.append("public class E {\n"); buf.append(" public char foo() {\n"); buf.append(" return (new File(\"x.txt\")).separatorChar;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.File;\n"); buf.append("public class E {\n"); buf.append(" public char foo() {\n"); buf.append(" return File.separatorChar;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testInheritedAccessOnStatic() throws Exception { IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null); StringBuffer buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class A {\n"); buf.append(" public static void foo() {\n"); buf.append(" }\n"); buf.append("}\n"); pack0.createCompilationUnit("A.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class B extends A {\n"); buf.append("}\n"); pack0.createCompilationUnit("B.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import pack.B;\n"); buf.append("public class E {\n"); buf.append(" public void foo(B b) {\n"); buf.append(" b.foo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 3); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import pack.B;\n"); buf.append("public class E {\n"); buf.append(" public void foo(B b) {\n"); buf.append(" B.foo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import pack.A;\n"); buf.append("import pack.B;\n"); buf.append("public class E {\n"); buf.append(" public void foo(B b) {\n"); buf.append(" A.foo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(2); String preview3= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" }\n"); buf.append("}\n"); String expected3= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 }); } public void testQualifiedAccessToStatic() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Thread t) {\n"); buf.append(" t.sleep(10);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Thread t) {\n"); buf.append(" Thread.sleep(10);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testThisAccessToStatic() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" this.goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" E.goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" this.goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testThisAccessToStaticField() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static int fCount;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" this.fCount= 1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public static int fCount;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" E.fCount= 1;\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int fCount;\n"); buf.append("\n"); buf.append(" public void foo() {\n"); buf.append(" this.fCount= 1;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInVarDecl() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Object o) {\n"); buf.append(" Thread th= o;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Object o) {\n"); buf.append(" Thread th= (Thread) o;\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Object o) {\n"); buf.append(" Object th= o;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInVarDecl2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class Container {\n"); buf.append(" public List[] getLists() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("Container.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Container c) {\n"); buf.append(" ArrayList[] lists= c.getLists();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Container c) {\n"); buf.append(" ArrayList[] lists= (ArrayList[]) c.getLists();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Container c) {\n"); buf.append(" List[] lists= c.getLists();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInVarDecl3() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" Thread th= foo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 0); } public void testCastMissingInFieldDecl() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" int time= System.currentTimeMillis();\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" int time= (int) System.currentTimeMillis();\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" long time= System.currentTimeMillis();\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastMissingInAssignment() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Iterator;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Iterator iter) {\n"); buf.append(" String str;\n"); buf.append(" str= iter.next();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.Iterator;\n"); buf.append("public class E {\n"); buf.append(" public void foo(Iterator iter) {\n"); buf.append(" String str;\n"); buf.append(" str= (String) iter.next();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testCastMissingInExpression() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public String[] foo(List list) {\n"); buf.append(" return list.toArray(new List[list.size()]);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public String[] foo(List list) {\n"); buf.append(" return (String[]) list.toArray(new List[list.size()]);\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public Object[] foo(List list) {\n"); buf.append(" return list.toArray(new List[list.size()]);\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testCastOnCastExpression() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public void foo(List list) {\n"); buf.append(" ArrayList a= (Cloneable) list;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public void foo(List list) {\n"); buf.append(" ArrayList a= (ArrayList) list;\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.util.ArrayList;\n"); buf.append("import java.util.List;\n"); buf.append("public class E {\n"); buf.append(" public void foo(List list) {\n"); buf.append(" Cloneable a= (Cloneable) list;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUncaughtException() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUncaughtException2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public String goo() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo().substring(2);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public String goo() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" goo().substring(2);\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public String goo() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo().substring(2);\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUncaughtExceptionRemoveMoreSpecific() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.net.SocketException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() throws SocketException {\n"); buf.append(" this.goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.net.SocketException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" this.goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.net.SocketException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() throws SocketException {\n"); buf.append(" try {\n"); buf.append(" this.goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUncaughtExceptionToSurroundingTry() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() throws IOException, ParseException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" E.goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 3); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() throws IOException, ParseException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() throws ParseException {\n"); buf.append(" try {\n"); buf.append(" E.goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() throws IOException, ParseException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" try {\n"); buf.append(" E.goo();\n"); buf.append(" } catch (ParseException e1) {\n"); buf.append(" }\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(2); String preview3= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public static void goo() throws IOException, ParseException {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" E.goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } catch (ParseException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected3= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2, preview3 }, new String[] { expected1, expected2, expected3 }); } public void testUncaughtExceptionOnSuper1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.FileInputStream;\n"); buf.append("public class E extends FileInputStream {\n"); buf.append(" public E() {\n"); buf.append(" super(\"x\");\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.FileInputStream;\n"); buf.append("import java.io.FileNotFoundException;\n"); buf.append("public class E extends FileInputStream {\n"); buf.append(" public E() throws FileNotFoundException {\n"); buf.append(" super(\"x\");\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUncaughtExceptionOnSuper2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public A() throws Exception {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("A.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends A {\n"); buf.append(" public E() {\n"); buf.append(" super();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends A {\n"); buf.append(" public E() throws Exception {\n"); buf.append(" super();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUncaughtExceptionOnThis() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" this(null);\n"); buf.append(" }\n"); buf.append(" public E(Object x) throws IOException {\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public E() throws IOException {\n"); buf.append(" this(null);\n"); buf.append(" }\n"); buf.append(" public E(Object x) throws IOException {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } boolean BUG_25417= true; public void testUncaughtExceptionDuplicate() throws Exception { if (BUG_25417) { return; } IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class MyException extends Exception {\n"); buf.append("}\n"); pack1.createCompilationUnit("MyException.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void m1() throws IOException {\n"); buf.append(" m2();\n"); buf.append(" }\n"); buf.append(" public void m2() throws IOException, ParseException, MyException {\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void m1() throws IOException, ParseException, MyException {\n"); buf.append(" m2();\n"); buf.append(" }\n"); buf.append(" public void m2() throws IOException, ParseException, MyException {\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void m1() throws IOException {\n"); buf.append(" try {\n"); buf.append(" m2();\n"); buf.append(" } catch (ParseException e) {\n"); buf.append(" } catch (MyException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append(" public void m2() throws IOException, ParseException, MyException {\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testMultipleUncaughtExceptions() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException, ParseException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot, 2); // 2 uncaught exceptions assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException, ParseException {\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException, ParseException {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException, ParseException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } catch (ParseException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnneededCatchBlock() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } catch (ParseException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() throws IOException {\n"); buf.append(" }\n"); buf.append(" public void foo() throws ParseException {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnneededCatchBlockSingle() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" goo();\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnneededCatchBlockBug47221() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public Object foo() {\n"); buf.append(" try {\n"); buf.append(" Object o= null;\n"); buf.append(" return o;\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" }\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public Object foo() {\n"); buf.append(" Object o= null;\n"); buf.append(" return o;\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public Object foo() throws IOException {\n"); buf.append(" Object o= null;\n"); buf.append(" return o;\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnneededCatchBlockWithFinally() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void goo() {\n"); buf.append(" }\n"); buf.append(" public void foo() throws IOException {\n"); buf.append(" try {\n"); buf.append(" goo();\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnimplementedMethods() throws Exception { IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import java.io.IOException;\n"); buf.append("public interface Inter {\n"); buf.append(" int getCount(Object[] o) throws IOException;\n"); buf.append("}\n"); pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.Inter;\n"); buf.append("public class E implements Inter{\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.Inter;\n"); buf.append("public abstract class E implements Inter{\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("\n"); buf.append("import test2.Inter;\n"); buf.append("public class E implements Inter{\n"); buf.append("\n"); buf.append(" public int getCount(Object[] o) throws IOException {\n"); buf.append(" return 0;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnimplementedMethods2() throws Exception { IPackageFragment pack2= fSourceFolder.createPackageFragment("test2", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import java.io.IOException;\n"); buf.append("public interface Inter {\n"); buf.append(" int getCount(Object[] o) throws IOException;\n"); buf.append("}\n"); pack2.createCompilationUnit("Inter.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test2;\n"); buf.append("import java.io.IOException;\n"); buf.append("public abstract class InterImpl implements Inter {\n"); buf.append(" protected abstract int[] getMusic() throws IOException;\n"); buf.append("}\n"); pack2.createCompilationUnit("InterImpl.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.InterImpl;\n"); buf.append("public class E extends InterImpl {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot, 2); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import test2.InterImpl;\n"); buf.append("public abstract class E extends InterImpl {\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("\n"); buf.append("import test2.InterImpl;\n"); buf.append("public class E extends InterImpl {\n"); buf.append("\n"); buf.append(" protected int[] getMusic() throws IOException {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("\n"); buf.append(" public int getCount(Object[] o) throws IOException {\n"); buf.append(" return 0;\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testUnitializedVariable() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int s;\n"); buf.append(" try {\n"); buf.append(" s= 1;\n"); buf.append(" } catch (Exception e) {\n"); buf.append(" System.out.println(s);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" int s = 0;\n"); buf.append(" try {\n"); buf.append(" s= 1;\n"); buf.append(" } catch (Exception e) {\n"); buf.append(" System.out.println(s);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUndefinedConstructorInDefaultConstructor1() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class F {\n"); buf.append(" public F(Runnable runnable) {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("F.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("\n"); buf.append(" public E(Runnable runnable) {\n"); buf.append(" super(runnable);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUndefinedConstructorInDefaultConstructor2() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class F {\n"); buf.append(" public F(Runnable runnable) throws IOException {\n"); buf.append(" }\n"); buf.append("\n"); buf.append(" public F(int i, Runnable runnable) {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("F.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 2); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview1= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("\n"); buf.append(" public E(int i, Runnable runnable) {\n"); buf.append(" super(i, runnable);\n"); buf.append(" }\n"); buf.append("}\n"); String expected1= buf.toString(); proposal= (CUCorrectionProposal) proposals.get(1); String preview2= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.io.IOException;\n"); buf.append("\n"); buf.append("public class E extends F {\n"); buf.append("\n"); buf.append(" public E(Runnable runnable) throws IOException {\n"); buf.append(" super(runnable);\n"); buf.append(" }\n"); buf.append("}\n"); String expected2= buf.toString(); assertEqualStringsIgnoreOrder(new String[] { preview1, preview2 }, new String[] { expected1, expected2 }); } public void testNotVisibleConstructorInDefaultConstructor() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class F {\n"); buf.append(" private F() {\n"); buf.append(" }\n"); buf.append(" public F(Runnable runnable) {\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("F.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("\n"); buf.append(" public E(Runnable runnable) {\n"); buf.append(" super(runnable);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnhandledExceptionInDefaultConstructor() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class F {\n"); buf.append(" public F() throws IOException{\n"); buf.append(" }\n"); buf.append("}\n"); pack1.createCompilationUnit("F.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E extends F {\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import java.io.IOException;\n"); buf.append("\n"); buf.append("public class E extends F {\n"); buf.append("\n"); buf.append(" public E() throws IOException {\n"); buf.append(" super();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedPrivateField() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int fCount;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedPrivateField1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int fCount, fColor= fCount;\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int fCount;\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedPrivateField2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int fCount= 0;\n"); buf.append(" public void foo() {\n"); buf.append(" fCount= 1 + 2;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedVariable() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" boolean res= process();\n"); buf.append(" res= (super.hashCode() == 1);\n"); buf.append(" }\n"); buf.append(" public boolean process() {\n"); buf.append(" return true;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" res= (super.hashCode() == 1);\n"); buf.append(" }\n"); buf.append(" public boolean process() {\n"); buf.append(" return true;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedVariable1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private Object[] foo() {\n"); buf.append(" Object[] i, j= new Object[0];\n"); buf.append(" i= j = null;\n"); buf.append(" i= (new Object[] { null, null });\n"); buf.append(" return j;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private Object[] foo() {\n"); buf.append(" Object[] j= new Object[0];\n"); buf.append(" j = null;\n"); buf.append(" return j;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedVariable2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private void foo() {\n"); buf.append(" for (int j= 0, i= 0; i < 3; i++) {\n"); buf.append(" j= i;\n"); buf.append(" };\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private void foo() {\n"); buf.append(" for (int i= 0; i < 3; i++) {\n"); buf.append(" };\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedParam() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_LOCAL, JavaCore.ERROR); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PARAMETER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private void foo(Object str) {\n"); buf.append(" {\n"); buf.append(" str= toString();\n"); buf.append(" str= new String[] { toString(), toString() };\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private void foo() {\n"); buf.append(" {\n"); buf.append(" str= toString();\n"); buf.append(" str= new String[] { toString(), toString() };\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedPrivateMethod() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int fCount;\n"); buf.append(" \n"); buf.append(" private void foo() {\n"); buf.append(" fCount= 1;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int fCount;\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedPrivateConstructor() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" }\n"); buf.append(" \n"); buf.append(" private E(int i) {\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnusedPrivateType() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_PRIVATE_MEMBER, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private class F {\n"); buf.append(" }\n"); buf.append(" \n"); buf.append(" public E() {\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryCast1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" int s = (int) i;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" int s = i;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryCast2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(String s) {\n"); buf.append(" String r = ((String) s);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(String s) {\n"); buf.append(" String r = s;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryCast3() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" int s = ((int) 1 + 2) * 3;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" int s = (1 + 2) * 3;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testSuperfluousSemicolon() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_SUPERFLUOUS_SEMICOLON, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" int s= 1;;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" int s= 1;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testIndirectStaticAccess1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null); StringBuffer buf= new StringBuffer(); buf.append("package other;\n"); buf.append("public class A {\n"); buf.append(" public static final int CONST=1;\n"); buf.append("}\n"); other.createCompilationUnit("A.java", buf.toString(), false, null); IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null); buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class B extends other.A {\n"); buf.append("}\n"); pack0.createCompilationUnit("B.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import pack.B;\n"); buf.append("public class E {\n"); buf.append(" public int foo(B b) {\n"); buf.append(" return B.CONST;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import other.A;\n"); buf.append("import pack.B;\n"); buf.append("public class E {\n"); buf.append(" public int foo(B b) {\n"); buf.append(" return A.CONST;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testIndirectStaticAccess2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment other= fSourceFolder.createPackageFragment("other", false, null); StringBuffer buf= new StringBuffer(); buf.append("package other;\n"); buf.append("public class A {\n"); buf.append(" public static int foo() {\n"); buf.append(" return 1;\n"); buf.append(" }\n"); buf.append("}\n"); other.createCompilationUnit("A.java", buf.toString(), false, null); IPackageFragment pack0= fSourceFolder.createPackageFragment("pack", false, null); buf= new StringBuffer(); buf.append("package pack;\n"); buf.append("public class B extends other.A {\n"); buf.append("}\n"); pack0.createCompilationUnit("B.java", buf.toString(), false, null); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return pack.B.foo();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("\n"); buf.append("import other.A;\n"); buf.append("\n"); buf.append("public class E {\n"); buf.append(" public int foo() {\n"); buf.append(" return A.foo();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testIndirectStaticAccess_bug40880() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_INDIRECT_STATIC_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("class FileType {\n"); buf.append(" public String extension;\n"); buf.append("}\n"); pack1.createCompilationUnit("FileType.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("interface ToolConfigurationSettingsConstants {\n"); buf.append(" FileType FILE_TYPE = null;\n"); buf.append("}\n"); pack1.createCompilationUnit("ToolConfigurationSettingsConstants.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("interface ToolUserSettingsConstants extends ToolConfigurationSettingsConstants {\n"); buf.append("}\n"); pack1.createCompilationUnit("ToolUserSettingsConstants.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" ToolUserSettingsConstants.FILE_TYPE.extension.toLowerCase();\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" ToolConfigurationSettingsConstants.FILE_TYPE.extension.toLowerCase();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryInstanceof1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public boolean foo(String b) {\n"); buf.append(" return (b instanceof String);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public boolean foo(String b) {\n"); buf.append(" return (b != null);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryInstanceof2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNNECESSARY_TYPE_CHECK, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(String b) {\n"); buf.append(" if (b instanceof String && b.getClass() != null) {\n"); buf.append(" System.out.println();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(String b) {\n"); buf.append(" if (b != null && b.getClass() != null) {\n"); buf.append(" System.out.println();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryThrownException1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo(String b) throws IOException {\n"); buf.append(" if (b != null) {\n"); buf.append(" System.out.println();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("public class E {\n"); buf.append(" public void foo(String b) {\n"); buf.append(" if (b != null) {\n"); buf.append(" System.out.println();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnnecessaryThrownException2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNUSED_DECLARED_THROWN_EXCEPTION, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public E(int i) throws IOException, ParseException {\n"); buf.append(" if (i == 0) {\n"); buf.append(" throw new IOException();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("import java.io.IOException;\n"); buf.append("import java.text.ParseException;\n"); buf.append("public class E {\n"); buf.append(" public E(int i) throws IOException {\n"); buf.append(" if (i == 0) {\n"); buf.append(" throw new IOException();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnqualifiedFieldAccess1() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int count;\n"); buf.append(" public E(int i) {\n"); buf.append(" count= i;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int count;\n"); buf.append(" public E(int i) {\n"); buf.append(" this.count= i;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnqualifiedFieldAccess2() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class F {\n"); buf.append(" public int count;\n"); buf.append("}\n"); pack1.createCompilationUnit("F.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private F f= new F();\n"); buf.append(" public E(int i) {\n"); buf.append(" f.count= i;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private F f= new F();\n"); buf.append(" public E(int i) {\n"); buf.append(" this.f.count= i;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnqualifiedFieldAccess3() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class F {\n"); buf.append(" public void setCount(int i) {}\n"); buf.append("}\n"); pack1.createCompilationUnit("F.java", buf.toString(), false, null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private F f= new F();\n"); buf.append(" public E(int i) {\n"); buf.append(" f.setCount(i);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private F f= new F();\n"); buf.append(" public E(int i) {\n"); buf.append(" this.f.setCount(i);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } public void testUnqualifiedFieldAccess4() throws Exception { Hashtable hashtable= JavaCore.getOptions(); hashtable.put(JavaCore.COMPILER_PB_UNQUALIFIED_FIELD_ACCESS, JavaCore.ERROR); JavaCore.setOptions(hashtable); IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int count;\n"); buf.append(" public E(int i) {\n"); buf.append(" class Inner {\n"); buf.append(" public void foo() {\n"); buf.append(" count= 1;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, true); ArrayList proposals= collectCorrections(cu, astRoot); assertNumberOf("proposals", proposals.size(), 1); assertCorrectLabels(proposals); CUCorrectionProposal proposal= (CUCorrectionProposal) proposals.get(0); String preview= proposal.getCompilationUnitChange().getPreviewContent(); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" private int count;\n"); buf.append(" public E(int i) {\n"); buf.append(" class Inner {\n"); buf.append(" public void foo() {\n"); buf.append(" E.this.count= 1;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(preview, buf.toString()); } }
32,022
Bug 32022 Indirect static proposal: Wrong compiler positions
QuickFix produce wrong code while trying to fix the way class accesses field of the static member of the static class instance, i.e.: instance.staticField.flag = true; Where "instance" is the static field of the same class as caller, "staticField" its static member (instance of inner class StaticField) and the "flag" is a public field. Code is a bit meaningless, but there is no matter. Using QuickFix results in: StaticField.flag = true; while should be: InstanceClass.staticField.flag = true; or staticField.flag = true;
verified fixed
2ec6921
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-04T17:41:19Z
2003-02-17T16:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LocalCorrectionsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Renaud Waldura &lt;renaud+eclipse@waldura.com&gt; - Access to static proposal ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.Collection; import java.util.List; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.PrimitiveType.Code; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.java.IInvocationContext; import org.eclipse.jdt.ui.text.java.IProblemLocation; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.ImportRewrite; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.ASTNodeConstants; import org.eclipse.jdt.internal.corext.dom.ASTNodeFactory; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.NewASTRewrite; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSRefactoring; import org.eclipse.jdt.internal.corext.refactoring.nls.NLSUtil; import org.eclipse.jdt.internal.corext.refactoring.surround.ExceptionAnalyzer; import org.eclipse.jdt.internal.corext.refactoring.surround.SurroundWithTryCatchRefactoring; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; 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.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter; import org.eclipse.jdt.internal.ui.refactoring.nls.ExternalizeWizard; /** */ public class LocalCorrectionsSubProcessor { public static void addCastProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { String[] args= problem.getProblemArguments(); if (args.length != 2) { return; } ICompilationUnit cu= context.getCompilationUnit(); String castType= args[1]; CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveredNode(astRoot); if (!(selectedNode instanceof Expression)) { return; } Expression nodeToCast= (Expression) selectedNode; int parentNodeType= selectedNode.getParent().getNodeType(); if (parentNodeType == ASTNode.ASSIGNMENT) { Assignment assign= (Assignment) selectedNode.getParent(); if (selectedNode.equals(assign.getLeftHandSide())) { nodeToCast= assign.getRightHandSide(); } } else if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment frag= (VariableDeclarationFragment) selectedNode.getParent(); if (selectedNode.equals(frag.getName())) { nodeToCast= frag.getInitializer(); } } ITypeBinding binding= nodeToCast.resolveTypeBinding(); if (binding == null || canCast(castType, binding)) { proposals.add(createCastProposal(context, castType, nodeToCast, 5)); } ITypeBinding currBinding= nodeToCast.resolveTypeBinding(); if (currBinding == null || "void".equals(currBinding.getName())) { //$NON-NLS-1$ return; } // change method return statement to actual type if (parentNodeType == ASTNode.RETURN_STATEMENT) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { MethodDeclaration methodDeclaration= (MethodDeclaration) decl; currBinding= Bindings.normalizeTypeBinding(currBinding); if (currBinding == null) { currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } ASTRewrite rewrite= new ASTRewrite(methodDeclaration); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changereturntype.description", currBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); String returnTypeName= proposal.addImport(currBinding); Type newReturnType= ASTNodeFactory.newType(astRoot.getAST(), returnTypeName); rewrite.markAsReplaced(methodDeclaration.getReturnType(), newReturnType); String returnKey= "return"; //$NON-NLS-1$ proposal.markAsLinked(rewrite, newReturnType, true, returnKey); ITypeBinding[] typeSuggestions= ASTResolving.getRelaxingTypes(astRoot.getAST(), currBinding); for (int i= 0; i < typeSuggestions.length; i++) { proposal.addLinkedModeProposal(returnKey, typeSuggestions[i]); } proposal.ensureNoModifications(); proposals.add(proposal); } } if (parentNodeType == ASTNode.VARIABLE_DECLARATION_FRAGMENT) { VariableDeclarationFragment fragment= (VariableDeclarationFragment) selectedNode.getParent(); ASTNode parent= fragment.getParent(); Type typeNode= null; if (parent instanceof VariableDeclarationStatement) { VariableDeclarationStatement stmt= (VariableDeclarationStatement) parent; if (stmt.fragments().size() == 1) { typeNode= stmt.getType(); } } else if (parent instanceof FieldDeclaration) { FieldDeclaration decl= (FieldDeclaration) parent; if (decl.fragments().size() == 1) { typeNode= decl.getType(); } } if (typeNode != null) { currBinding= Bindings.normalizeTypeBinding(currBinding); if (currBinding == null) { currBinding= astRoot.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } TextBuffer buffer= null; try { buffer= TextBuffer.acquire((IFile)WorkingCopyUtil.getOriginal(cu).getResource()); ImportRewrite importRewrite= new ImportRewrite(cu, JavaPreferencesSettings.getCodeGenerationSettings()); String typeName= importRewrite.addImport(currBinding); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changevartype.description", typeName); //$NON-NLS-1$ ReplaceCorrectionProposal varProposal= new ReplaceCorrectionProposal(label, cu, typeNode.getStartPosition(), typeNode.getLength(), typeName, 5); varProposal.getRootTextEdit().addChild(importRewrite.createEdit(buffer)); proposals.add(varProposal); } finally { if (buffer != null) TextBuffer.release(buffer); } } } } private static boolean canCast(String castTarget, ITypeBinding bindingToCast) { bindingToCast= Bindings.normalizeTypeBinding(bindingToCast); if (bindingToCast == null) { return false; } int arrStart= castTarget.indexOf('['); if (arrStart != -1) { if (!bindingToCast.isArray()) { return "java.lang.Object".equals(bindingToCast.getQualifiedName()); //$NON-NLS-1$ } castTarget= castTarget.substring(0, arrStart); bindingToCast= bindingToCast.getElementType(); if (bindingToCast.isPrimitive() && !castTarget.equals(bindingToCast.getName())) { return false; // can't cast arrays of primitive types into each other } } Code targetCode= PrimitiveType.toCode(castTarget); if (bindingToCast.isPrimitive()) { Code castCode= PrimitiveType.toCode(bindingToCast.getName()); if (castCode == targetCode) { return true; } return (targetCode != null && targetCode != PrimitiveType.BOOLEAN && castCode != PrimitiveType.BOOLEAN); } else { return targetCode == null; // can not check } } public static ASTRewriteCorrectionProposal createCastProposal(IInvocationContext context, String castType, Expression nodeToCast, int relevance) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTRewrite rewrite= new ASTRewrite(nodeToCast.getParent()); String label; Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, relevance, image); //$NON-NLS-1$ String simpleCastType= proposal.addImport(castType); if (nodeToCast.getNodeType() == ASTNode.CAST_EXPRESSION) { label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changecast.description", castType); //$NON-NLS-1$ CastExpression expression= (CastExpression) nodeToCast; rewrite.markAsReplaced(expression.getType(), rewrite.createPlaceholder(simpleCastType, NewASTRewrite.TYPE)); } else { label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.addcast.description", castType); //$NON-NLS-1$ Expression expressionCopy= (Expression) rewrite.createCopy(nodeToCast); int nodeType= nodeToCast.getNodeType(); if (nodeType == ASTNode.INFIX_EXPRESSION || nodeType == ASTNode.CONDITIONAL_EXPRESSION || nodeType == ASTNode.ASSIGNMENT || nodeType == ASTNode.INSTANCEOF_EXPRESSION) { // nodes have weaker precedence than cast ParenthesizedExpression parenthesizedExpression= astRoot.getAST().newParenthesizedExpression(); parenthesizedExpression.setExpression(expressionCopy); expressionCopy= parenthesizedExpression; } Type typeCopy= (Type) rewrite.createPlaceholder(simpleCastType, NewASTRewrite.TYPE); CastExpression castExpression= astRoot.getAST().newCastExpression(); castExpression.setExpression(expressionCopy); castExpression.setType(typeCopy); rewrite.markAsReplaced(nodeToCast, castExpression); } proposal.setDisplayName(label); proposal.ensureNoModifications(); return proposal; } public static void addUncaughtExceptionProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } while (selectedNode != null && !(selectedNode instanceof Statement)) { selectedNode= selectedNode.getParent(); } if (selectedNode == null) { return; } CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); SurroundWithTryCatchRefactoring refactoring= SurroundWithTryCatchRefactoring.create(cu, selectedNode.getStartPosition(), selectedNode.getLength(), settings, null); if (refactoring == null) return; refactoring.setSaveChanges(false); if (refactoring.checkActivationBasics(astRoot, null).isOK()) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.surroundwith.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); CUCorrectionProposal proposal= new CUCorrectionProposal(label, (CompilationUnitChange) refactoring.createChange(null), 4, image); proposals.add(proposal); } BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl == null) { return; } ITypeBinding[] uncaughtExceptions= ExceptionAnalyzer.perform(decl, Selection.createFromStartLength(selectedNode.getStartPosition(), selectedNode.getLength())); if (uncaughtExceptions.length == 0) { return; } TryStatement surroundingTry= ASTResolving.findParentTryStatement(selectedNode); if (surroundingTry != null && ASTNodes.isParent(selectedNode, surroundingTry.getBody())) { ASTRewrite rewrite= new ASTRewrite(surroundingTry); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addadditionalcatch.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 5, image); AST ast= astRoot.getAST(); List catchClauses= surroundingTry.catchClauses(); for (int i= 0; i < uncaughtExceptions.length; i++) { ITypeBinding excBinding= uncaughtExceptions[i]; String varName= PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.CODEGEN_EXCEPTION_VAR_NAME); String imp= proposal.addImport(excBinding); Name name= ASTNodeFactory.newName(ast, imp); SingleVariableDeclaration var= ast.newSingleVariableDeclaration(); var.setName(ast.newSimpleName(varName)); var.setType(ast.newSimpleType(name)); CatchClause newClause= ast.newCatchClause(); newClause.setException(var); String catchBody = StubUtility.getCatchBodyContent(cu, excBinding.getName(), varName, String.valueOf('\n')); if (catchBody != null) { ASTNode node= rewrite.createPlaceholder(catchBody, NewASTRewrite.STATEMENT); newClause.getBody().statements().add(node); } rewrite.markAsInserted(newClause); catchClauses.add(newClause); String typeKey= "type" + i; //$NON-NLS-1$ String nameKey= "name" + i; //$NON-NLS-1$ proposal.markAsLinked(rewrite, var.getType(), false, typeKey); //$NON-NLS-1$ proposal.markAsLinked(rewrite, var.getName(), false, nameKey); //$NON-NLS-1$ addExceptionTypeLinkProposals(proposal, excBinding, typeKey); } proposal.ensureNoModifications(); proposals.add(proposal); } if (decl instanceof MethodDeclaration) { ASTRewrite rewrite= new ASTRewrite(astRoot); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addthrows.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); AST ast= astRoot.getAST(); MethodDeclaration methodDecl= (MethodDeclaration) decl; List exceptions= methodDecl.thrownExceptions(); for (int i= 0; i < uncaughtExceptions.length; i++) { String imp= proposal.addImport(uncaughtExceptions[i]); Name name= ASTNodeFactory.newName(ast, imp); rewrite.markAsInserted(name); exceptions.add(name); String typeKey= "type" + i; //$NON-NLS-1$ proposal.markAsLinked(rewrite, name, false, typeKey); //$NON-NLS-1$ addExceptionTypeLinkProposals(proposal, uncaughtExceptions[i], typeKey); } for (int i= 0; i < exceptions.size(); i++) { Name elem= (Name) exceptions.get(i); if (canRemoveException(elem.resolveTypeBinding(), uncaughtExceptions)) { rewrite.markAsRemoved(elem); } } proposal.ensureNoModifications(); proposals.add(proposal); } } private static void addExceptionTypeLinkProposals(LinkedCorrectionProposal proposal, ITypeBinding exc, String key) { // all superclasses except Object while (exc != null && !"java.lang.Object".equals(exc.getQualifiedName())) { //$NON-NLS-1$ proposal.addLinkedModeProposal(key, exc); exc= exc.getSuperclass(); } } private static boolean canRemoveException(ITypeBinding curr, ITypeBinding[] addedExceptions) { while (curr != null) { for (int i= 0; i < addedExceptions.length; i++) { if (curr == addedExceptions[i]) { return true; } } curr= curr.getSuperclass(); } return false; } public static void addUnreachableCatchProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } QuickAssistProcessor.getCatchClauseToThrowsProposals(context, selectedNode, proposals); } public static void addNLSProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { final ICompilationUnit cu= context.getCompilationUnit(); if (! NLSRefactoring.isAvailable(cu)){ return; } String name= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.description"); //$NON-NLS-1$ ChangeCorrectionProposal proposal= new ChangeCorrectionProposal(name, null, 5) { public void apply(IDocument document) { try { NLSRefactoring refactoring= NLSRefactoring.create(cu, JavaPreferencesSettings.getCodeGenerationSettings()); if (refactoring == null) return; ExternalizeWizard wizard= new ExternalizeWizard(refactoring); String dialogTitle= CorrectionMessages.getString("LocalCorrectionsSubProcessor.externalizestrings.dialog.title"); //$NON-NLS-1$ new RefactoringStarter().activate(refactoring, wizard, JavaPlugin.getActiveWorkbenchShell(), dialogTitle, true); } catch (JavaModelException e) { JavaPlugin.log(e); } } }; proposals.add(proposal); TextEdit edit= NLSUtil.createNLSEdit(cu, problem.getOffset()); if (edit != null) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.addnon-nls.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_NLS_NEVER_TRANSLATE); CUCorrectionProposal nlsProposal= new CUCorrectionProposal(label, cu, 6, image); nlsProposal.getRootTextEdit().addChild(edit); proposals.add(nlsProposal); } } /** * Fix instance accesses and indirect (static) accesses to static fields/methods */ public static void addCorrectAccessToStaticProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); CompilationUnit astRoot= context.getASTRoot(); ASTNode selectedNode= problem.getCoveringNode(astRoot); if (selectedNode == null) { return; } Expression qualifier= null; IBinding accessBinding= null; if (selectedNode instanceof QualifiedName) { QualifiedName name= (QualifiedName) selectedNode; qualifier= name.getQualifier(); accessBinding= name.resolveBinding(); } else if (selectedNode instanceof SimpleName) { ASTNode parent= selectedNode.getParent(); if (parent instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) parent; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); } } else if (selectedNode instanceof MethodInvocation) { MethodInvocation methodInvocation= (MethodInvocation) selectedNode; qualifier= methodInvocation.getExpression(); accessBinding= methodInvocation.getName().resolveBinding(); } else if (selectedNode instanceof FieldAccess) { FieldAccess fieldAccess= (FieldAccess) selectedNode; qualifier= fieldAccess.getExpression(); accessBinding= fieldAccess.getName().resolveBinding(); } if (problem.getProblemId() == IProblem.IndirectAccessToStaticField || problem.getProblemId() == IProblem.IndirectAccessToStaticMethod) { // indirectAccessToStaticProposal if (accessBinding != null) { ITypeBinding declaringTypeBinding= getDeclaringTypeBinding(accessBinding); if (declaringTypeBinding != null) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.indirectaccesstostatic.description", declaringTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); String typeName= proposal.addImport(declaringTypeBinding); rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName)); proposal.ensureNoModifications(); proposals.add(proposal); } } return; } ITypeBinding declaringTypeBinding= null; if (accessBinding != null) { declaringTypeBinding= getDeclaringTypeBinding(accessBinding); if (declaringTypeBinding != null) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostaticdefining.description", declaringTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 6, image); String typeName= proposal.addImport(declaringTypeBinding); rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName)); proposal.ensureNoModifications(); proposals.add(proposal); } } if (qualifier != null) { ITypeBinding instanceTypeBinding= Bindings.normalizeTypeBinding(qualifier.resolveTypeBinding()); if (instanceTypeBinding != null && instanceTypeBinding != declaringTypeBinding) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.changeaccesstostatic.description", instanceTypeBinding.getName()); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, 5, image); String typeName= proposal.addImport(instanceTypeBinding); rewrite.markAsReplaced(qualifier, ASTNodeFactory.newName(astRoot.getAST(), typeName)); proposal.ensureNoModifications(); proposals.add(proposal); } } ModifierCorrectionSubProcessor.addNonAccessibleMemberProposal(context, problem, proposals, ModifierCorrectionSubProcessor.TO_NON_STATIC, 4); } private static ITypeBinding getDeclaringTypeBinding(IBinding accessBinding) { if (accessBinding instanceof IMethodBinding) { return ((IMethodBinding) accessBinding).getDeclaringClass(); } else if (accessBinding instanceof IVariableBinding) { return ((IVariableBinding) accessBinding).getDeclaringClass(); } return null; } public static void addUnimplementedMethodsProposals(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } ASTNode typeNode= null; if (selectedNode.getNodeType() == ASTNode.SIMPLE_NAME && selectedNode.getParent().getNodeType() == ASTNode.TYPE_DECLARATION) { typeNode= selectedNode.getParent(); } else if (selectedNode.getNodeType() == ASTNode.CLASS_INSTANCE_CREATION) { ClassInstanceCreation creation= (ClassInstanceCreation) selectedNode; typeNode= creation.getAnonymousClassDeclaration(); } if (typeNode != null) { UnimplementedMethodsCompletionProposal proposal= new UnimplementedMethodsCompletionProposal(cu, typeNode, 10); proposals.add(proposal); } if (typeNode instanceof TypeDeclaration) { TypeDeclaration typeDeclaration= (TypeDeclaration) typeNode; ASTRewriteCorrectionProposal proposal= ModifierCorrectionSubProcessor.getMakeTypeStaticProposal(cu, typeDeclaration, 5); proposals.add(proposal); } } public static void addUninitializedLocalVariableProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ICompilationUnit cu= context.getCompilationUnit(); ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof Name)) { return; } Name name= (Name) selectedNode; IBinding binding= name.resolveBinding(); if (!(binding instanceof IVariableBinding)) { return; } IVariableBinding varBinding= (IVariableBinding) binding; CompilationUnit astRoot= context.getASTRoot(); ASTNode node= astRoot.findDeclaringNode(binding); if (node instanceof VariableDeclarationFragment) { ASTRewrite rewrite= new ASTRewrite(node.getParent()); VariableDeclarationFragment fragment= (VariableDeclarationFragment) node; if (fragment.getInitializer() != null) { return; } Expression expression= ASTNodeFactory.newDefaultExpression(astRoot.getAST(), varBinding.getType()); if (expression == null) { return; } rewrite.markAsInsert(fragment, ASTNodeConstants.INITIALIZER, expression, null); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.uninitializedvariable.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); LinkedCorrectionProposal proposal= new LinkedCorrectionProposal(label, cu, rewrite, 6, image); proposal.markAsLinked(rewrite, expression, false, "initializer"); //$NON-NLS-1$ proposal.ensureNoModifications(); proposals.add(proposal); } } public static void addConstructorFromSuperclassProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (!(selectedNode instanceof Name && selectedNode.getParent() instanceof TypeDeclaration)) { return; } TypeDeclaration typeDeclaration= (TypeDeclaration) selectedNode.getParent(); ITypeBinding binding= typeDeclaration.resolveBinding(); if (binding == null || binding.getSuperclass() == null) { return; } ICompilationUnit cu= context.getCompilationUnit(); IMethodBinding[] methods= binding.getSuperclass().getDeclaredMethods(); for (int i= 0; i < methods.length; i++) { IMethodBinding curr= methods[i]; if (curr.isConstructor() && !Modifier.isPrivate(curr.getModifiers())) { proposals.add(new ConstructorFromSuperclassProposal(cu, typeDeclaration, curr, 5)); } } } public static void addUnusedMemberProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); SimpleName name= null; if (selectedNode instanceof MethodDeclaration) { name= ((MethodDeclaration) selectedNode).getName(); } else if (selectedNode instanceof SimpleName) { name= (SimpleName) selectedNode; } if (name != null) { IBinding binding= name.resolveBinding(); if (binding != null) { proposals.add(new RemoveDeclarationCorrectionProposal(context.getCompilationUnit(), name, 5)); } } } public static void addSuperfluousSemicolonProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.removesemicolon.description"); //$NON-NLS-1$ ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, context.getCompilationUnit(), problem.getOffset(), problem.getLength(), "", 6); //$NON-NLS-1$ proposals.add(proposal); } public static void addUnnecessaryCastProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); ASTNode curr= selectedNode; while (curr instanceof ParenthesizedExpression) { curr= ((ParenthesizedExpression) curr).getExpression(); } if (curr instanceof CastExpression) { ASTRewrite rewrite= new ASTRewrite(selectedNode.getParent()); CastExpression cast= (CastExpression) curr; Expression expression= cast.getExpression(); ASTNode placeholder= rewrite.createCopy(expression); if (ASTNodes.needsParentheses(expression)) { rewrite.markAsReplaced(curr, placeholder); } else { rewrite.markAsReplaced(selectedNode, placeholder); } String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarycast.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); } } public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); ASTNode curr= selectedNode; while (curr instanceof ParenthesizedExpression) { curr= ((ParenthesizedExpression) curr).getExpression(); } if (curr instanceof InstanceofExpression) { ASTRewrite rewrite= new ASTRewrite(curr.getParent()); InstanceofExpression inst= (InstanceofExpression) curr; AST ast= inst.getAST(); InfixExpression expression= ast.newInfixExpression(); expression.setLeftOperand((Expression) rewrite.createCopy(inst.getLeftOperand())); expression.setOperator(InfixExpression.Operator.NOT_EQUALS); expression.setRightOperand(ast.newNullLiteral()); if (false/*ASTNodes.needsParentheses(expression)*/) { ParenthesizedExpression parents= ast.newParenthesizedExpression(); parents.setExpression(expression); rewrite.markAsReplaced(inst, parents); } else { rewrite.markAsReplaced(inst, expression); } String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessaryinstanceof.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); } } public static void addUnnecessaryThrownExceptionProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); if (selectedNode == null) { return; } if (selectedNode.getParent() instanceof MethodDeclaration) { MethodDeclaration decl= (MethodDeclaration) selectedNode.getParent(); List thrownExceptions= decl.thrownExceptions(); if (!thrownExceptions.contains(selectedNode)) { return; } ASTRewrite rewrite= new ASTRewrite(decl); rewrite.markAsRemoved(selectedNode); String label= CorrectionMessages.getString("LocalCorrectionsSubProcessor.unnecessarythrow.description"); //$NON-NLS-1$ Image image= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_EXCEPTION); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, 5, image); proposals.add(proposal); } } public static void addUnqualifiedFieldAccessProposal(IInvocationContext context, IProblemLocation problem, Collection proposals) throws CoreException { ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot()); while (selectedNode instanceof QualifiedName) { selectedNode= ((QualifiedName) selectedNode).getQualifier(); } if (!(selectedNode instanceof SimpleName)) { return; } SimpleName name = (SimpleName) selectedNode; IBinding binding= name.resolveBinding(); if (binding.getKind() != IBinding.VARIABLE) { return; } ASTRewrite rewrite= new ASTRewrite(name.getParent()); Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", context.getCompilationUnit(), rewrite, 5, image); //$NON-NLS-1$ ITypeBinding declaringClass= ((IVariableBinding) binding).getDeclaringClass(); String qualifier; if (Modifier.isStatic(binding.getModifiers())) { qualifier= proposal.addImport(declaringClass); } else { ITypeBinding currType= Bindings.getBindingOfParentType(name); if (Bindings.isSuperType(currType, declaringClass)) { qualifier= "this"; //$NON-NLS-1$ } else { String outer= proposal.addImport(declaringClass); qualifier= outer + ".this"; //$NON-NLS-1$ } } String replacement= qualifier + '.' + name.getIdentifier(); rewrite.markAsReplaced(name, rewrite.createPlaceholder(replacement, NewASTRewrite.NAME)); String label= CorrectionMessages.getFormattedString("LocalCorrectionsSubProcessor.unqualifiedfieldaccess.description", qualifier); //$NON-NLS-1$ proposal.setDisplayName(label); proposals.add(proposal); } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/javaeditor/CompilationUnitEditor.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.javaeditor; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Stack; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Preferences; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.VerifyKeyListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IMessageProvider; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.window.Window; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IAutoEditStrategy; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.ILineTracker; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextOperationTarget; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.text.ITextViewerExtension; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.IWidgetTokenKeeper; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.contentassist.ContentAssistant; import org.eclipse.jface.text.contentassist.IContentAssistant; import org.eclipse.jface.text.source.IOverviewRuler; import org.eclipse.jface.text.source.ISourceViewer; import org.eclipse.jface.text.source.IVerticalRuler; import org.eclipse.jface.text.source.SourceViewerConfiguration; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.dialogs.SaveAsDialog; import org.eclipse.ui.editors.text.IStorageDocumentProvider; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.FileEditorInput; import org.eclipse.ui.texteditor.ContentAssistAction; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.IDocumentProvider; import org.eclipse.ui.texteditor.ITextEditorActionConstants; import org.eclipse.ui.texteditor.TextOperationAction; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddBlockCommentAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.IndentAction; import org.eclipse.jdt.internal.ui.actions.RemoveBlockCommentAction; import org.eclipse.jdt.internal.ui.compare.LocalHistoryActionGroup; import org.eclipse.jdt.internal.ui.text.ContentAssistPreference; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.correction.JavaCorrectionAssistant; import org.eclipse.jdt.internal.ui.text.java.IReconcilingParticipant; import org.eclipse.jdt.internal.ui.text.java.SmartSemicolonAutoEditStrategy; import org.eclipse.jdt.internal.ui.text.link.ExclusivePositionUpdater; import org.eclipse.jdt.internal.ui.text.link.ILinkedListener; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.ExitFlags; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.IExitPolicy; /** * Java specific text editor. */ public class CompilationUnitEditor extends JavaEditor implements IReconcilingParticipant { /** * Text operation code for requesting correction assist to show correction * proposals for the current position. */ public static final int CORRECTIONASSIST_PROPOSALS= 50; interface ITextConverter { void customizeDocumentCommand(IDocument document, DocumentCommand command); } class AdaptedSourceViewer extends JavaSourceViewer { private List fTextConverters; private boolean fIgnoreTextConverters= false; private JavaCorrectionAssistant fCorrectionAssistant; public AdaptedSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean showAnnotationsOverview, int styles) { super(parent, verticalRuler, overviewRuler, showAnnotationsOverview, styles); } public IContentAssistant getContentAssistant() { return fContentAssistant; } /* * @see ITextOperationTarget#doOperation(int) */ public void doOperation(int operation) { if (getTextWidget() == null) return; switch (operation) { case CONTENTASSIST_PROPOSALS: String msg= fContentAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case CORRECTIONASSIST_PROPOSALS: msg= fCorrectionAssistant.showPossibleCompletions(); setStatusLineErrorMessage(msg); return; case UNDO: fIgnoreTextConverters= true; break; case REDO: fIgnoreTextConverters= true; break; } super.doOperation(operation); } /* * @see ITextOperationTarget#canDoOperation(int) */ public boolean canDoOperation(int operation) { if (operation == CORRECTIONASSIST_PROPOSALS) return isEditable(); return super.canDoOperation(operation); } /* * @see TextViewer#handleDispose() */ protected void handleDispose() { if (fCorrectionAssistant != null) { fCorrectionAssistant.uninstall(); fCorrectionAssistant= null; } super.handleDispose(); } public void insertTextConverter(ITextConverter textConverter, int index) { throw new UnsupportedOperationException(); } public void addTextConverter(ITextConverter textConverter) { if (fTextConverters == null) { fTextConverters= new ArrayList(1); fTextConverters.add(textConverter); } else if (!fTextConverters.contains(textConverter)) fTextConverters.add(textConverter); } public void removeTextConverter(ITextConverter textConverter) { if (fTextConverters != null) { fTextConverters.remove(textConverter); if (fTextConverters.size() == 0) fTextConverters= null; } } /* * @see TextViewer#customizeDocumentCommand(DocumentCommand) */ protected void customizeDocumentCommand(DocumentCommand command) { super.customizeDocumentCommand(command); if (!fIgnoreTextConverters && fTextConverters != null) { for (Iterator e = fTextConverters.iterator(); e.hasNext();) ((ITextConverter) e.next()).customizeDocumentCommand(getDocument(), command); } fIgnoreTextConverters= false; } // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 public void updateIndentationPrefixes() { SourceViewerConfiguration configuration= getSourceViewerConfiguration(); String[] types= configuration.getConfiguredContentTypes(this); for (int i= 0; i < types.length; i++) { String[] prefixes= configuration.getIndentPrefixes(this, types[i]); if (prefixes != null && prefixes.length > 0) setIndentPrefixes(prefixes, types[i]); } } /* * @see IWidgetTokenOwner#requestWidgetToken(IWidgetTokenKeeper) */ public boolean requestWidgetToken(IWidgetTokenKeeper requester) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester); } /* * @see IWidgetTokenOwnerExtension#requestWidgetToken(IWidgetTokenKeeper, int) * @since 3.0 */ public boolean requestWidgetToken(IWidgetTokenKeeper requester, int priority) { if (WorkbenchHelp.isContextHelpDisplayed()) return false; return super.requestWidgetToken(requester, priority); } /* * @see org.eclipse.jface.text.source.ISourceViewer#configure(org.eclipse.jface.text.source.SourceViewerConfiguration) */ public void configure(SourceViewerConfiguration configuration) { super.configure(configuration); fCorrectionAssistant= new JavaCorrectionAssistant(CompilationUnitEditor.this); fCorrectionAssistant.install(this); IAutoEditStrategy smartSemi= new SmartSemicolonAutoEditStrategy(IJavaPartitions.JAVA_PARTITIONING); prependAutoEditStrategy(smartSemi, IDocument.DEFAULT_CONTENT_TYPE); } } static class TabConverter implements ITextConverter { private int fTabRatio; private ILineTracker fLineTracker; public TabConverter() { } public void setNumberOfSpacesPerTab(int ratio) { fTabRatio= ratio; } public void setLineTracker(ILineTracker lineTracker) { fLineTracker= lineTracker; } private int insertTabString(StringBuffer buffer, int offsetInLine) { if (fTabRatio == 0) return 0; int remainder= offsetInLine % fTabRatio; remainder= fTabRatio - remainder; for (int i= 0; i < remainder; i++) buffer.append(' '); return remainder; } public void customizeDocumentCommand(IDocument document, DocumentCommand command) { String text= command.text; if (text == null) return; int index= text.indexOf('\t'); if (index > -1) { StringBuffer buffer= new StringBuffer(); fLineTracker.set(command.text); int lines= fLineTracker.getNumberOfLines(); try { for (int i= 0; i < lines; i++) { int offset= fLineTracker.getLineOffset(i); int endOffset= offset + fLineTracker.getLineLength(i); String line= text.substring(offset, endOffset); int position= 0; if (i == 0) { IRegion firstLine= document.getLineInformationOfOffset(command.offset); position= command.offset - firstLine.getOffset(); } int length= line.length(); for (int j= 0; j < length; j++) { char c= line.charAt(j); if (c == '\t') { position += insertTabString(buffer, position); } else { buffer.append(c); ++ position; } } } command.text= buffer.toString(); } catch (BadLocationException x) { } } } } private class ExitPolicy implements IExitPolicy { final char fExitCharacter; final char fEscapeCharacter; final Stack fStack; final int fSize; public ExitPolicy(char exitCharacter, char escapeCharacter, Stack stack) { fExitCharacter= exitCharacter; fEscapeCharacter= escapeCharacter; fStack= stack; fSize= fStack.size(); } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { if (fSize == fStack.size() && !isMasked(offset)) { BracketLevel level= (BracketLevel) fStack.peek(); if (level.fSecondPosition.offset == offset && length == 0) // don't enter the character if if its the closing peer return new ExitFlags(ILinkedListener.UPDATE_CARET, false); else return new ExitFlags(ILinkedListener.UPDATE_CARET, true); } } return null; } private boolean isMasked(int offset) { IDocument document= getSourceViewer().getDocument(); try { return fEscapeCharacter == document.getChar(offset - 1); } catch (BadLocationException e) { } return false; } } private static class BracketLevel { int fOffset; int fLength; LinkedUIControl fEditor; Position fFirstPosition; Position fSecondPosition; } private class BracketInserter implements VerifyKeyListener, ILinkedListener { private boolean fCloseBrackets= true; private boolean fCloseStrings= true; private final String CATEGORY= toString(); private IPositionUpdater fUpdater= new ExclusivePositionUpdater(CATEGORY); private Stack fBracketLevelStack= new Stack(); public void setCloseBracketsEnabled(boolean enabled) { fCloseBrackets= enabled; } public void setCloseStringsEnabled(boolean enabled) { fCloseStrings= enabled; } private boolean hasIdentifierToTheRight(IDocument document, int offset) { try { int end= offset; IRegion endLine= document.getLineInformationOfOffset(end); int maxEnd= endLine.getOffset() + endLine.getLength(); while (end != maxEnd && Character.isWhitespace(document.getChar(end))) ++end; return end != maxEnd && Character.isJavaIdentifierPart(document.getChar(end)); } catch (BadLocationException e) { // be conservative return true; } } private boolean hasIdentifierToTheLeft(IDocument document, int offset) { try { int start= offset; IRegion startLine= document.getLineInformationOfOffset(start); int minStart= startLine.getOffset(); while (start != minStart && Character.isWhitespace(document.getChar(start - 1))) --start; return start != minStart && Character.isJavaIdentifierPart(document.getChar(start - 1)); } catch (BadLocationException e) { return true; } } private boolean hasCharacterToTheRight(IDocument document, int offset, char character) { try { int end= offset; IRegion endLine= document.getLineInformationOfOffset(end); int maxEnd= endLine.getOffset() + endLine.getLength(); while (end != maxEnd && Character.isWhitespace(document.getChar(end))) ++end; return end != maxEnd && document.getChar(end) == character; } catch (BadLocationException e) { // be conservative return true; } } /* * @see org.eclipse.swt.custom.VerifyKeyListener#verifyKey(org.eclipse.swt.events.VerifyEvent) */ public void verifyKey(VerifyEvent event) { if (!event.doit || getInsertMode() != SMART_INSERT) return; final ISourceViewer sourceViewer= getSourceViewer(); IDocument document= sourceViewer.getDocument(); final Point selection= sourceViewer.getSelectedRange(); final int offset= selection.x; final int length= selection.y; switch (event.character) { case '(': if (hasCharacterToTheRight(document, offset + length, '(')) return; // fall through case '[': if (!fCloseBrackets) return; if (hasIdentifierToTheRight(document, offset + length)) return; // fall through case '\'': if (event.character == '\'') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } // fall through case '"': if (event.character == '"') { if (!fCloseStrings) return; if (hasIdentifierToTheLeft(document, offset) || hasIdentifierToTheRight(document, offset + length)) return; } try { ITypedRegion partition= TextUtilities.getPartition(document, IJavaPartitions.JAVA_PARTITIONING, offset); if (! IDocument.DEFAULT_CONTENT_TYPE.equals(partition.getType()) && partition.getOffset() != offset) return; if (!validateEditorInputState()) return; final char character= event.character; final char closingCharacter= getPeerCharacter(character); final StringBuffer buffer= new StringBuffer(); buffer.append(character); buffer.append(closingCharacter); document.replace(offset, length, buffer.toString()); BracketLevel level= new BracketLevel(); fBracketLevelStack.push(level); LinkedPositionGroup group= new LinkedPositionGroup(); group.createPosition(document, offset + 1, 0); LinkedEnvironment env= LinkedEnvironment.createLinkedEnvironment(document); env.addLinkedListener(this); env.addGroup(group); level.fOffset= offset; level.fLength= 2; // set up position tracking for our magic peers if (fBracketLevelStack.size() == 1) { document.addPositionCategory(CATEGORY); document.addPositionUpdater(fUpdater); } level.fFirstPosition= new Position(offset, 1); level.fSecondPosition= new Position(offset + 1, 1); document.addPosition(CATEGORY, level.fFirstPosition); document.addPosition(CATEGORY, level.fSecondPosition); level.fEditor= new LinkedUIControl(env, sourceViewer); level.fEditor.setExitPolicy(new ExitPolicy(closingCharacter, getEscapeCharacter(closingCharacter), fBracketLevelStack)); level.fEditor.setExitPosition(sourceViewer, offset + 2, 0, true); level.fEditor.setCyclingMode(LinkedUIControl.CYCLE_NEVER); level.fEditor.enter(); IRegion newSelection= level.fEditor.getSelectedRegion(); sourceViewer.setSelectedRange(newSelection.getOffset(), newSelection.getLength()); event.doit= false; } catch (BadLocationException e) { JavaPlugin.log(e); } catch (BadPositionCategoryException e) { JavaPlugin.log(e); } break; } } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void left(LinkedEnvironment environment, int flags) { final BracketLevel level= (BracketLevel) fBracketLevelStack.pop(); if (flags != ILinkedListener.EXTERNAL_MODIFICATION) return; // remove brackets final ISourceViewer sourceViewer= getSourceViewer(); final IDocument document= sourceViewer.getDocument(); if (document instanceof IDocumentExtension) { IDocumentExtension extension= (IDocumentExtension) document; extension.registerPostNotificationReplace(null, new IDocumentExtension.IReplace() { public void perform(IDocument d, IDocumentListener owner) { if ((level.fFirstPosition.isDeleted || level.fFirstPosition.length == 0) && !level.fSecondPosition.isDeleted && level.fSecondPosition.offset == level.fFirstPosition.offset) { try { document.replace(level.fSecondPosition.offset, level.fSecondPosition.length, null); } catch (BadLocationException e) { } } if (fBracketLevelStack.size() == 0) { document.removePositionUpdater(fUpdater); try { document.removePositionCategory(CATEGORY); } catch (BadPositionCategoryException e) { } } } }); } } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void suspend(LinkedEnvironment environment) { } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void resume(LinkedEnvironment environment, int flags) { } } /** Preference key for code formatter tab size */ private final static String CODE_FORMATTER_TAB_SIZE= JavaCore.FORMATTER_TAB_SIZE; /** Preference key for inserting spaces rather than tabs */ private final static String SPACES_FOR_TABS= PreferenceConstants.EDITOR_SPACES_FOR_TABS; /** Preference key for automatically closing strings */ private final static String CLOSE_STRINGS= PreferenceConstants.EDITOR_CLOSE_STRINGS; /** Preference key for automatically closing brackets and parenthesis */ private final static String CLOSE_BRACKETS= PreferenceConstants.EDITOR_CLOSE_BRACKETS; /** The editor's save policy */ protected ISavePolicy fSavePolicy; /** Listener to annotation model changes that updates the error tick in the tab image */ private JavaEditorErrorTickUpdater fJavaEditorErrorTickUpdater; /** The editor's tab converter */ private TabConverter fTabConverter; /** The remembered java element */ private IJavaElement fRememberedElement; /** The remembered selection */ private ITextSelection fRememberedSelection; /** The remembered java element offset */ private int fRememberedElementOffset; /** The bracket inserter. */ private BracketInserter fBracketInserter= new BracketInserter(); /** The standard action groups added to the menu */ private GenerateActionGroup fGenerateActionGroup; private CompositeActionGroup fContextMenuGroup; /** * Creates a new compilation unit editor. */ public CompilationUnitEditor() { super(); setDocumentProvider(JavaPlugin.getDefault().getCompilationUnitDocumentProvider()); setEditorContextMenuId("#CompilationUnitEditorContext"); //$NON-NLS-1$ setRulerContextMenuId("#CompilationUnitRulerContext"); //$NON-NLS-1$ setOutlinerContextMenuId("#CompilationUnitOutlinerContext"); //$NON-NLS-1$ // don't set help contextId, we install our own help context fSavePolicy= null; fJavaEditorErrorTickUpdater= new JavaEditorErrorTickUpdater(this); } /* * @see AbstractTextEditor#createActions() */ protected void createActions() { super.createActions(); Action action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "CorrectionAssistProposal.", this, CORRECTIONASSIST_PROPOSALS); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CORRECTION_ASSIST_PROPOSALS); setAction("CorrectionAssistProposal", action); //$NON-NLS-1$ markAsStateDependentAction("CorrectionAssistProposal", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.QUICK_FIX_ACTION); action= new ContentAssistAction(JavaEditorMessages.getResourceBundle(), "ContentAssistProposal.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_PROPOSALS); setAction("ContentAssistProposal", action); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistProposal", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.CONTENT_ASSIST_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "ContentAssistContextInformation.", this, ISourceViewer.CONTENTASSIST_CONTEXT_INFORMATION); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.CONTENT_ASSIST_CONTEXT_INFORMATION); setAction("ContentAssistContextInformation", action); //$NON-NLS-1$ markAsStateDependentAction("ContentAssistContextInformation", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.PARAMETER_HINTS_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Comment.", this, ITextOperationTarget.PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.COMMENT); setAction("Comment", action); //$NON-NLS-1$ markAsStateDependentAction("Comment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.COMMENT_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Uncomment.", this, ITextOperationTarget.STRIP_PREFIX); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.UNCOMMENT); setAction("Uncomment", action); //$NON-NLS-1$ markAsStateDependentAction("Uncomment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.UNCOMMENT_ACTION); action= new TextOperationAction(JavaEditorMessages.getResourceBundle(), "Format.", this, ISourceViewer.FORMAT); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.FORMAT); setAction("Format", action); //$NON-NLS-1$ markAsStateDependentAction("Format", true); //$NON-NLS-1$ markAsSelectionDependentAction("Format", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.FORMAT_ACTION); action= new AddBlockCommentAction(JavaEditorMessages.getResourceBundle(), "AddBlockComment.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_BLOCK_COMMENT); setAction("AddBlockComment", action); //$NON-NLS-1$ markAsStateDependentAction("AddBlockComment", true); //$NON-NLS-1$ markAsSelectionDependentAction("AddBlockComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.ADD_BLOCK_COMMENT_ACTION); action= new RemoveBlockCommentAction(JavaEditorMessages.getResourceBundle(), "RemoveBlockComment.", this); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.REMOVE_BLOCK_COMMENT); setAction("RemoveBlockComment", action); //$NON-NLS-1$ markAsStateDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ markAsSelectionDependentAction("RemoveBlockComment", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.REMOVE_BLOCK_COMMENT_ACTION); action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, false); //$NON-NLS-1$ action.setActionDefinitionId(IJavaEditorActionDefinitionIds.INDENT); setAction("Indent", action); //$NON-NLS-1$ markAsStateDependentAction("Indent", true); //$NON-NLS-1$ markAsSelectionDependentAction("Indent", true); //$NON-NLS-1$ WorkbenchHelp.setHelp(action, IJavaHelpContextIds.INDENT_ACTION); action= new IndentAction(JavaEditorMessages.getResourceBundle(), "Indent.", this, true); //$NON-NLS-1$ setAction("IndentOnTab", action); //$NON-NLS-1$ markAsStateDependentAction("IndentOnTab", true); //$NON-NLS-1$ markAsSelectionDependentAction("IndentOnTab", true); //$NON-NLS-1$ if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { // don't replace Shift Right - have to make sure their enablement is mutually exclusive // removeActionActivationCode(ITextEditorActionConstants.SHIFT_RIGHT); setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ } fGenerateActionGroup= new GenerateActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); ActionGroup rg= new RefactorActionGroup(this, ITextEditorActionConstants.GROUP_EDIT); fActionGroups.addGroup(rg); fActionGroups.addGroup(fGenerateActionGroup); // We have to keep the context menu group separate to have better control over positioning fContextMenuGroup= new CompositeActionGroup(new ActionGroup[] { fGenerateActionGroup, rg, new LocalHistoryActionGroup(this, ITextEditorActionConstants.GROUP_EDIT)}); } /* * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementAt(int offset) { return getElementAt(offset, true); } /** * Returns the most narrow element including the given offset. If <code>reconcile</code> * is <code>true</code> the editor's input element is reconciled in advance. If it is * <code>false</code> this method only returns a result if the editor's input element * does not need to be reconciled. * * @param offset the offset included by the retrieved element * @param reconcile <code>true</code> if working copy should be reconciled */ protected IJavaElement getElementAt(int offset, boolean reconcile) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { if (reconcile) { synchronized (unit) { unit.reconcile(); } return unit.getElementAt(offset); } else if (unit.isConsistent()) return unit.getElementAt(offset); } catch (JavaModelException x) { if (!x.isDoesNotExist()) JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /* * @see JavaEditor#getCorrespondingElement(IJavaElement) */ protected IJavaElement getCorrespondingElement(IJavaElement element) { try { return EditorUtility.getWorkingCopy(element, true); } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } return null; } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#getInputElement() */ protected IJavaElement getInputJavaElement() { return JavaPlugin.getDefault().getWorkingCopyManager().getWorkingCopy(getEditorInput()); } /* * @see AbstractTextEditor#editorContextMenuAboutToShow(IMenuManager) */ public void editorContextMenuAboutToShow(IMenuManager menu) { super.editorContextMenuAboutToShow(menu); ActionContext context= new ActionContext(getSelectionProvider().getSelection()); fContextMenuGroup.setContext(context); fContextMenuGroup.fillContextMenu(menu); fContextMenuGroup.setContext(null); } /* * @see JavaEditor#setOutlinePageInput(JavaOutlinePage, IEditorInput) */ protected void setOutlinePageInput(JavaOutlinePage page, IEditorInput input) { if (page != null) { IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); page.setInput(manager.getWorkingCopy(input)); } } /* * @see org.eclipse.ui.texteditor.AbstractTextEditor#performSave(boolean, org.eclipse.core.runtime.IProgressMonitor) */ protected void performSave(boolean overwrite, IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p; cp.setSavePolicy(fSavePolicy); } try { super.performSave(overwrite, progressMonitor); } finally { if (p instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cp= (ICompilationUnitDocumentProvider) p; cp.setSavePolicy(null); } } } /* * @see AbstractTextEditor#doSaveAs */ public void doSaveAs() { if (askIfNonWorkbenchEncodingIsOk()) { super.doSaveAs(); } } /* * @see AbstractTextEditor#doSave(IProgressMonitor) */ public void doSave(IProgressMonitor progressMonitor) { IDocumentProvider p= getDocumentProvider(); if (p == null) { // editor has been closed return; } if (!askIfNonWorkbenchEncodingIsOk()) { progressMonitor.setCanceled(true); return; } if (p.isDeleted(getEditorInput())) { if (isSaveAsAllowed()) { /* * 1GEUSSR: ITPUI:ALL - User should never loose changes made in the editors. * Changed Behavior to make sure that if called inside a regular save (because * of deletion of input element) there is a way to report back to the caller. */ performSaveAs(progressMonitor); } else { /* * 1GF5YOX: ITPJUI:ALL - Save of delete file claims it's still there * Missing resources. */ Shell shell= getSite().getShell(); MessageDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title1"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message1")); //$NON-NLS-1$ //$NON-NLS-2$ } } else { setStatusLineErrorMessage(null); IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { synchronized (unit) { performSave(false, progressMonitor); } } else performSave(false, progressMonitor); } } /** * Asks the user if it is ok to store in non-workbench encoding. * @return <true> if the user wants to continue */ private boolean askIfNonWorkbenchEncodingIsOk() { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof IStorageDocumentProvider) { IEditorInput input= getEditorInput(); IStorageDocumentProvider storageProvider= (IStorageDocumentProvider)provider; String encoding= storageProvider.getEncoding(input); String defaultEncoding= storageProvider.getDefaultEncoding(); if (encoding != null && !encoding.equals(defaultEncoding)) { Shell shell= getSite().getShell(); String title= JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.title"); //$NON-NLS-1$ String msg; if (input != null) msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message1"), new String[] {input.getName(), encoding});//$NON-NLS-1$ else msg= MessageFormat.format(JavaEditorMessages.getString("CompilationUnitEditor.warning.save.nonWorkbenchEncoding.message2"), new String[] {encoding});//$NON-NLS-1$ return MessageDialog.openQuestion(shell, title, msg); } } return true; } public boolean isSaveAsAllowed() { return true; } /** * The compilation unit editor implementation of this <code>AbstractTextEditor</code> * method asks the user for the workspace path of a file resource and saves the document * there. See http://dev.eclipse.org/bugs/show_bug.cgi?id=6295 */ protected void performSaveAs(IProgressMonitor progressMonitor) { Shell shell= getSite().getShell(); IEditorInput input = getEditorInput(); SaveAsDialog dialog= new SaveAsDialog(shell); IFile original= (input instanceof IFileEditorInput) ? ((IFileEditorInput) input).getFile() : null; if (original != null) dialog.setOriginalFile(original); dialog.create(); IDocumentProvider provider= getDocumentProvider(); if (provider == null) { // editor has been programmatically closed while the dialog was open return; } if (provider.isDeleted(input) && original != null) { String message= JavaEditorMessages.getFormattedString("CompilationUnitEditor.warning.save.delete", new Object[] { original.getName() }); //$NON-NLS-1$ dialog.setErrorMessage(null); dialog.setMessage(message, IMessageProvider.WARNING); } if (dialog.open() == Window.CANCEL) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IPath filePath= dialog.getResult(); if (filePath == null) { if (progressMonitor != null) progressMonitor.setCanceled(true); return; } IWorkspaceRoot workspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); IFile file= workspaceRoot.getFile(filePath); final IEditorInput newInput= new FileEditorInput(file); boolean success= false; try { provider.aboutToChange(newInput); getDocumentProvider().saveDocument(progressMonitor, newInput, getDocumentProvider().getDocument(getEditorInput()), true); success= true; } catch (CoreException x) { ErrorDialog.openError(shell, JavaEditorMessages.getString("CompilationUnitEditor.error.saving.title2"), JavaEditorMessages.getString("CompilationUnitEditor.error.saving.message2"), x.getStatus()); //$NON-NLS-1$ //$NON-NLS-2$ } finally { provider.changed(newInput); if (success) setInput(newInput); } if (progressMonitor != null) progressMonitor.setCanceled(!success); } /* * @see AbstractTextEditor#doSetInput(IEditorInput) */ protected void doSetInput(IEditorInput input) throws CoreException { super.doSetInput(input); configureTabConverter(); } private void configureTabConverter() { if (fTabConverter != null) { IDocumentProvider provider= getDocumentProvider(); if (provider instanceof ICompilationUnitDocumentProvider) { ICompilationUnitDocumentProvider cup= (ICompilationUnitDocumentProvider) provider; fTabConverter.setLineTracker(cup.createLineTracker(getEditorInput())); } } } private int getTabSize() { Preferences preferences= JavaCore.getPlugin().getPluginPreferences(); return preferences.getInt(CODE_FORMATTER_TAB_SIZE); } private void startTabConversion() { if (fTabConverter == null) { fTabConverter= new TabConverter(); configureTabConverter(); fTabConverter.setNumberOfSpacesPerTab(getTabSize()); AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.addTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); } } private void stopTabConversion() { if (fTabConverter != null) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); asv.removeTextConverter(fTabConverter); // http://dev.eclipse.org/bugs/show_bug.cgi?id=19270 asv.updateIndentationPrefixes(); fTabConverter= null; } } private boolean isTabConversionEnabled() { IPreferenceStore store= getPreferenceStore(); return store.getBoolean(SPACES_FOR_TABS); } public void dispose() { ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).removeVerifyKeyListener(fBracketInserter); if (fJavaEditorErrorTickUpdater != null) { fJavaEditorErrorTickUpdater.dispose(); fJavaEditorErrorTickUpdater= null; } if (fActionGroups != null) { fActionGroups.dispose(); fActionGroups= null; } super.dispose(); } /* * @see AbstractTextEditor#createPartControl(Composite) */ public void createPartControl(Composite parent) { super.createPartControl(parent); if (isTabConversionEnabled()) startTabConversion(); IPreferenceStore preferenceStore= getPreferenceStore(); boolean closeBrackets= preferenceStore.getBoolean(CLOSE_BRACKETS); boolean closeStrings= preferenceStore.getBoolean(CLOSE_STRINGS); fBracketInserter.setCloseBracketsEnabled(closeBrackets); fBracketInserter.setCloseStringsEnabled(closeStrings); ISourceViewer sourceViewer= getSourceViewer(); if (sourceViewer instanceof ITextViewerExtension) ((ITextViewerExtension) sourceViewer).prependVerifyKeyListener(fBracketInserter); } private static char getEscapeCharacter(char character) { switch (character) { case '"': case '\'': return '\\'; default: return 0; } } private static char getPeerCharacter(char character) { switch (character) { case '(': return ')'; case ')': return '('; case '[': return ']'; case ']': return '['; case '"': return character; case '\'': return character; default: throw new IllegalArgumentException(); } } /* * @see AbstractTextEditor#handlePreferenceStoreChanged(PropertyChangeEvent) */ protected void handlePreferenceStoreChanged(PropertyChangeEvent event) { try { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CLOSE_BRACKETS.equals(p)) { fBracketInserter.setCloseBracketsEnabled(getPreferenceStore().getBoolean(p)); return; } if (CLOSE_STRINGS.equals(p)) { fBracketInserter.setCloseStringsEnabled(getPreferenceStore().getBoolean(p)); return; } if (SPACES_FOR_TABS.equals(p)) { if (isTabConversionEnabled()) startTabConversion(); else stopTabConversion(); return; } if (PreferenceConstants.EDITOR_SMART_TAB.equals(p)) { if (getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_TAB)) { setActionActivationCode("IndentOnTab", '\t', -1, SWT.NONE); //$NON-NLS-1$ } else { removeActionActivationCode("IndentOnTab"); //$NON-NLS-1$ } } IContentAssistant c= asv.getContentAssistant(); if (c instanceof ContentAssistant) ContentAssistPreference.changeConfiguration((ContentAssistant) c, getPreferenceStore(), event); } } finally { super.handlePreferenceStoreChanged(event); } } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent) */ protected void handlePreferencePropertyChanged(org.eclipse.core.runtime.Preferences.PropertyChangeEvent event) { AdaptedSourceViewer asv= (AdaptedSourceViewer) getSourceViewer(); if (asv != null) { String p= event.getProperty(); if (CODE_FORMATTER_TAB_SIZE.equals(p)) { asv.updateIndentationPrefixes(); if (fTabConverter != null) fTabConverter.setNumberOfSpacesPerTab(getTabSize()); } } super.handlePreferencePropertyChanged(event); } /* * @see org.eclipse.jdt.internal.ui.javaeditor.JavaEditor#createJavaSourceViewer(org.eclipse.swt.widgets.Composite, org.eclipse.jface.text.source.IVerticalRuler, org.eclipse.jface.text.source.IOverviewRuler, boolean, int) */ protected ISourceViewer createJavaSourceViewer(Composite parent, IVerticalRuler verticalRuler, IOverviewRuler overviewRuler, boolean isOverviewRulerVisible, int styles) { return new AdaptedSourceViewer(parent, verticalRuler, overviewRuler, isOverviewRulerVisible, styles); } /* * @see IReconcilingParticipant#reconciled() */ public void reconciled() { if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SYNC_OUTLINE_ON_CURSOR_MOVE)) { Shell shell= getSite().getShell(); if (shell != null && !shell.isDisposed()) { shell.getDisplay().asyncExec(new Runnable() { public void run() { synchronizeOutlinePageSelection(); } }); } } } protected void updateStateDependentActions() { super.updateStateDependentActions(); fGenerateActionGroup.editorStateChanged(); } /** * Returns the updated java element for the old java element. */ private IJavaElement findElement(IJavaElement element) { if (element == null) return null; IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(getEditorInput()); if (unit != null) { try { synchronized (unit) { unit.reconcile(); } IJavaElement[] findings= unit.findElements(element); if (findings != null && findings.length > 0) return findings[0]; } catch (JavaModelException x) { JavaPlugin.log(x.getStatus()); // nothing found, be tolerant and go on } } return null; } /** * Returns the offset of the given Java element. */ private int getOffset(IJavaElement element) { if (element instanceof ISourceReference) { ISourceReference sr= (ISourceReference) element; try { ISourceRange srcRange= sr.getSourceRange(); if (srcRange != null) return srcRange.getOffset(); } catch (JavaModelException e) { } } return -1; } /* * @see AbstractTextEditor#rememberSelection() */ protected void rememberSelection() { ISelectionProvider sp= getSelectionProvider(); fRememberedSelection= (sp == null ? null : (ITextSelection) sp.getSelection()); if (fRememberedSelection != null) { fRememberedElement= getElementAt(fRememberedSelection.getOffset(), true); fRememberedElementOffset= getOffset(fRememberedElement); } } /* * @see AbstractTextEditor#restoreSelection() */ protected void restoreSelection() { try { if (getSourceViewer() == null || fRememberedSelection == null) return; IJavaElement newElement= findElement(fRememberedElement); int newOffset= getOffset(newElement); int delta= (newOffset > -1 && fRememberedElementOffset > -1) ? newOffset - fRememberedElementOffset : 0; if (isValidSelection(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength())) selectAndReveal(delta + fRememberedSelection.getOffset(), fRememberedSelection.getLength()); } finally { fRememberedSelection= null; fRememberedElement= null; fRememberedElementOffset= -1; } } private boolean isValidSelection(int offset, int length) { IDocumentProvider provider= getDocumentProvider(); if (provider != null) { IDocument document= provider.getDocument(getEditorInput()); if (document != null) { int end= offset + length; int documentLength= document.getLength(); return 0 <= offset && offset <= documentLength && 0 <= end && end <= documentLength; } } return false; } /* * @see AbstractTextEditor#canHandleMove(IEditorInput, IEditorInput) */ protected boolean canHandleMove(IEditorInput originalElement, IEditorInput movedElement) { String oldExtension= ""; //$NON-NLS-1$ if (originalElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) originalElement).getFile(); if (file != null) { String ext= file.getFileExtension(); if (ext != null) oldExtension= ext; } } String newExtension= ""; //$NON-NLS-1$ if (movedElement instanceof IFileEditorInput) { IFile file= ((IFileEditorInput) movedElement).getFile(); if (file != null) newExtension= file.getFileExtension(); } return oldExtension.equals(newExtension); } /* * @see org.eclipse.ui.texteditor.ExtendedTextEditor#isPrefQuickDiffAlwaysOn() */ protected boolean isPrefQuickDiffAlwaysOn() { // reestablishes the behaviour from ExtendedTextEditor which was hacked by JavaEditor // to disable the change bar for the class file (attached source) java editor. IPreferenceStore store= getPreferenceStore(); return store.getBoolean(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CUCorrectionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.HashMap; import java.util.Iterator; import org.eclipse.compare.contentmergeviewer.ITokenComparator; import org.eclipse.compare.rangedifferencer.RangeDifference; import org.eclipse.compare.rangedifferencer.RangeDifferencer; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.internal.corext.refactoring.base.Change; import org.eclipse.jdt.internal.corext.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.GroupDescription; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.textmanipulation.TextRegion; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.corext.util.Resources; import org.eclipse.jdt.internal.corext.util.Strings; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.compare.JavaTokenComparator; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; public class CUCorrectionProposal extends ChangeCorrectionProposal { private ICompilationUnit fCompilationUnit; private TextEdit fRootEdit; public CUCorrectionProposal(String name, ICompilationUnit cu, int relevance) { this(name, cu, relevance, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE)); } public CUCorrectionProposal(String name, ICompilationUnit cu, int relevance, Image image) { super(name, null, relevance, image); fRootEdit= new MultiTextEdit(); fCompilationUnit= cu; } public CUCorrectionProposal(String name, CompilationUnitChange change, int relevance, Image image) { super(name, change, relevance, image); fCompilationUnit= change.getCompilationUnit(); } protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException { CompilationUnitChange change= new CompilationUnitChange(name, cu); change.setEdit(rootEdit); change.setSave(false); setChange(change); return change; } /* * @see ChangeCorrectionProposal#getChange() */ protected Change getChange() throws CoreException { Change change= super.getChange(); if (change == null) { return createCompilationUnitChange(getDisplayString(), fCompilationUnit, fRootEdit); } return change; } protected final void addEdits(CompilationUnitChange change) throws CoreException { } protected GroupDescription[] getLinkedRanges() { return null; } protected ICompletionProposal[] getLinkedModeProposals(String name) { return null; } protected GroupDescription getSelectionDescription() { return null; } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { StringBuffer buf= new StringBuffer(); try { CompilationUnitChange change= getCompilationUnitChange(); TextBuffer previewConent= change.getPreviewTextBuffer(); String currentConentString= change.getCurrentContent(); ITokenComparator leftSide= new JavaTokenComparator(previewConent.getContent(), true); ITokenComparator rightSide= new JavaTokenComparator(currentConentString, true); RangeDifference[] differences= RangeDifferencer.findRanges(leftSide, rightSide); for (int i= 0; i < differences.length; i++) { RangeDifference curr= differences[i]; int start= leftSide.getTokenStart(curr.leftStart()); int end= leftSide.getTokenStart(curr.leftEnd()); if (curr.kind() == RangeDifference.CHANGE && curr.leftLength() > 0) { buf.append("<b>"); //$NON-NLS-1$ appendContent(previewConent, start, end, buf, false); buf.append("</b>"); //$NON-NLS-1$ } else if (curr.kind() == RangeDifference.NOCHANGE) { appendContent(previewConent, start, end, buf, true); } } } catch (CoreException e) { JavaPlugin.log(e); } return buf.toString(); } private final int surroundLines= 1; private void appendContent(TextBuffer text, int startOffset, int endOffset, StringBuffer buf, boolean surroundLinesOnly) { int startLine= text.getLineOfOffset(startOffset); int endLine= text.getLineOfOffset(endOffset); boolean dotsAdded= false; if (surroundLinesOnly && startOffset == 0) { // no surround lines for the top no-change range startLine= Math.max(endLine - surroundLines, 0); buf.append("...<br>"); //$NON-NLS-1$ dotsAdded= true; } for (int i= startLine; i <= endLine; i++) { if (surroundLinesOnly) { if ((i - startLine > surroundLines) && (endLine - i > surroundLines)) { if (!dotsAdded) { buf.append("...<br>"); //$NON-NLS-1$ dotsAdded= true; } else if (endOffset == text.getLength()) { return; // no surround lines for the bottom no-change range } continue; } } TextRegion lineInfo= text.getLineInformation(i); int start= lineInfo.getOffset(); int end= start + lineInfo.getLength(); int from= Math.max(start, startOffset); int to= Math.min(end, endOffset); String content= text.getContent(from, to - from); if (surroundLinesOnly && (from == start) && Strings.containsOnlyWhitespaces(content)) { continue; // ignore empty lines exept when range started in the middle of a line } buf.append(content); if (to == end && to != endOffset) { // new line when at the end of the line, and not end of range buf.append("<br>"); //$NON-NLS-1$ } } } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposal#apply(org.eclipse.jface.text.IDocument) */ public void apply(IDocument document) { try { ICompilationUnit unit= JavaModelUtil.toOriginal(getCompilationUnit()); IStatus status= Resources.makeCommittable(unit.getResource(), null); if (!status.isOK()) { String label= CorrectionMessages.getString("CUCorrectionProposal.error.title"); //$NON-NLS-1$ String message= CorrectionMessages.getString("CUCorrectionProposal.error.message"); //$NON-NLS-1$ ErrorDialog.openError(JavaPlugin.getActiveWorkbenchShell(), label, message, status); return; } CompilationUnitChange change= getCompilationUnitChange(); GroupDescription selection= getSelectionDescription(); GroupDescription[] linked= getLinkedRanges(); IEditorPart part= null; if (selection != null || linked != null) { change.setKeepExecutedTextEdits(true); part= EditorUtility.isOpenInEditor(unit); if (part == null) { part= EditorUtility.openInEditor(unit, true); } IWorkbenchPage page= JavaPlugin.getActivePage(); if (page != null && part != null) { page.bringToTop(part); } if (part != null) { part.setFocus(); } } super.apply(document); if (part == null) { return; } if (linked != null && part instanceof JavaEditor) { // enter linked mode ITextViewer viewer= ((JavaEditor) part).getViewer(); enterLinkedMode(change, viewer, linked, selection); } else if (selection != null && part instanceof ITextEditor) { // select a result IRegion range= change.getNewTextRange(selection.getTextEdits()); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } catch (BadLocationException e) { JavaPlugin.log(e); } } private void enterLinkedMode(CompilationUnitChange change, ITextViewer viewer, GroupDescription[] linked, GroupDescription selection) throws BadLocationException { IDocument document= viewer.getDocument(); HashMap map= new HashMap(); for (int i= 0; i < linked.length; i++) { GroupDescription curr= linked[i]; String name= curr.getName(); // name used as key for link mode proposals & as kind for linked mode LinkedPositionGroup group= (LinkedPositionGroup) map.get(name); if (group == null) { group= new LinkedPositionGroup(); map.put(name, group); } TextEdit[] textEdits= curr.getTextEdits(); if (name != null && textEdits.length > 0) { IRegion range= change.getNewTextRange(textEdits); if (range != null) { // all edits could be deleted ICompletionProposal[] linkedModeProposals= getLinkedModeProposals(name); if (linkedModeProposals != null && linkedModeProposals.length > 1) { group.createPosition(document, range.getOffset(), range.getLength(), i, linkedModeProposals); } else { group.createPosition(document, range.getOffset(), range.getLength(), i); } } } } LinkedEnvironment environment= LinkedEnvironment.createLinkedEnvironment(document); boolean added= false; for (Iterator it= map.values().iterator(); it.hasNext(); ) { LinkedPositionGroup group= (LinkedPositionGroup) it.next(); if (!group.isEmtpy()) { environment.addGroup(group); added= true; } } if (added) { // only set up UI if there are any positions set LinkedUIControl ui= new LinkedUIControl(environment, viewer); if (selection != null) { TextEdit[] textEdits= selection.getTextEdits(); if (textEdits.length > 0) { IRegion range= change.getNewTextRange(textEdits); if (range != null) ui.setExitPosition(viewer, range.getOffset() + range.getLength(), 0, true); } } else { int cursorPosition= viewer.getSelectedRange().x; if (cursorPosition != 0) { ui.setExitPosition(viewer, cursorPosition, 0, true); } } ui.enter(); IRegion region= ui.getSelectedRegion(); viewer.setSelectedRange(region.getOffset(), region.getLength()); viewer.revealRange(region.getOffset(), region.getLength()); } } /** * Gets the compilationUnitChange. * @return Returns a CompilationUnitChange */ public CompilationUnitChange getCompilationUnitChange() throws CoreException { return (CompilationUnitChange) getChange(); } /** * @return Returns the root text edit */ public TextEdit getRootTextEdit() { return fRootEdit; } /** * Returns the compilationUnit. * @return ICompilationUnit */ public ICompilationUnit getCompilationUnit() { return fCompilationUnit; } /* (non-Javadoc) * @see java.lang.Object#toString() */ public String toString() { try { CompilationUnitChange change= getCompilationUnitChange(); return change.getPreviewContent(); } catch (CoreException e) { } return super.toString(); } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/LinkedNamesAssistProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.Arrays; import java.util.Comparator; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder; import org.eclipse.jdt.internal.corext.dom.NodeFinder; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; /** * A template proposal. */ public class LinkedNamesAssistProposal implements IJavaCompletionProposal, ICompletionProposalExtension2 { private SimpleName fNode; private IRegion fSelectedRegion; // initialized by apply() private ICompilationUnit fCompilationUnit; public LinkedNamesAssistProposal(ICompilationUnit cu, SimpleName node) { fNode= node; fCompilationUnit= cu; } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, final int offset) { try { // create full ast CompilationUnit root= AST.parseCompilationUnit(fCompilationUnit, true); SimpleName nameNode= (SimpleName) NodeFinder.perform(root, fNode.getStartPosition(), fNode.getLength()); ASTNode[] sameNodes= LinkedNodeFinder.perform(root, nameNode.resolveBinding()); // sort for iteration order, starting with the node @ offset Arrays.sort(sameNodes, new Comparator() { /* * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object o1, Object o2) { return rank((ASTNode) o1) - rank((ASTNode) o2); } /** * Returns the absolute rank of an <code>ASTNode</code>. Nodes * preceding <code>offset</code> are ranked last. * * @param node the node to compute the rank for * @return the rank of the node with respect to the invocation offset */ private int rank(ASTNode node) { int relativeRank= node.getStartPosition() + node.getLength() - offset; if (relativeRank < 0) return Integer.MAX_VALUE + relativeRank; else return relativeRank; } }); IDocument document= viewer.getDocument(); LinkedPositionGroup group= new LinkedPositionGroup(); for (int i= 0; i < sameNodes.length; i++) { ASTNode elem= sameNodes[i]; group.createPosition(document, elem.getStartPosition(), elem.getLength(), i); } LinkedEnvironment enviroment= LinkedEnvironment.createLinkedEnvironment(document); enviroment.addGroup(group); LinkedUIControl ui= new LinkedUIControl(enviroment, viewer); // ui.setInitialOffset(offset); ui.setExitPosition(viewer, offset, 0, false); ui.enter(); fSelectedRegion= ui.getSelectedRegion(); } catch (BadLocationException e) { } } /* * @see ICompletionProposal#apply(IDocument) */ public void apply(IDocument document) { // can't do anything } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { return CorrectionMessages.getString("LinkedNamesAssistProposal.proposalinfo"); //$NON-NLS-1$ } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { return CorrectionMessages.getString("LinkedNamesAssistProposal.description"); //$NON-NLS-1$ } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL); } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return null; } /* * @see IJavaCompletionProposal#getRelevance() */ public int getRelevance() { return 1; } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean) */ public void selected(ITextViewer textViewer, boolean smartToggle) { } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer) */ public void unselected(ITextViewer textViewer) { } /* (non-Javadoc) * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) */ public boolean validate(IDocument document, int offset, DocumentEvent event) { return false; } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ExperimentalProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; /** * An experimental proposal. */ public class ExperimentalProposal extends JavaCompletionProposal { private int[] fPositionOffsets; private int[] fPositionLengths; private ITextViewer fViewer; private IRegion fSelectedRegion; // initialized by apply() /** * Creates a template proposal with a template and its context. * @param template the template * @param context the context in which the template was requested. * @param image the icon of the proposal. */ public ExperimentalProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int[] positionOffsets, int[] positionLengths, ITextViewer viewer, int relevance) { super(replacementString, replacementOffset, replacementLength, image, displayString, relevance); fPositionOffsets= positionOffsets; fPositionLengths= positionLengths; fViewer= viewer; } /* * @see ICompletionProposalExtension#apply(IDocument, char) */ public void apply(IDocument document, char trigger, int offset) { super.apply(document, trigger, offset); int replacementOffset= getReplacementOffset(); String replacementString= getReplacementString(); if (LinkedEnvironment.hasEnvironment(document)) { fSelectedRegion= (fPositionOffsets.length == 0) ? new Region(replacementOffset + replacementString.length(), 0) : new Region(replacementOffset + fPositionOffsets[0], fPositionLengths[0]); } else if (fPositionOffsets.length > 0) { try { LinkedEnvironment env= LinkedEnvironment.createLinkedEnvironment(document); for (int i= 0; i != fPositionOffsets.length; i++) { LinkedPositionGroup group= new LinkedPositionGroup(); group.createPosition(document, replacementOffset + fPositionOffsets[i], fPositionLengths[i]); env.addGroup(group); } LinkedUIControl ui= new LinkedUIControl(env, fViewer); ui.setExitPosition(fViewer, replacementOffset + replacementString.length(), 0, true); ui.enter(); fSelectedRegion= ui.getSelectedRegion(); } catch (BadLocationException e) { JavaPlugin.log(e); openErrorDialog(e); } } else fSelectedRegion= new Region(replacementOffset + replacementString.length(), 0); } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { if (fSelectedRegion == null) return new Point(getReplacementOffset(), 0); return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } private void openErrorDialog(BadLocationException e) { Shell shell= fViewer.getTextWidget().getShell(); MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.RGB; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferenceConverter; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.ITextViewerExtension2; import org.eclipse.jface.text.ITextViewerExtension3; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.text.JavaTextTools; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.link.ILinkedListener; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.ExitFlags; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl.IExitPolicy; public class JavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension, ICompletionProposalExtension2 { private String fDisplayString; private String fReplacementString; private int fReplacementOffset; private int fReplacementLength; private int fCursorPosition; private Image fImage; private IContextInformation fContextInformation; private int fContextInformationPosition; private ProposalInfo fProposalInfo; private char[] fTriggerCharacters; protected boolean fToggleEating; protected ITextViewer fTextViewer; private int fRelevance; private StyleRange fRememberedStyleRange; /** * Creates a new completion proposal. All fields are initialized based on the provided information. * * @param replacementString the actual string to be inserted into the document * @param replacementOffset the offset of the text to be replaced * @param replacementLength the length of the text to be replaced * @param image the image to display for this proposal * @param displayString the string to be displayed for the proposal * If set to <code>null</code>, the replacement string will be taken as display string. */ public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) { this(replacementString, replacementOffset, replacementLength, image, displayString, relevance, null); } /** * Creates a new completion proposal. All fields are initialized based on the provided information. * * @param replacementString the actual string to be inserted into the document * @param replacementOffset the offset of the text to be replaced * @param replacementLength the length of the text to be replaced * @param image the image to display for this proposal * @param displayString the string to be displayed for the proposal * @param viewer the text viewer for which this proposal is computed, may be <code>null</code> * If set to <code>null</code>, the replacement string will be taken as display string. */ public JavaCompletionProposal(String replacementString, int replacementOffset, int replacementLength, Image image, String displayString, int relevance, ITextViewer viewer) { Assert.isNotNull(replacementString); Assert.isTrue(replacementOffset >= 0); Assert.isTrue(replacementLength >= 0); fReplacementString= replacementString; fReplacementOffset= replacementOffset; fReplacementLength= replacementLength; fImage= image; fDisplayString= displayString != null ? displayString : replacementString; fRelevance= relevance; fTextViewer= viewer; fCursorPosition= replacementString.length(); fContextInformation= null; fContextInformationPosition= -1; fTriggerCharacters= null; fProposalInfo= null; } /** * Sets the context information. * @param contentInformation The context information associated with this proposal */ public void setContextInformation(IContextInformation contextInformation) { fContextInformation= contextInformation; fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); } /** * Sets the trigger characters. * @param triggerCharacters The set of characters which can trigger the application of this completion proposal */ public void setTriggerCharacters(char[] triggerCharacters) { fTriggerCharacters= triggerCharacters; } /** * Sets the proposal info. * @param additionalProposalInfo The additional information associated with this proposal or <code>null</code> */ public void setProposalInfo(ProposalInfo proposalInfo) { fProposalInfo= proposalInfo; } /** * Sets the cursor position relative to the insertion offset. By default this is the length of the completion string * (Cursor positioned after the completion) * @param cursorPosition The cursorPosition to set */ public void setCursorPosition(int cursorPosition) { Assert.isTrue(cursorPosition >= 0); fCursorPosition= cursorPosition; fContextInformationPosition= (fContextInformation != null ? fCursorPosition : -1); } /* * @see ICompletionProposalExtension#apply(IDocument, char, int) */ public void apply(IDocument document, char trigger, int offset) { try { // patch replacement length int delta= offset - (fReplacementOffset + fReplacementLength); if (delta > 0) fReplacementLength += delta; String string; if (trigger == (char) 0) { string= fReplacementString; } else { StringBuffer buffer= new StringBuffer(fReplacementString); // fix for PR #5533. Assumes that no eating takes place. if ((fCursorPosition > 0 && fCursorPosition <= buffer.length() && buffer.charAt(fCursorPosition - 1) != trigger)) { buffer.insert(fCursorPosition, trigger); ++fCursorPosition; } string= buffer.toString(); } // reference position just at the end of the document change. int referenceOffset= fReplacementOffset + fReplacementLength; final ReferenceTracker referenceTracker= new ReferenceTracker(); referenceTracker.preReplace(document, referenceOffset); replace(document, fReplacementOffset, fReplacementLength, string); referenceOffset= referenceTracker.postReplace(document); fReplacementOffset= referenceOffset - (string == null ? 0 : string.length()); if (fTextViewer != null && string != null) { int index= string.indexOf("()"); //$NON-NLS-1$ if (index != -1 && index + 1 == fCursorPosition) { IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore(); if (preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACKETS)) { int newOffset= fReplacementOffset + fCursorPosition; LinkedPositionGroup group= new LinkedPositionGroup(); group.createPosition(document, newOffset, 0); LinkedEnvironment env= LinkedEnvironment.createLinkedEnvironment(document); env.addGroup(group); LinkedUIControl ui= new LinkedUIControl(env, fTextViewer); ui.setExitPolicy(new ExitPolicy(')')); ui.setExitPosition(fTextViewer, newOffset + 1, 0, true); ui.setCyclingMode(LinkedUIControl.CYCLE_NEVER); ui.enter(); } } } } catch (BadLocationException x) { // ignore } } /** * A class to simplify tracking a reference position in a document. */ private static final class ReferenceTracker { /** The reference position category name. */ private static final String CATEGORY= "reference_position"; //$NON-NLS-1$ /** The position updater of the reference position. */ private final IPositionUpdater fPositionUpdater= new DefaultPositionUpdater(CATEGORY); /** The reference position. */ private final Position fPosition= new Position(0); /** * Called before document changes occur. It must be followed by a call to postReplace(). * * @param document the document on which to track the reference position. * */ public void preReplace(IDocument document, int offset) throws BadLocationException { fPosition.setOffset(offset); try { document.addPositionCategory(CATEGORY); document.addPositionUpdater(fPositionUpdater); document.addPosition(CATEGORY, fPosition); } catch (BadPositionCategoryException e) { // should not happen JavaPlugin.log(e); } } /** * Called after the document changed occured. It must be preceded by a call to preReplace(). * * @param document the document on which to track the reference position. */ public int postReplace(IDocument document) { try { document.removePosition(CATEGORY, fPosition); document.removePositionUpdater(fPositionUpdater); document.removePositionCategory(CATEGORY); } catch (BadPositionCategoryException e) { // should not happen JavaPlugin.log(e); } return fPosition.getOffset(); } } private static class ExitPolicy implements IExitPolicy { final char fExitCharacter; public ExitPolicy(char exitCharacter) { fExitCharacter= exitCharacter; } /* * @see org.eclipse.jdt.internal.ui.text.link.LinkedPositionUI.ExitPolicy#doExit(org.eclipse.jdt.internal.ui.text.link.LinkedPositionManager, org.eclipse.swt.events.VerifyEvent, int, int) */ public ExitFlags doExit(VerifyEvent event, int offset, int length) { if (event.character == fExitCharacter) { // if (manager.anyPositionIncludes(offset, length)) // return new ExitFlags(LinkedPositionUI.COMMIT| LinkedPositionUI.UPDATE_CARET, false); // else return new ExitFlags(ILinkedListener.UPDATE_CARET, true); } switch (event.character) { case '\b': // if (manager.getFirstPosition().length == 0) // return new ExitFlags(0, true); // else return null; case '\n': case '\r': return new ExitFlags(ILinkedListener.UPDATE_CARET, false); case ';': return new ExitFlags(ILinkedListener.NONE, true); default: return null; } } } // #6410 - File unchanged but dirtied by code assist private void replace(IDocument document, int offset, int length, String string) throws BadLocationException { if (!document.get(offset, length).equals(string)) document.replace(offset, length, string); } /* * @see ICompletionProposal#apply */ public void apply(IDocument document) { apply(document, (char) 0, fReplacementOffset + fReplacementLength); } /* * @see ICompletionProposal#getSelection */ public Point getSelection(IDocument document) { return new Point(fReplacementOffset + fCursorPosition, 0); } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return fContextInformation; } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return fImage; } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { return fDisplayString; } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { if (fProposalInfo != null) { return fProposalInfo.getInfo(); } return null; } /* * @see ICompletionProposalExtension#getTriggerCharacters() */ public char[] getTriggerCharacters() { return fTriggerCharacters; } /* * @see ICompletionProposalExtension#getContextInformationPosition() */ public int getContextInformationPosition() { return fReplacementOffset + fContextInformationPosition; } /** * Gets the replacement offset. * @return Returns a int */ public int getReplacementOffset() { return fReplacementOffset; } /** * Sets the replacement offset. * @param replacementOffset The replacement offset to set */ public void setReplacementOffset(int replacementOffset) { Assert.isTrue(replacementOffset >= 0); fReplacementOffset= replacementOffset; } /** * Gets the replacement length. * @return Returns a int */ public int getReplacementLength() { return fReplacementLength; } /** * Sets the replacement length. * @param replacementLength The replacementLength to set */ public void setReplacementLength(int replacementLength) { Assert.isTrue(replacementLength >= 0); fReplacementLength= replacementLength; } /** * Gets the replacement string. * @return Returns a String */ public String getReplacementString() { return fReplacementString; } /** * Sets the replacement string. * @param replacementString The replacement string to set */ public void setReplacementString(String replacementString) { fReplacementString= replacementString; } /** * Sets the image. * @param image The image to set */ public void setImage(Image image) { fImage= image; } /* * @see ICompletionProposalExtension#isValidFor(IDocument, int) */ public boolean isValidFor(IDocument document, int offset) { return validate(document, offset, null); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) */ public boolean validate(IDocument document, int offset, DocumentEvent event) { if (offset < fReplacementOffset) return false; /* * See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667 String word= fReplacementString; */ boolean validated= startsWith(document, offset, fDisplayString); if (validated && event != null) { // adapt replacement range to document change int delta= (event.fText == null ? 0 : event.fText.length()) - event.fLength; fReplacementLength += delta; } return validated; } /** * Gets the proposal's relevance. * @return Returns a int */ public int getRelevance() { return fRelevance; } /** * Sets the proposal's relevance. * @param relevance The relevance to set */ public void setRelevance(int relevance) { fRelevance= relevance; } /** * Returns <code>true</code> if a words starts with the code completion prefix in the document, * <code>false</code> otherwise. */ protected boolean startsWith(IDocument document, int offset, String word) { int wordLength= word == null ? 0 : word.length(); if (offset > fReplacementOffset + wordLength) return false; try { int length= offset - fReplacementOffset; String start= document.get(fReplacementOffset, length); return word.substring(0, length).equalsIgnoreCase(start); } catch (BadLocationException x) { } return false; } private static boolean insertCompletion() { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); return preference.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension1#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { IDocument document= viewer.getDocument(); // don't eat if not in preferences, XOR with modifier key 1 (Ctrl) // but: if there is a selection, replace it! Point selection= viewer.getSelectedRange(); fToggleEating= (stateMask & SWT.MOD1) != 0; if (insertCompletion() ^ fToggleEating) fReplacementLength= selection.x + selection.y - fReplacementOffset; apply(document, trigger, offset); fToggleEating= false; } private static Color getForegroundColor(StyledText text) { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); RGB rgb= PreferenceConverter.getColor(preference, PreferenceConstants.CODEASSIST_REPLACEMENT_FOREGROUND); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private static Color getBackgroundColor(StyledText text) { IPreferenceStore preference= JavaPlugin.getDefault().getPreferenceStore(); RGB rgb= PreferenceConverter.getColor(preference, PreferenceConstants.CODEASSIST_REPLACEMENT_BACKGROUND); JavaTextTools textTools= JavaPlugin.getDefault().getJavaTextTools(); return textTools.getColorManager().getColor(rgb); } private void repairPresentation(ITextViewer viewer) { if (fRememberedStyleRange != null) { if (viewer instanceof ITextViewerExtension2) { // attempts to reduce the redraw area ITextViewerExtension2 viewer2= (ITextViewerExtension2) viewer; if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; IRegion widgetRange= extension.modelRange2WidgetRange(new Region(fRememberedStyleRange.start, fRememberedStyleRange.length)); if (widgetRange != null) viewer2.invalidateTextPresentation(widgetRange.getOffset(), widgetRange.getLength()); } else { viewer2.invalidateTextPresentation(fRememberedStyleRange.start + viewer.getVisibleRegion().getOffset(), fRememberedStyleRange.length); } } else viewer.invalidateTextPresentation(); } } private void updateStyle(ITextViewer viewer) { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return; int widgetCaret= text.getCaretOffset(); int modelCaret= 0; if (viewer instanceof ITextViewerExtension3) { ITextViewerExtension3 extension= (ITextViewerExtension3) viewer; modelCaret= extension.widgetOffset2ModelOffset(widgetCaret); } else { IRegion visibleRegion= viewer.getVisibleRegion(); modelCaret= widgetCaret + visibleRegion.getOffset(); } if (modelCaret >= fReplacementOffset + fReplacementLength) { repairPresentation(viewer); return; } int offset= widgetCaret; int length= fReplacementOffset + fReplacementLength - modelCaret; Color foreground= getForegroundColor(text); Color background= getBackgroundColor(text); StyleRange range= text.getStyleRangeAtOffset(offset); int fontStyle= range != null ? range.fontStyle : SWT.NORMAL; repairPresentation(viewer); fRememberedStyleRange= new StyleRange(offset, length, foreground, background, fontStyle); // http://dev.eclipse.org/bugs/show_bug.cgi?id=34754 try { text.setStyleRange(fRememberedStyleRange); } catch (IllegalArgumentException x) { // catching exception as offset + length might be outside of the text widget fRememberedStyleRange= null; } } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(ITextViewer, boolean) */ public void selected(ITextViewer viewer, boolean smartToggle) { if (!insertCompletion() ^ smartToggle) updateStyle(viewer); else { repairPresentation(viewer); fRememberedStyleRange= null; } } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(ITextViewer) */ public void unselected(ITextViewer viewer) { repairPresentation(viewer); fRememberedStyleRange= null; } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ParameterGuessingProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Andrew McCullough - initial API and implementation * IBM Corporation - general improvement and bug fixes, partial reimplementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.CompletionProposal; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; /** * This is a {@link org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposal} which includes templates * that represent the best guess completion for each parameter of a method. */ public class ParameterGuessingProposal extends JavaCompletionProposal { private final char[] fName; private final char[][] fParameterNames; private final char[][] fParamaterTypePackageNames; private final char[][] fParameterTypeNames; private final int fCodeAssistOffset; private final ICompilationUnit fCompilationUnit; private final ITextViewer fViewer; private IRegion fSelectedRegion; // initialized by apply() private ICompletionProposal[][] fChoices; // initialized by guessParameters() /** * Creates a template proposal with a template and its context. * @param template the template * @param context the context in which the template was requested. * @param image the icon of the proposal. */ public ParameterGuessingProposal( int replacementOffset, int replacementLength, Image image, String displayString, ITextViewer viewer, int relevance, char[] name, char[][] paramaterTypePackageNames, char[][] parameterTypeNames, char[][] parameterNames, int codeAssistOffset, ICompilationUnit compilationUnit) { // replacementString is set in apply() super("", replacementOffset, replacementLength, image, displayString, relevance); //$NON-NLS-1$ fName= name; fParamaterTypePackageNames= paramaterTypePackageNames; fParameterTypeNames= parameterTypeNames; fParameterNames= parameterNames; fViewer= viewer; fCodeAssistOffset= codeAssistOffset; fCompilationUnit= compilationUnit; } private boolean appendArguments(IDocument document, int offset) { IPreferenceStore preferenceStore= JavaPlugin.getDefault().getPreferenceStore(); if (preferenceStore.getBoolean(PreferenceConstants.CODEASSIST_INSERT_COMPLETION) ^ fToggleEating) return true; try { IRegion region= document.getLineInformationOfOffset(offset); String line= document.get(region.getOffset(), region.getLength()); int index= offset - region.getOffset(); while (index != line.length() && Character.isUnicodeIdentifierPart(line.charAt(index))) ++index; if (index == line.length()) return true; return line.charAt(index) != '('; } catch (BadLocationException e) { return true; } } /* * @see ICompletionProposalExtension#apply(IDocument, char) */ public void apply(IDocument document, char trigger, int offset) { try { int parameterCount= fParameterNames.length; int[] positionOffsets; int[] positionLengths; String replacementString; int baseOffset= getReplacementOffset(); if (appendArguments(document, offset)) { parameterCount= fParameterNames.length; positionOffsets= new int[parameterCount]; positionLengths= new int[parameterCount]; replacementString= computeGuessingCompletion(baseOffset, positionOffsets, positionLengths); } else { parameterCount= 0; positionOffsets= new int[0]; positionLengths= new int[0]; replacementString= new String(fName); } setReplacementString(replacementString); super.apply(document, trigger, offset); if (parameterCount > 0) { LinkedEnvironment environment= LinkedEnvironment.createLinkedEnvironment(document); for (int i= 0; i != parameterCount; i++) { LinkedPositionGroup group= new LinkedPositionGroup(); int positionOffset= baseOffset + positionOffsets[i]; if (fChoices[i].length < 2) { group.createPosition(document, positionOffset, positionLengths[i]); } else { group.createPosition(document, positionOffset, positionLengths[i], fChoices[i]); } environment.addGroup(group); } LinkedUIControl editor= new LinkedUIControl(environment, fViewer); editor.setExitPosition(fViewer, baseOffset + replacementString.length(), 0, true); editor.setCyclingMode(LinkedUIControl.CYCLE_WHEN_NO_PARENT); editor.enter(); fSelectedRegion= editor.getSelectedRegion(); } else { fSelectedRegion= new Region(baseOffset + replacementString.length(), 0); } } catch (BadLocationException e) { JavaPlugin.log(e); openErrorDialog(e); } catch (JavaModelException e) { JavaPlugin.log(e); openErrorDialog(e); } } private ICompletionProposal[][] guessParameters(int offset) throws JavaModelException { // find matches in reverse order. Do this because people tend to declare the variable meant for the last // parameter last. That is, local variables for the last parameter in the method completion are more // likely to be closer to the point of codecompletion. As an example consider a "delegation" completion: // // public void myMethod(int param1, int param2, int param3) { // someOtherObject.yourMethod(param1, param2, param3); // } // // The other consideration is giving preference to variables that have not previously been used in this // code completion (which avoids "someOtherObject.yourMethod(param1, param1, param1)"; fChoices= new ICompletionProposal[fParameterNames.length][]; if (fCompilationUnit == null) { for (int i= 0; i != fParameterNames.length; i++) { String name= new String(fParameterNames[i]); int length= name.length(); fChoices[i]= new ICompletionProposal[] {new CompletionProposal(name, offset, length, length)}; offset+= length + 2; } return fChoices; } else { synchronized (fCompilationUnit) { fCompilationUnit.reconcile(); } ParameterGuesser guesser= new ParameterGuesser(fCodeAssistOffset, fCompilationUnit); for (int i= fParameterNames.length - 1; i >= 0; i--) { String paramName= new String(fParameterNames[i]); ICompletionProposal[] parameter= guesser.parameterProposals( new String(fParamaterTypePackageNames[i]), new String(fParameterTypeNames[i]), paramName, offset); int paramLength= paramName.length(); fChoices[i]= (parameter == null) ? new ICompletionProposal[] {new CompletionProposal(paramName, offset, paramLength, paramLength)} : parameter; offset+= paramLength + 2; } return fChoices; } } /** * Creates the completion string. Offsets and Lengths are set to the offsets and lengths * of the parameters. */ private String computeGuessingCompletion(int startOffset, int[] offsets, int[] lengths) throws JavaModelException { StringBuffer buffer= new StringBuffer(); buffer.append(fName); buffer.append('('); fChoices= guessParameters(startOffset+buffer.length()); for (int i= 0; i < fChoices.length; i++) { if (i != 0) buffer.append(", "); //$NON-NLS-1$ offsets[i]= buffer.length(); ICompletionProposal[] proposals= fChoices[i]; String display= proposals.length > 0 ? proposals[0].getDisplayString() : new String(fParameterNames[i]); buffer.append(display); lengths[i]= buffer.length() - offsets[i]; } buffer.append(')'); return buffer.toString(); } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { if (fSelectedRegion == null) return new Point(getReplacementOffset(), 0); return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } private void openErrorDialog(Exception e) { Shell shell= fViewer.getTextWidget().getShell(); MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ } /* * @see java.lang.Object#toString() */ public String toString() { return getDisplayString() + super.toString(); } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedEnvironment.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.link; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.text.edits.MalformedTreeException; import org.eclipse.text.edits.TextEdit; import org.eclipse.core.runtime.Status; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IDocumentExtension; import org.eclipse.jface.text.IDocumentListener; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IDocumentExtension.IReplace; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * A <code> LinkedEnvironment</code> umbrellas several <code>PositionGroup</code>s. * Responsible for updating the siblings of a linked position when a change * occurs. * * @since 3.0 */ public class LinkedEnvironment { /** * Returns a linked environment on <code>document</code>. * * @param document the document for which a <code>LinkedManager</code> is * requested * @return a linked environment for <code>document</code> */ public static LinkedEnvironment createLinkedEnvironment(IDocument document) { return LinkedManager.createEnvironment(document); } /** * Returns a linked environment for the specified documents. Throws a * <code>BadLocationException</code> if there is a conflict between the * documents (i.e. two or more environments are already installed on * subsets of <code>documents</code>). * * @param documents the documents for which a�<code>LinkedManager</code> * is requested * @return a linked manager for <code>documents</code> * @throws BadLocationException if there is a conflict */ public static LinkedEnvironment createLinkedEnvironment(IDocument[] documents) throws BadLocationException { return LinkedManager.createEnvironment(documents); } /** * Checks whether there is alreay a linked environment installed on <code>document</code>. * * @param document the <code>IDocument</code> of interest * @return <code>true</code> if there is an existing environment, <code>false</code> * otherwise */ public static boolean hasEnvironment(IDocument document) { // if there is a manager, there also is an enviroment return LinkedManager.hasManager(document); } /** * Checks whether there is alreay a linked environment installed on any of * the <code>documents</code>. * * @param documents the <code>IDocument</code> s of interest * @return <code>true</code> if there is an existing environment, <code>false</code> * otherwise */ public static boolean hasEnvironment(IDocument[] documents) { // if there is a manager, there also is an enviroment return LinkedManager.hasManager(documents); } /** * Cancels any linked environment on the specified document. If there is no * environment, nothing happens. * * @param document the document whose <code>LinkedEnvironment</code> should * be cancelled */ public static void closeEnvironment(IDocument document) { LinkedManager.cancelManager(document); } /** * Encapsulates the edition triggered by a change to a linked position. Can * be applied to a document as a whole. */ private class Replace implements IReplace { /** The edition to apply on a document. */ private TextEdit fEdit; /** * Creates a new instance. * * @param edit the edition to apply to a document. */ public Replace(TextEdit edit) { fEdit= edit; } /* * @see org.eclipse.jface.text.IDocumentExtension.IReplace#perform(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.IDocumentListener) */ public void perform(IDocument document, IDocumentListener owner) { document.removeDocumentListener(owner); fIsChanging= true; try { fEdit.apply(document, TextEdit.UPDATE_REGIONS | TextEdit.CREATE_UNDO); } catch (MalformedTreeException e) { // log & ignore (can happen on concurrent document modifications JavaPlugin.log(new Status(Status.WARNING, JavaPlugin.getPluginId(), Status.OK, "error when applying changes", e)); //$NON-NLS-1$ } catch (BadLocationException e) { // log & ignore (can happen on concurrent document modifications JavaPlugin.log(new Status(Status.WARNING, JavaPlugin.getPluginId(), Status.OK, "error when applying changes", e)); //$NON-NLS-1$ } finally { document.addDocumentListener(owner); fIsChanging= false; } } } /** * The document listener triggering the linked updating of positions * managed by this environment. */ private class DocumentListener implements IDocumentListener { /* * @see org.eclipse.jface.text.IDocumentListener#documentAboutToBeChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentAboutToBeChanged(DocumentEvent event) { // don't react on changes executed by the parent environment if (fParentEnvironment != null && fParentEnvironment.isChanging()) return; for (Iterator it= fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup group= (LinkedPositionGroup) it.next(); if (group.isLegalEvent(event)) // take the first hit - exlusion is guaranteed by enforcing // disjointness when adding positions return; } // the event describes a change that lies outside of any managed // position -> exit mode. // TODO we might not always want to exit, e.g. we want to stay // linked if code completion has inserted import statements LinkedEnvironment.this.exit(ILinkedListener.EXTERNAL_MODIFICATION); } /* * @see org.eclipse.jface.text.IDocumentListener#documentChanged(org.eclipse.jface.text.DocumentEvent) */ public void documentChanged(DocumentEvent event) { // don't react on changes executed by the parent environment if (fParentEnvironment != null && fParentEnvironment.isChanging()) return; for (Iterator it= fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup group= (LinkedPositionGroup) it.next(); Map result= group.handleEvent(event); if (result == null) continue; // edit all documents for (Iterator it2= result.keySet().iterator(); it2.hasNext(); ) { IDocument doc= (IDocument) it2.next(); TextEdit edit= (TextEdit) result.get(doc); Replace replace= new Replace(edit); // apply the edition, either as post notification replace // on the calling document or directly on any other // document if (doc == event.getDocument()) { if (doc instanceof IDocumentExtension) { ((IDocumentExtension) doc).registerPostNotificationReplace(this, replace); } else { JavaPlugin.log(new Status(Status.WARNING, JavaPlugin.getPluginId(), Status.OK, "not executing changes on document that is not a IDocumentExtension", null)); //$NON-NLS-1$ } } else { replace.perform(doc, this); } } // take the first hit - exlusion is guaranteed by enforcing // disjointness when adding positions return; } } } /** The set of linked position groups. */ private final List fGroups= new ArrayList(); /** The set of documents spanned by this group. */ private final Set fDocuments= new HashSet(); /** The position updater for linked positions. */ private final IPositionUpdater fUpdater= new InclusivePositionUpdater(getCategory()); /** The document listener on the documents affected by this environment. */ private final IDocumentListener fDocumentListener= new DocumentListener(); /** The parent environment for a hierachical set up, or <code>null</code>. */ private final LinkedEnvironment fParentEnvironment; // set in ctor /** * The position in <code>fParentEnvironment</code> that includes all * positions in this object, or <code>null</code> if there is no parent * environment. */ private LinkedPosition fParentPosition= null; /** * An environment is sealed once it has children - no more positions can be * added. */ private boolean fIsSealed= false; /** <code>true</code> when this environment is changing documents. */ private boolean fIsChanging= false; /** The linked listeners. */ private final List fListeners= new ArrayList(); /** Flag telling whether we have exited: */ private boolean fIsActive= true; /** * The sequence of document positions as we are going to iterate through * them. */ private List fPositionSequence= new ArrayList(); /** * Creates a new environment. If <code>parent</code> is not <code>null</code>, * a nested environment is created. * * @param parent the parent environment, or <code>null</code> for a * top-level environment */ LinkedEnvironment(LinkedEnvironment parent) { // TODO debug trace the erroneous nestings. Assert.isTrue(parent == null || parent.fGroups.size() > 0); fParentEnvironment= parent; if (parent != null) parent.suspend(); } /** * Whether we are in the process of editing documents (set by <code>Replace</code>, * read by <code>DocumentListener</code>. * * @return <code>true</code> if we are in the process of editing a * document, <code>false</code> otherwise */ private boolean isChanging() { return fIsChanging || fParentEnvironment != null && fParentEnvironment.isChanging(); } /** * Throws a <code>BadLocationException</code> if <code>group</code> * conflicts with this environment's groups. * * @param group the group being checked * @throws BadLocationException if <code>group</code> conflicts with this * environment's groups */ private void enforceDisjoint(LinkedPositionGroup group) throws BadLocationException { for (Iterator it= fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup g= (LinkedPositionGroup) it.next(); g.enforceDisjoint(group); } } /** * Causes this environment to exit. Called either if a document change * outside this enviroment is detected, or by the UI. * * <p>This method part of the private protocol between <code>LinkedUIControl</code> and <code>LinkedEnvironment</code>.</p> * * @param flags the exit flags. */ void exit(int flags) { if (!fIsActive) return; fIsActive= false; for (Iterator it= fDocuments.iterator(); it.hasNext(); ) { IDocument doc= (IDocument) it.next(); try { doc.removePositionCategory(getCategory()); } catch (BadPositionCategoryException e) { // won't happen Assert.isTrue(false); } doc.removePositionUpdater(fUpdater); doc.removeDocumentListener(fDocumentListener); } fDocuments.clear(); fGroups.clear(); for (Iterator it= fListeners.iterator(); it.hasNext(); ) { ILinkedListener listener= (ILinkedListener) it.next(); listener.left(this, flags); } fListeners.clear(); if (fParentEnvironment != null) fParentEnvironment.resume(flags); } /** * Puts <code>document</code> into the set of managed documents. This * involves registering the document listener and adding our position * category. * * @param document the new document */ private void manageDocument(IDocument document) { if (!fDocuments.contains(document)) { fDocuments.add(document); document.addPositionCategory(getCategory()); document.addPositionUpdater(fUpdater); document.addDocumentListener(fDocumentListener); } } /** * Returns the position category used by this environment. * * @return the position category used by this environment */ private String getCategory() { return toString(); } /** * Adds a position group to this <code>LinkedEnvironment</code>. This * method may not be called if the environment is already sealed, i.e. a * nested environment has been added to it. It is also not wise to add * groups once a UI has been established on top of this environment. * * <p> * If the positions in <code>group</code> conflict with any other groups * in this environment, a <code>BadLocationException</code> is thrown. * Also, if this environment is nested in another one, all positions in all * groups of the child environment have to lie in a single position in the * parent environment, otherwise a <code>BadLocationException</code> is * thrown. * </p> * * <p> * If <code>group</code> already exists, nothing happens. * </p> * * @param group the group to be added to this environment * @throws BadLocationException if the group conflicts with the other * groups in this environment or violates the nesting requirements. * @throws IllegalStateException if the method is called when the * environment is already sealed */ public void addGroup(LinkedPositionGroup group) throws BadLocationException { Assert.isNotNull(group); if (fIsSealed) throw new IllegalStateException("environment is already sealed"); //$NON-NLS-1$ if (fGroups.contains(group)) // nothing happens return; enforceNestability(group); enforceDisjoint(group); group.setEnvironment(this); fGroups.add(group); } /** * Called by nested environments when a group is added to them. All * positions in all groups of a nested environment have to fit inside a * single position in the parent environment. * * @param group the group of the nested environment to be adopted. * @throws BadLocationException if the nesting requirement is violated */ private void enforceNestability(LinkedPositionGroup group) throws BadLocationException { // TODO debug trace the erroneous nestings. Assert.isTrue(fParentEnvironment == null || fParentEnvironment.fGroups.size() > 0); if (fParentEnvironment == null) return; for (Iterator it= fParentEnvironment.fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup pg= (LinkedPositionGroup) it.next(); LinkedPosition pos= pg.adopt(group); if (pos != null && fParentPosition != null && fParentPosition != pos) throw new BadLocationException(); else if (fParentPosition == null && pos != null) fParentPosition= pos; } // group must fit in exactly one of the parent's positions if (fParentPosition == null) throw new BadLocationException(); } /** * Seals this environment. Further calls to <code>addGroup</code> will * throw an <code>IllegalStateException</code>. */ void seal() { fIsSealed= true; } /** * Returns whether this environment is nested. * * <p>This method part of the private protocol between <code>LinkedUIControl</code> and <code>LinkedEnvironment</code>.</p> * * @return <code>true</code> if this environment is nested, <code>false</code> * otherwise */ boolean isNested() { return fParentEnvironment != null; } /** * Returns the positions in this environment that have a tab stop, in the * order they were added. * * <p>This method part of the private protocol between <code>LinkedUIControl</code> and <code>LinkedEnvironment</code>.</p> * * @return the positions in this environment that have a tab stop, in the * order they were added */ List getTabStopSequence() { return fPositionSequence; } /** * Adds <code>listener</code> to the set of listeners that are informed * upon state changes. * * @param listener the new listener */ public void addLinkedListener(ILinkedListener listener) { Assert.isNotNull(listener); if (!fListeners.contains(listener)) fListeners.add(listener); } /** * Removes <code>listener</code> from the set of listeners that are * informed upon state changes. * * @param listener the new listener */ public void removeLinkedListener(ILinkedListener listener) { fListeners.remove(listener); } /** * Finds the position in this environment that is closest after <code>toFind</code>. * <code>toFind</code> needs not be a position in this environment and * serves merely as an offset. * * <p>This method part of the private protocol between <code>LinkedUIControl</code> and <code>LinkedEnvironment</code>.</p> * * @param toFind the position to search from * @return the closest position in the same document as <code>toFind</code> * after the offset of <code>toFind</code>, or <code>null</code> */ LinkedPosition findPosition(LinkedPosition toFind) { LinkedPosition position= null; for (Iterator it= fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup group= (LinkedPositionGroup) it.next(); position= group.getPosition(toFind); if (position != null) break; } return position; } /** * Registers a <code>LinkedPosition</code> with this environment. Called * by <code>PositionGroup</code>. * * @param position the position to register * @throws BadLocationException if the position cannot be added to its * document */ void register(LinkedPosition position) throws BadLocationException { Assert.isNotNull(position); IDocument document= position.getDocument(); manageDocument(document); try { document.addPosition(getCategory(), position); } catch (BadPositionCategoryException e) { // won't happen as the category has been added by manageDocument() Assert.isTrue(false); } int seqNr= position.getSequenceNumber(); if (seqNr != LinkedPositionGroup.NO_STOP) { fPositionSequence.add(position); } } /** * Suspends this environment. */ private void suspend() { List l= new ArrayList(fListeners); for (Iterator it= l.iterator(); it.hasNext(); ) { ILinkedListener listener= (ILinkedListener) it.next(); listener.suspend(this); } } /** * Resumes this environment. <code>flags</code> can be <code>NONE</code> * or <code>SELECT</code>. * * @param flags <code>NONE</code> or <code>SELECT</code> */ private void resume(int flags) { List l= new ArrayList(fListeners); for (Iterator it= l.iterator(); it.hasNext(); ) { ILinkedListener listener= (ILinkedListener) it.next(); listener.resume(this, flags); } } /** * Returns whether an offset is contained by any position in this * environment. * * <p>This method part of the private protocol between <code>LinkedUIControl</code> and <code>LinkedEnvironment</code>.</p> * * @param offset the offset to check * @return <code>true</code> if <code>offset</code> is included by any * position (see {@link LinkedPosition#includes(int)}) in this * environment, <code>false</code> otherwise */ boolean anyPositionContains(int offset) { for (Iterator it= fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup group= (LinkedPositionGroup) it.next(); if (group.contains(offset)) // take the first hit - exlusion is guaranteed by enforcing // disjointness when adding positions return true; } return false; } LinkedPositionGroup getGroupForPosition(LinkedPosition position) { for (Iterator it= fGroups.iterator(); it.hasNext(); ) { LinkedPositionGroup group= (LinkedPositionGroup) it.next(); if (group.contains(position)) return group; } return null; } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedManager.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.link; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Stack; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; /** * A linked manager ensures exclusive access of linked position infrastructures to documents. There * is at most one <code>LinkedManager</code> installed on the same document. The <code>getManager</code> * methods will return the existing instance if any of the specified documents already have an installed * manager. * * @since 3.0 */ class LinkedManager { /** * Our implementation of <code>ILinkedListener</code>. */ private class Listener implements ILinkedListener { /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#left(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void left(LinkedEnvironment environment, int flags) { LinkedManager.this.left(environment, flags); } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#suspend(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment) */ public void suspend(LinkedEnvironment environment) { // not interested } /* * @see org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment.ILinkedListener#resume(org.eclipse.jdt.internal.ui.text.link2.LinkedEnvironment, int) */ public void resume(LinkedEnvironment environment, int flags) { // not interested } } /** Global map from documents to managers. */ private static Map fManagers= new HashMap(); /** * Returns whether there exists a <code>LinkedManager</code> on <code>document</code>. * * @param document the document of interest * @return <code>true</code> if there exists a <code>LinkedManager</code> on <code>document</code>, <code>false</code> otherwise */ public static boolean hasManager(IDocument document) { return fManagers.get(document) != null; } /** * Returns whether there exists a <code>LinkedManager</code> on any of the <code>documents</code>. * * @param document the documents of interest * @return <code>true</code> if there exists a <code>LinkedManager</code> on any of the <code>documents</code>, <code>false</code> otherwise */ public static boolean hasManager(IDocument[] documents) { for (int i= 0; i < documents.length; i++) { if (hasManager(documents[i])) return true; } return false; } /** * Returns a linked environment on <code>document</code>. * * @param document the document for which a <code>LinkedManager</code> is requested * @return a linked environment for <code>document</code> */ public static LinkedEnvironment createEnvironment(IDocument document) { LinkedManager mgr= (LinkedManager) fManagers.get(document); if (mgr == null) { mgr= new LinkedManager(); fManagers.put(document, mgr); } return mgr.createLinkedEnvironment(); } /** * Returns the linked manager for the specified documents, or <code>null</code> if there is * a conflict between the documents (i.e. two or more managers are already installed on subsets * of <code>documents</code>). * * @param documents the documents for which a <code>LinkedManager</code> is requested * @return a linked manager for <code>documents</code>, or <code>null</code> if there is a conflict */ public static LinkedEnvironment createEnvironment(IDocument[] documents) throws BadLocationException { Set mgrs= new HashSet(); LinkedManager mgr= null; for (int i= 0; i < documents.length; i++) { mgr= (LinkedManager) fManagers.get(documents[i]); if (mgr != null) mgrs.add(mgr); } if (mgrs.size() > 1) throw new BadLocationException(); if (mgrs.size() == 0) mgr= new LinkedManager(); for (int i= 0; i < documents.length; i++) fManagers.put(documents[i], mgr); return mgr.createLinkedEnvironment(); } /** * Cancels any linked manager for the specified document. * * @param document the document whose <code>LinkedManager</code> should be cancelled */ public static void cancelManager(IDocument document) { LinkedManager mgr= (LinkedManager) fManagers.get(document); if (mgr != null) mgr.closeAllEnvironments(); } /** The hierarchy of environments managed by this manager. */ private Stack fEnvironments= new Stack(); private Listener fListener= new Listener(); /** * Creates a linked environment. If there are already other existing linked environments in the * manager, a nested linked environment is created. * * @return a linked environment on the documents of this manager. */ public LinkedEnvironment createLinkedEnvironment() { LinkedEnvironment env; if (fEnvironments.isEmpty()) { env= new LinkedEnvironment(null); } else { LinkedEnvironment parent= (LinkedEnvironment) fEnvironments.peek(); parent.seal(); env= new LinkedEnvironment(parent); } env.addLinkedListener(fListener); fEnvironments.push(env); return env; } /** * @param environment * @param flags */ private void left(LinkedEnvironment environment, int flags) { if (!fEnvironments.contains(environment)) return; while (!fEnvironments.isEmpty()) { LinkedEnvironment env= (LinkedEnvironment) fEnvironments.pop(); if (env == environment) break; else env.exit(ILinkedListener.NONE); } if (fEnvironments.isEmpty()) { removeManager(); } } private void closeAllEnvironments() { while (!fEnvironments.isEmpty()) { LinkedEnvironment env= (LinkedEnvironment) fEnvironments.pop(); env.exit(ILinkedListener.NONE); } removeManager(); } private void removeManager() { for (Iterator it= fManagers.keySet().iterator(); it.hasNext();) { IDocument doc= (IDocument) it.next(); if (fManagers.get(doc) == this) it.remove(); } } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/link/LinkedPositionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.link; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.eclipse.text.edits.MultiTextEdit; import org.eclipse.text.edits.ReplaceEdit; import org.eclipse.text.edits.TextEdit; import org.eclipse.jface.text.Assert; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContentAssistProcessor; /** * A group of positions in multiple documents that are simultaneously modified - * if one gets edited, all other positions in a <code>PositionGroup</code> * are edited the same way. All linked positions in a group have the same * content. * <p> * Normally, new positions are given a tab stop weight which can be used by * clients, e.g. the UI. If no weight is given, a position will not be visited. * If no weights are used at all, the first position in a document is taken as * the only stop as to comply with the behaviour of the old linked position * infrastructure. * </p> * * @since 3.0 */ public class LinkedPositionGroup { /** Sequence constant declaring that a position should not be stopped by. */ public static final int NO_STOP= -1; /* members */ /** The linked positions of this group. */ private final List fPositions= new LinkedList(); /** The environment. */ private LinkedEnvironment fEnvironment; /* * iteration variables, set to communicate state between isLegalEvent and * handleEvent */ /** The position including the most recent <code>DocumentEvent</code>. */ private LinkedPosition fLastPosition; /** The offset of <code>fLastPosition</code>. */ private int fLastPositionOffset; /** * <code>true</code> if there are custom iteration weights. For backward * compatibility. */ private boolean fHasCustomIteration= false; /** * Creates a new position group. */ public LinkedPositionGroup() { fEnvironment= null; } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param offset the offset of the position * @param length the length of the position * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument document, int offset, int length) throws BadLocationException { createPosition(document, offset, length, LinkedPositionGroup.NO_STOP); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param offset the offset of the position * @param length the length of the position * @param sequence the tab stop number of the position * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument document, int offset, int length, int sequence) throws BadLocationException { addPosition(new LinkedPosition(document, offset, length, sequence)); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param region a region describing the new position (it is not * stored, only its values are used) * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument doc, IRegion region) throws BadLocationException { createPosition(doc, region, LinkedPositionGroup.NO_STOP); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param region a region describing the new position (it is not * stored, only its values are used) * @param sequence the tab stop number of the position * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument doc, IRegion region, int sequence) throws BadLocationException { createPosition(doc, region.getOffset(), region.getLength(), sequence); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param region a region describing the new position (it is not * stored, only its values are used) * @param proposals the completion proposals to be shown when a position of * this type comes up * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument doc, IRegion region, ICompletionProposal[] proposals) throws BadLocationException { createPosition(doc, region, LinkedPositionGroup.NO_STOP, proposals); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param offset the offset of the position * @param length the length of the position * @param proposals the completion proposals to be shown when a position of * this type comes up * @param sequence the tab stop number of the position * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument doc, int offset, int length, int sequence, ICompletionProposal[] proposals) throws BadLocationException { addPosition(new ProposalPosition(doc, offset, length, sequence, proposals)); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param offset the offset of the position * @param length the length of the position * @param proposals the completion proposals to be shown when a position of * this type comes up * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument doc, int offset, int length, ICompletionProposal[] proposals) throws BadLocationException { createPosition(doc, offset, length, LinkedPositionGroup.NO_STOP, proposals); } /** * Adds a position to this group. If the position overlaps with another in * this group, or if the group is already part of an environment, an * exception is thrown. * * @param document the document of the position * @param region a region describing the new position (it is not * stored, only its values are used) * @param proposals the completion proposals to be shown when a position of * this type comes up * @param sequence the tab stop number of the position * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ public void createPosition(IDocument doc, IRegion region, int sequence, ICompletionProposal[] proposals) throws BadLocationException { createPosition(doc, region.getOffset(), region.getLength(), sequence, proposals); } /** * Not implemented yet. */ public void createPosition(IDocument doc, IRegion region, int sequence, IContentAssistProcessor processor) throws BadLocationException { // TODO add overloaded versions with some lazy computation interface throw new UnsupportedOperationException(); } /** * Implementation of all the <code>addPosition</code> methods. Enforces * constraints and sets the custom iteration flag. If the position is * already in this group, nothing happens. * * @param position the position to add * @throws BadLocationException if the position is invalid or conflicts * with other positions in the group * @throws IllegalStateException if the group has alreay been added to an * environment */ private void addPosition(LinkedPosition position) throws BadLocationException { Assert.isNotNull(position); // don't add positions after it is installed. if (fEnvironment != null) throw new IllegalStateException("cannot add positions after the group is added to an environment"); //$NON-NLS-1$ if (!fPositions.contains(position)) { enforceDisjoint(position); enforceEqualContent(position); fPositions.add(position); fHasCustomIteration |= position.getSequenceNumber() != LinkedPositionGroup.NO_STOP; } else return; // nothing happens } /** * Adds <code>position</code> to the document and ensures management of * its document by the environment. * * @param position the position to register * @throws BadLocationException if the position overlaps with an other, or * is illegal on the document */ private void register(LinkedPosition position) throws BadLocationException { Assert.isNotNull(fEnvironment); Assert.isNotNull(position); fEnvironment.register(position); } /** * Enforces the invariant that all positions must contain the same string. * * @param position the position to check * @throws BadLocationException if the equal content check fails */ private void enforceEqualContent(LinkedPosition position) throws BadLocationException { if (fPositions.size() > 0) { String groupContent= ((LinkedPosition) fPositions.get(0)).getContent(); String positionContent= position.getContent(); if (!groupContent.equals(positionContent)) throw new BadLocationException(); } } /** * Enforces the invariant that all positions must be disjoint. * * @param position the position to check * @throws BadLocationException if the disjointness check fails */ private void enforceDisjoint(LinkedPosition position) throws BadLocationException { for (Iterator it= fPositions.iterator(); it.hasNext(); ) { LinkedPosition p= (LinkedPosition) it.next(); if (p.overlapsWith(position)) throw new BadLocationException(); } } /** * Enforces the disjointness for another group * * @param group the group to check * @throws BadLocationException if the disjointness check fails */ void enforceDisjoint(LinkedPositionGroup group) throws BadLocationException { Assert.isNotNull(group); for (Iterator it= group.fPositions.iterator(); it.hasNext(); ) { LinkedPosition p= (LinkedPosition) it.next(); enforceDisjoint(p); } } /** * Checks whether <code>event</code> fits in any of the positions of this * group. * * @param event the document event to check * @return <code>true</code> if <code>event</code> fits in any position */ boolean isLegalEvent(DocumentEvent event) { for (Iterator it= fPositions.iterator(); it.hasNext(); ) { LinkedPosition pos= (LinkedPosition) it.next(); if (pos.includes(event)) { fLastPosition= pos; fLastPositionOffset= pos.getOffset(); return true; } } fLastPosition= null; fLastPositionOffset= -1; return false; } /** * Creates an edition of a document change that will forward any * modification in one position to all linked siblings. The return value is * a map from <code>IDocument</code> to <code>TextEdit</code>. * * @param event the document event to check * @return a map of edits, grouped by edited document */ Map handleEvent(DocumentEvent event) { if (fLastPosition != null) { Map map= new HashMap(); int relOffset= event.getOffset() - fLastPositionOffset; int length= event.getLength(); String text= event.getText(); for (Iterator it2= fPositions.iterator(); it2.hasNext(); ) { LinkedPosition p= (LinkedPosition) it2.next(); if (p == fLastPosition) continue; // don't re-update the origin of the change List edits= (List) map.get(p.getDocument()); if (edits == null) { edits= new ArrayList(); map.put(p.getDocument(), edits); } edits.add(new ReplaceEdit(p.getOffset() + relOffset, length, text)); } for (Iterator it2= map.keySet().iterator(); it2.hasNext(); ) { IDocument d= (IDocument) it2.next(); TextEdit edit= new MultiTextEdit(0, d.getLength()); edit.addChildren((TextEdit[]) ((List) map.get(d)).toArray(new TextEdit[0])); map.put(d, edit); } return map; } return null; } /** * Sets the environment of this group. Once an environment has been set, no * more positions can be added and the environment cannot be changed. * * @param environment the environment * @throws BadLocationException if registering any position with the * environment fails */ void setEnvironment(LinkedEnvironment environment) throws BadLocationException { Assert.isNotNull(environment); Assert.isTrue(fEnvironment == null); fEnvironment= environment; if (fHasCustomIteration == false && fPositions.size() > 0) { ((LinkedPosition) fPositions.get(0)).setSequenceNumber(0); } for (Iterator it= fPositions.iterator(); it.hasNext(); ) { LinkedPosition pos= (LinkedPosition) it.next(); register(pos); } } /** * Returns the position in this group that encompasses all positions in * <code>group</code>. * * @param group the group to be adopted * @return a position in the receiver that contains all positions in <code>group</code>, * or <code>null</code> if none can be found * @throws BadLocationException if more than one position are affected by * <code>group</code> */ LinkedPosition adopt(LinkedPositionGroup group) throws BadLocationException { LinkedPosition found= null; for (Iterator it= group.fPositions.iterator(); it.hasNext(); ) { LinkedPosition pos= (LinkedPosition) it.next(); LinkedPosition localFound= null; for (Iterator it2= fPositions.iterator(); it2.hasNext(); ) { LinkedPosition myPos= (LinkedPosition) it2.next(); if (myPos.includes(pos)) { if (found == null) found= myPos; else if (found != myPos) throw new BadLocationException(); if (localFound == null) localFound= myPos; } } if (localFound != found) throw new BadLocationException(); } return found; } /** * Finds the closest position to <code>toFind</code>. */ LinkedPosition getPosition(LinkedPosition toFind) { for (Iterator it= fPositions.iterator(); it.hasNext(); ) { LinkedPosition p= (LinkedPosition) it.next(); if (p.includes(toFind)) return p; } return null; } /** * Returns <code>true</code> if <code>offset</code> is contained in any * position in this group. * * @param offset the offset to check * @return <code>true</code> if offset is contained by this group */ boolean contains(int offset) { for (Iterator it= fPositions.iterator(); it.hasNext(); ) { LinkedPosition pos= (LinkedPosition) it.next(); if (pos.includes(offset)) { return true; } } return false; } /** * Returns whether this group contains any positions. * * @return <code>true</code> if this group is empty, <code>false</code> if it is not */ public boolean isEmtpy() { return fPositions.size() == 0; } /** * Returns the positions contained in the receiver as an array. The * positions are the actual positions and may not be modified; the array * is a copy of internal structures. * * @return the positions of this group in no particular order */ LinkedPosition[] getPositions() { return (LinkedPosition[]) fPositions.toArray(new LinkedPosition[0]); } /** * Returns <code>true</code> if the receiver contains <code>position</code>. * * @param position the position to check * @return <code>true</code> if the receiver contains <code>position</code> */ boolean contains(LinkedPosition position) { for (Iterator it= fPositions.iterator(); it.hasNext(); ) { LinkedPosition p= (LinkedPosition) it.next(); if (position.equals(p)) return true; } return false; } }
48,122
Bug 48122 NPE in LinkedNamesAssistProposal
I20031203 Sorry, no steps to reproduce but I found several instances of the following in my log: java.lang.NullPointerException at org.eclipse.jdt.internal.ui.text.correction.LinkedNamesAssistProposal.getSelection(LinkedNamesAssistProposal.java:124) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal(CompletionProposalPopup.java:375) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposalWithMask(CompletionProposalPopup.java:336) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.verifyKey(CompletionProposalPopup.java:635) at org.eclipse.jface.text.contentassist.ContentAssistant$InternalListener.verifyKey(ContentAssistant.java:603) at org.eclipse.jface.text.TextViewer$VerifyKeyListenersManager.verifyKey(TextViewer.java:371) at org.eclipse.swt.custom.StyledTextListener.handleEvent(StyledTextListener.java:55) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:846) at org.eclipse.swt.custom.StyledText.handleKeyDown(StyledText.java:5321) at org.eclipse.swt.custom.StyledText$8.handleEvent(StyledText.java:5070) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:967) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:991) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:976) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:2237) at org.eclipse.swt.widgets.Control.gtk_key_press_event(Control.java:1750) at org.eclipse.swt.widgets.Widget.windowProc(Widget.java:1228) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2317) at org.eclipse.swt.internal.gtk.OS.gtk_main_do_event(Native Method) at org.eclipse.swt.widgets.Display.eventProc(Display.java:710) at org.eclipse.swt.internal.gtk.OS.gtk_main_iteration(Native Method) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1618) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1486) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1462) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.applicationrunner.ApplicationRunnerActivator$1.run(ApplicationRunnerActivator.java:85) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:87) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601)
resolved fixed
d78140b
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T16:28:14Z
2003-12-04T23:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/template/TemplateProposal.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.template; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPositionCategoryException; import org.eclipse.jface.text.DefaultPositionUpdater; import org.eclipse.jface.text.DocumentEvent; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IInformationControlCreator; import org.eclipse.jface.text.IPositionUpdater; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension2; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension3; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.TemplateBuffer; import org.eclipse.jdt.internal.corext.template.TemplateContext; import org.eclipse.jdt.internal.corext.template.TemplateMessages; import org.eclipse.jdt.internal.corext.template.TemplatePosition; import org.eclipse.jdt.internal.corext.template.java.GlobalVariables; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.link.LinkedEnvironment; import org.eclipse.jdt.internal.ui.text.link.LinkedPositionGroup; import org.eclipse.jdt.internal.ui.text.link.LinkedUIControl; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * A template proposal. */ public class TemplateProposal implements IJavaCompletionProposal, ICompletionProposalExtension2, ICompletionProposalExtension3 { private final Template fTemplate; private final TemplateContext fContext; private final Image fImage; private final IRegion fRegion; private int fRelevance; private IRegion fSelectedRegion; // initialized by apply() private String fDisplayString; /** * Creates a template proposal with a template and its context. * @param template the template * @param context the context in which the template was requested. * @param image the icon of the proposal. */ public TemplateProposal(Template template, TemplateContext context, IRegion region, Image image) { Assert.isNotNull(template); Assert.isNotNull(context); Assert.isNotNull(region); fTemplate= template; fContext= context; fImage= image; fRegion= region; fDisplayString= null; if (context instanceof JavaContext) { switch (((JavaContext) context).getCharacterBeforeStart()) { // high relevance after whitespace case ' ': case '\r': case '\n': case '\t': fRelevance= 90; break; default: fRelevance= 0; } } else { fRelevance= 90; } } /* * @see ICompletionProposal#apply(IDocument) */ public final void apply(IDocument document) { // not called anymore } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#apply(org.eclipse.jface.text.ITextViewer, char, int, int) */ public void apply(ITextViewer viewer, char trigger, int stateMask, int offset) { try { IDocument document= viewer.getDocument(); Position position= new Position(fRegion.getOffset(), fRegion.getLength()); final String category= "__template_position_" + System.currentTimeMillis(); //$NON-NLS-1$ IPositionUpdater updater= new DefaultPositionUpdater(category); document.addPositionCategory(category); document.addPositionUpdater(updater); document.addPosition(position); fContext.setReadOnly(false); TemplateBuffer templateBuffer= fContext.evaluate(fTemplate); if (templateBuffer == null) { fSelectedRegion= fRegion; return; } document.removePosition(position); document.removePositionUpdater(updater); document.removePositionCategory(category); int start= position.getOffset(); int end= position.getOffset() + position.getLength(); // insert template string String templateString= templateBuffer.getString(); document.replace(start, end - start, templateString); // translate positions LinkedEnvironment env= LinkedEnvironment.createLinkedEnvironment(document); TemplatePosition[] variables= templateBuffer.getVariables(); boolean hasPositions= false; for (int i= 0; i != variables.length; i++) { TemplatePosition variable= variables[i]; if (variable.isResolved()) continue; LinkedPositionGroup group= new LinkedPositionGroup(); int[] offsets= variable.getOffsets(); int length= variable.getLength(); for (int j= 0; j != offsets.length; j++) group.createPosition(document, offsets[j] + start, length); env.addGroup(group); hasPositions= true; } if (hasPositions) { LinkedUIControl editor= new LinkedUIControl(env, viewer); editor.setExitPosition(viewer, getCaretOffset(templateBuffer) + start, 0, true); editor.enter(); fSelectedRegion= editor.getSelectedRegion(); } else fSelectedRegion= new Region(getCaretOffset(templateBuffer) + start, 0); } catch (BadLocationException e) { JavaPlugin.log(e); openErrorDialog(viewer.getTextWidget().getShell(), e); fSelectedRegion= fRegion; } catch (BadPositionCategoryException e) { JavaPlugin.log(e); openErrorDialog(viewer.getTextWidget().getShell(), e); fSelectedRegion= fRegion; } catch (CoreException e) { handleException(viewer.getTextWidget().getShell(), e); fSelectedRegion= fRegion; } } private int getCaretOffset(TemplateBuffer buffer) { TemplatePosition[] variables= buffer.getVariables(); for (int i= 0; i != variables.length; i++) { TemplatePosition variable= variables[i]; if (variable.getName().equals(GlobalVariables.Cursor.NAME)) return variable.getOffsets()[0]; } return buffer.getString().length(); } /* * @see ICompletionProposal#getSelection(IDocument) */ public Point getSelection(IDocument document) { return new Point(fSelectedRegion.getOffset(), fSelectedRegion.getLength()); } /* * @see ICompletionProposal#getAdditionalProposalInfo() */ public String getAdditionalProposalInfo() { try { fContext.setReadOnly(true); TemplateBuffer templateBuffer= fContext.evaluate(fTemplate); if (templateBuffer == null) return null; return templateBuffer.getString(); } catch (CoreException e) { handleException(JavaPlugin.getActiveWorkbenchShell(), e); return null; } } /* * @see ICompletionProposal#getDisplayString() */ public String getDisplayString() { if (fDisplayString == null) { fDisplayString= fTemplate.getName() + TemplateMessages.getString("TemplateProposal.delimiter") + fTemplate.getDescription(); //$NON-NLS-1$ } return fDisplayString; } public void setDisplayString(String displayString) { fDisplayString= displayString; } /* * @see ICompletionProposal#getImage() */ public Image getImage() { return fImage; } /* * @see ICompletionProposal#getContextInformation() */ public IContextInformation getContextInformation() { return null; } private void openErrorDialog(Shell shell, Exception e) { MessageDialog.openError(shell, TemplateMessages.getString("TemplateEvaluator.error.title"), e.getMessage()); //$NON-NLS-1$ } private void handleException(Shell shell, CoreException e) { ExceptionHandler.handle(e, shell, TemplateMessages.getString("TemplateEvaluator.error.title"), null); //$NON-NLS-1$ } /* * @see IJavaCompletionProposal#getRelevance() */ public int getRelevance() { return fRelevance; } public void setRelevance(int relevance) { fRelevance= relevance; } public Template getTemplate() { return fTemplate; } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension3#getInformationControlCreator() */ public IInformationControlCreator getInformationControlCreator() { return new TemplateInformationControlCreator(); } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#selected(org.eclipse.jface.text.ITextViewer, boolean) */ public void selected(ITextViewer viewer, boolean smartToggle) { } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#unselected(org.eclipse.jface.text.ITextViewer) */ public void unselected(ITextViewer viewer) { } /* * @see org.eclipse.jface.text.contentassist.ICompletionProposalExtension2#validate(org.eclipse.jface.text.IDocument, int, org.eclipse.jface.text.DocumentEvent) */ public boolean validate(IDocument document, int offset, DocumentEvent event) { return false; } }
44,737
Bug 44737 JavaElementLabels broken for nested anonymous types
null
resolved fixed
2482cbe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:12:30Z
2003-10-13T10:13:20Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/CoreTests.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.tests.core; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** */ public class CoreTests extends TestCase { public static Test suite() { TestSuite suite= new TestSuite(); suite.addTest(AddImportTest.allTests()); suite.addTest(AddUnimplementedMethodsTest.allTests()); suite.addTest(AddUnimplementedConstructorsTest.allTests()); suite.addTest(AllTypesCacheTest.allTests()); suite.addTest(BindingsNameTest.allTests()); suite.addTest(ClassPathDetectorTest.allTests()); suite.addTest(HierarchicalASTVisitorTest.allTests()); suite.addTest(ImportOrganizeTest.allTests()); suite.addTest(JavaModelUtilTest.allTests()); suite.addTest(NameProposerTest.allTests()); suite.addTest(TextEditTests.allTests()); suite.addTest(PrimaryWorkingCopyTest.allTests()); suite.addTest(TypeInfoTest.allTests()); suite.addTest(CallHierarchyTest.allTests()); suite.addTest(ScopeAnalyzerTest.allTests()); suite.addTest(PartialASTTest.allTests()); suite.addTest(CodeCompletionTest.allTests()); suite.addTest(TypeRulesTest.allTests()); return new ProjectTestSetup(suite); } public CoreTests(String name) { super(name); } private static final int printRange= 6; private static int getDiffPos(String str1, String str2) { int len1= Math.min(str1.length(), str2.length()); int diffPos= -1; for (int i= 0; i < len1; i++) { if (str1.charAt(i) != str2.charAt(i)) { diffPos= i; break; } } if (diffPos == -1 && str1.length() != str2.length()) { diffPos= len1; } return diffPos; } public static void assertEqualString(String current, String expected) { if (current == null || expected == null) { if (current == expected) { return; } if (current == null) { assertTrue("Content not as expected: is 'null' expected: " + expected, false); } else { assertTrue("Content not as expected: expected 'null' is: " + current, false); } } int diffPos= getDiffPos(current, expected); if (diffPos != -1) { int diffAhead= Math.max(0, diffPos - printRange); int diffAfter= Math.min(current.length(), diffPos + printRange); String diffStr= current.substring(diffAhead, diffPos) + '^' + current.substring(diffPos, diffAfter); assertTrue("Content not as expected: is\n" + current + "\nDiffers at pos " + diffPos + ": " + diffStr + "\nexpected:\n" + expected, false); } } public static void assertEqualStringIgnoreDelim(String str1, String str2) throws IOException { BufferedReader read1= new BufferedReader(new StringReader(str1)); BufferedReader read2= new BufferedReader(new StringReader(str2)); int line= 1; do { String s1= read1.readLine(); String s2= read2.readLine(); if (s1 == null || !s1.equals(s2)) { if (s1 == null && s2 == null) { return; } String diffStr= (s1 == null) ? s2 : s1; assertTrue("Content not as expected: is\n" + str1 + "\nDiffers at line " + line + ": " + diffStr + "\nexpected:\n" + str2, false); } line++; } while (true); } public static void assertEqualStringsIgnoreOrder(String[] str1, String[] str2) { ArrayList list1= new ArrayList(Arrays.asList(str1)); ArrayList list2= new ArrayList(Arrays.asList(str2)); for (int i= list1.size() - 1; i >= 0; i--) { if (list2.remove(list1.get(i))) { list1.remove(i); } } int n1= list1.size(); int n2= list2.size(); if (n1 + n2 > 0) { if (n1 == 1 && n2 == 1) { assertEqualString((String) list1.get(0), (String) list2.get(0)); } StringBuffer buf= new StringBuffer(); buf.append("Content not as expected: Content is: \n"); for (int i= 0; i < n1; i++) { String s1= (String) list1.get(i); if (s1 != null) { buf.append(s1); buf.append("\n"); } } buf.append("Expected contents: \n"); for (int i= 0; i < n2; i++) { String s2= (String) list2.get(i); if (s2 != null) { buf.append(s2); buf.append("\n"); } } assertTrue(buf.toString(), false); } } public static void assertNumberOf(String name, int is, int expected) { assertTrue("Wrong number of " + name + ", is: " + is + ", expected: " + expected, is == expected); } }
44,737
Bug 44737 JavaElementLabels broken for nested anonymous types
null
resolved fixed
2482cbe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:12:30Z
2003-10-13T10:13:20Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/core/JavaElementLabelsTest.java
44,737
Bug 44737 JavaElementLabels broken for nested anonymous types
null
resolved fixed
2482cbe
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:12:30Z
2003-10-13T10:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementLabels.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.viewsupport; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.ILocalVariable; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; public class JavaElementLabels { /** * Method names contain parameter types. * e.g. <code>foo(int)</code> */ public final static int M_PARAMETER_TYPES= 1 << 0; /** * Method names contain parameter names. * e.g. <code>foo(index)</code> */ public final static int M_PARAMETER_NAMES= 1 << 1; /** * Method names contain thrown exceptions. * e.g. <code>foo throws IOException</code> */ public final static int M_EXCEPTIONS= 1 << 2; /** * Method names contain return type (appended) * e.g. <code>foo : int</code> */ public final static int M_APP_RETURNTYPE= 1 << 3; /** * Method names contain return type (appended) * e.g. <code>int foo</code> */ public final static int M_PRE_RETURNTYPE= 1 << 4; /** * Method names are fully qualified. * e.g. <code>java.util.Vector.size</code> */ public final static int M_FULLY_QUALIFIED= 1 << 5; /** * Method names are post qualified. * e.g. <code>size - java.util.Vector</code> */ public final static int M_POST_QUALIFIED= 1 << 6; /** * Initializer names are fully qualified. * e.g. <code>java.util.Vector.{ ... }</code> */ public final static int I_FULLY_QUALIFIED= 1 << 7; /** * Type names are post qualified. * e.g. <code>{ ... } - java.util.Map</code> */ public final static int I_POST_QUALIFIED= 1 << 8; /** * Field names contain the declared type (appended) * e.g. <code>fHello : int</code> */ public final static int F_APP_TYPE_SIGNATURE= 1 << 9; /** * Field names contain the declared type (prepended) * e.g. <code>int fHello</code> */ public final static int F_PRE_TYPE_SIGNATURE= 1 << 10; /** * Fields names are fully qualified. * e.g. <code>java.lang.System.out</code> */ public final static int F_FULLY_QUALIFIED= 1 << 11; /** * Fields names are post qualified. * e.g. <code>out - java.lang.System</code> */ public final static int F_POST_QUALIFIED= 1 << 12; /** * Type names are fully qualified. * e.g. <code>java.util.Map.MapEntry</code> */ public final static int T_FULLY_QUALIFIED= 1 << 13; /** * Type names are type container qualified. * e.g. <code>Map.MapEntry</code> */ public final static int T_CONTAINER_QUALIFIED= 1 << 14; /** * Type names are post qualified. * e.g. <code>MapEntry - java.util.Map</code> */ public final static int T_POST_QUALIFIED= 1 << 15; /** * Declarations (import container / declarartion, package declarartion) are qualified. * e.g. <code>java.util.Vector.class/import container</code> */ public final static int D_QUALIFIED= 1 << 16; /** * Declarations (import container / declarartion, package declarartion) are post qualified. * e.g. <code>import container - java.util.Vector.class</code> */ public final static int D_POST_QUALIFIED= 1 << 17; /** * Class file names are fully qualified. * e.g. <code>java.util.Vector.class</code> */ public final static int CF_QUALIFIED= 1 << 18; /** * Class file names are post qualified. * e.g. <code>Vector.class - java.util</code> */ public final static int CF_POST_QUALIFIED= 1 << 19; /** * Compilation unit names are fully qualified. * e.g. <code>java.util.Vector.java</code> */ public final static int CU_QUALIFIED= 1 << 20; /** * Compilation unit names are post qualified. * e.g. <code>Vector.java - java.util</code> */ public final static int CU_POST_QUALIFIED= 1 << 21; /** * Package names are qualified. * e.g. <code>MyProject/src/java.util</code> */ public final static int P_QUALIFIED= 1 << 22; /** * Package names are post qualified. * e.g. <code>java.util - MyProject/src</code> */ public final static int P_POST_QUALIFIED= 1 << 23; /** * Package Fragment Roots contain variable name if from a variable. * e.g. <code>JRE_LIB - c:\java\lib\rt.jar</code> */ public final static int ROOT_VARIABLE= 1 << 24; /** * Package Fragment Roots contain the project name if not an archive (prepended). * e.g. <code>MyProject/src</code> */ public final static int ROOT_QUALIFIED= 1 << 25; /** * Package Fragment Roots contain the project name if not an archive (appended). * e.g. <code>src - MyProject</code> */ public final static int ROOT_POST_QUALIFIED= 1 << 26; /** * Add root path to all elements except Package Fragment Roots and Java projects. * e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code> * Option only applies to getElementLabel */ public final static int APPEND_ROOT_PATH= 1 << 27; /** * Add root path to all elements except Package Fragment Roots and Java projects. * e.g. <code>java.lang.Vector - c:\java\lib\rt.jar</code> * Option only applies to getElementLabel */ public final static int PREPEND_ROOT_PATH= 1 << 28; /** * Package names are compressed. * e.g. <code>o*.e*.search</code> */ public final static int P_COMPRESSED= 1 << 29; /** * Post qualify referenced package fragement roots. For example * <code>jdt.jar - org.eclipse.jdt.ui</code> if the jar is referenced * from another project. */ public final static int REFERENCED_ROOT_POST_QUALIFIED= 1 << 30; /** * Qualify all elements */ public final static int ALL_FULLY_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED | P_QUALIFIED | ROOT_QUALIFIED; /** * Post qualify all elements */ public final static int ALL_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED | P_POST_QUALIFIED | ROOT_POST_QUALIFIED; /** * Default options (M_PARAMETER_TYPES enabled) */ public final static int ALL_DEFAULT= M_PARAMETER_TYPES; /** * Default qualify options (All except Root and Package) */ public final static int DEFAULT_QUALIFIED= F_FULLY_QUALIFIED | M_FULLY_QUALIFIED | I_FULLY_QUALIFIED | T_FULLY_QUALIFIED | D_QUALIFIED | CF_QUALIFIED | CU_QUALIFIED; /** * Default post qualify options (All except Root and Package) */ public final static int DEFAULT_POST_QUALIFIED= F_POST_QUALIFIED | M_POST_QUALIFIED | I_POST_QUALIFIED | T_POST_QUALIFIED | D_POST_QUALIFIED | CF_POST_QUALIFIED | CU_POST_QUALIFIED; public final static String CONCAT_STRING= JavaUIMessages.getString("JavaElementLabels.concat_string"); // " - "; //$NON-NLS-1$ public final static String COMMA_STRING= JavaUIMessages.getString("JavaElementLabels.comma_string"); // ", "; //$NON-NLS-1$ public final static String DECL_STRING= JavaUIMessages.getString("JavaElementLabels.declseparator_string"); // " "; // use for return type //$NON-NLS-1$ public final static String DEFAULT_PACKAGE= JavaUIMessages.getString("JavaElementLabels.default_package"); // "(default package)" //$NON-NLS-1$ /* * Package name compression */ private static String fgPkgNamePattern= ""; //$NON-NLS-1$ private static String fgPkgNamePrefix; private static String fgPkgNamePostfix; private static int fgPkgNameChars; private static int fgPkgNameLength= -1; private JavaElementLabels() { } private static boolean getFlag(int flags, int flag) { return (flags & flag) != 0; } public static String getTextLabel(Object obj, int flags) { if (obj instanceof IJavaElement) { return getElementLabel((IJavaElement) obj, flags); } else if (obj instanceof IAdaptable) { IWorkbenchAdapter wbadapter= (IWorkbenchAdapter) ((IAdaptable)obj).getAdapter(IWorkbenchAdapter.class); if (wbadapter != null) { return wbadapter.getLabel(obj); } } return ""; //$NON-NLS-1$ } /** * Returns the label for a Java element. Flags as defined above. */ public static String getElementLabel(IJavaElement element, int flags) { StringBuffer buf= new StringBuffer(60); getElementLabel(element, flags, buf); return buf.toString(); } /** * Returns the label for a Java element. Flags as defined above. */ public static void getElementLabel(IJavaElement element, int flags, StringBuffer buf) { int type= element.getElementType(); IPackageFragmentRoot root= null; if (type != IJavaElement.JAVA_MODEL && type != IJavaElement.JAVA_PROJECT && type != IJavaElement.PACKAGE_FRAGMENT_ROOT) root= JavaModelUtil.getPackageFragmentRoot(element); if (root != null && getFlag(flags, PREPEND_ROOT_PATH)) { getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf); buf.append(CONCAT_STRING); } switch (type) { case IJavaElement.METHOD: getMethodLabel((IMethod) element, flags, buf); break; case IJavaElement.FIELD: getFieldLabel((IField) element, flags, buf); break; case IJavaElement.LOCAL_VARIABLE: getLocalVariableLabel((ILocalVariable) element, flags, buf); break; case IJavaElement.INITIALIZER: getInitializerLabel((IInitializer) element, flags, buf); break; case IJavaElement.TYPE: getTypeLabel((IType) element, flags, buf); break; case IJavaElement.CLASS_FILE: getClassFileLabel((IClassFile) element, flags, buf); break; case IJavaElement.COMPILATION_UNIT: getCompilationUnitLabel((ICompilationUnit) element, flags, buf); break; case IJavaElement.PACKAGE_FRAGMENT: getPackageFragmentLabel((IPackageFragment) element, flags, buf); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: getPackageFragmentRootLabel((IPackageFragmentRoot) element, flags, buf); break; case IJavaElement.IMPORT_CONTAINER: case IJavaElement.IMPORT_DECLARATION: case IJavaElement.PACKAGE_DECLARATION: getDeclararionLabel(element, flags, buf); break; case IJavaElement.JAVA_PROJECT: case IJavaElement.JAVA_MODEL: buf.append(element.getElementName()); break; default: buf.append(element.getElementName()); } if (root != null && getFlag(flags, APPEND_ROOT_PATH)) { buf.append(CONCAT_STRING); getPackageFragmentRootLabel(root, ROOT_QUALIFIED, buf); } } /** * Appends the label for a method to a StringBuffer. Considers the M_* flags. */ public static void getMethodLabel(IMethod method, int flags, StringBuffer buf) { try { // return type if (getFlag(flags, M_PRE_RETURNTYPE) && method.exists() && !method.isConstructor()) { buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType()))); buf.append(' '); } // qualification if (getFlag(flags, M_FULLY_QUALIFIED)) { getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); buf.append('.'); } buf.append(method.getElementName()); // parameters if (getFlag(flags, M_PARAMETER_TYPES | M_PARAMETER_NAMES)) { buf.append('('); String[] types= getFlag(flags, M_PARAMETER_TYPES) ? method.getParameterTypes() : null; String[] names= (getFlag(flags, M_PARAMETER_NAMES) && method.exists()) ? method.getParameterNames() : null; int nParams= types != null ? types.length : names.length; for (int i= 0; i < nParams; i++) { if (i > 0) { buf.append(COMMA_STRING); //$NON-NLS-1$ } if (types != null) { buf.append(Signature.getSimpleName(Signature.toString(types[i]))); } if (names != null) { if (types != null) { buf.append(' '); } buf.append(names[i]); } } buf.append(')'); } if (getFlag(flags, M_EXCEPTIONS) && method.exists()) { String[] types= method.getExceptionTypes(); if (types.length > 0) { buf.append(" throws "); //$NON-NLS-1$ for (int i= 0; i < types.length; i++) { if (i > 0) { buf.append(COMMA_STRING); } buf.append(Signature.getSimpleName(Signature.toString(types[i]))); } } } if (getFlag(flags, M_APP_RETURNTYPE) && method.exists() && !method.isConstructor()) { buf.append(DECL_STRING); buf.append(Signature.getSimpleName(Signature.toString(method.getReturnType()))); } // post qualification if (getFlag(flags, M_POST_QUALIFIED)) { buf.append(CONCAT_STRING); getTypeLabel(method.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); } } catch (JavaModelException e) { JavaPlugin.log(e); // NotExistsException will not reach this point } } /** * Appends the label for a field to a StringBuffer. Considers the F_* flags. */ public static void getFieldLabel(IField field, int flags, StringBuffer buf) { try { if (getFlag(flags, F_PRE_TYPE_SIGNATURE) && field.exists()) { buf.append(Signature.toString(field.getTypeSignature())); buf.append(' '); } // qualification if (getFlag(flags, F_FULLY_QUALIFIED)) { getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); buf.append('.'); } buf.append(field.getElementName()); if (getFlag(flags, F_APP_TYPE_SIGNATURE) && field.exists()) { buf.append(DECL_STRING); buf.append(Signature.toString(field.getTypeSignature())); } // post qualification if (getFlag(flags, F_POST_QUALIFIED)) { buf.append(CONCAT_STRING); getTypeLabel(field.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); } } catch (JavaModelException e) { JavaPlugin.log(e); // NotExistsException will not reach this point } } /** * Appends the label for a local variable to a StringBuffer. * * @since 3.0 */ public static void getLocalVariableLabel(ILocalVariable localVariable, int flags, StringBuffer buf) { buf.append(Signature.toString(localVariable.getTypeSignature())); buf.append(' '); buf.append(localVariable.getElementName()); buf.append(CONCAT_STRING); getElementLabel(localVariable.getParent(), M_PARAMETER_TYPES | M_FULLY_QUALIFIED | T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); } /** * Appends the label for a initializer to a StringBuffer. Considers the I_* flags. */ public static void getInitializerLabel(IInitializer initializer, int flags, StringBuffer buf) { // qualification if (getFlag(flags, I_FULLY_QUALIFIED)) { getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); buf.append('.'); } buf.append(JavaUIMessages.getString("JavaElementLabels.initializer")); //$NON-NLS-1$ // post qualification if (getFlag(flags, I_POST_QUALIFIED)) { buf.append(CONCAT_STRING); getTypeLabel(initializer.getDeclaringType(), T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); } } /** * Appends the label for a type to a StringBuffer. Considers the T_* flags. */ public static void getTypeLabel(IType type, int flags, StringBuffer buf) { if (getFlag(flags, T_FULLY_QUALIFIED)) { IPackageFragment pack= type.getPackageFragment(); if (!pack.isDefaultPackage()) { getPackageFragmentLabel(pack, (flags & P_COMPRESSED), buf); buf.append('.'); } IType declaringType= type.getDeclaringType(); if (declaringType != null) { buf.append(JavaModelUtil.getTypeQualifiedName(declaringType)); buf.append('.'); } } else if (getFlag(flags, T_CONTAINER_QUALIFIED)) { IType declaringType= type.getDeclaringType(); if (declaringType != null) { buf.append(JavaModelUtil.getTypeQualifiedName(declaringType)); buf.append('.'); } } String typeName= type.getElementName(); if (typeName.length() == 0) { // anonymous try { String superclassName= Signature.getSimpleName(type.getSuperclassName()); typeName= JavaUIMessages.getFormattedString("JavaElementLabels.anonym_type" , superclassName); //$NON-NLS-1$ } catch (JavaModelException e) { //ignore typeName= JavaUIMessages.getString("JavaElementLabels.anonym"); //$NON-NLS-1$ } } buf.append(typeName); // post qualification if (getFlag(flags, T_POST_QUALIFIED)) { buf.append(CONCAT_STRING); IType declaringType= type.getDeclaringType(); if (declaringType != null) { getTypeLabel(declaringType, T_FULLY_QUALIFIED | (flags & P_COMPRESSED), buf); } else { getPackageFragmentLabel(type.getPackageFragment(), (flags & P_COMPRESSED), buf); } } } /** * Appends the label for a declaration to a StringBuffer. Considers the D_* flags. */ public static void getDeclararionLabel(IJavaElement declaration, int flags, StringBuffer buf) { if (getFlag(flags, D_QUALIFIED)) { IJavaElement openable= (IJavaElement) declaration.getOpenable(); if (openable != null) { buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED)); buf.append('/'); } } if (declaration.getElementType() == IJavaElement.IMPORT_CONTAINER) { buf.append(JavaUIMessages.getString("JavaElementLabels.import_container")); //$NON-NLS-1$ } else { buf.append(declaration.getElementName()); } // post qualification if (getFlag(flags, D_POST_QUALIFIED)) { IJavaElement openable= (IJavaElement) declaration.getOpenable(); if (openable != null) { buf.append(CONCAT_STRING); buf.append(getElementLabel(openable, CF_QUALIFIED | CU_QUALIFIED)); } } } /** * Appends the label for a class file to a StringBuffer. Considers the CF_* flags. */ public static void getClassFileLabel(IClassFile classFile, int flags, StringBuffer buf) { if (getFlag(flags, CF_QUALIFIED)) { IPackageFragment pack= (IPackageFragment) classFile.getParent(); if (!pack.isDefaultPackage()) { buf.append(pack.getElementName()); buf.append('.'); } } buf.append(classFile.getElementName()); if (getFlag(flags, CF_POST_QUALIFIED)) { buf.append(CONCAT_STRING); getPackageFragmentLabel((IPackageFragment) classFile.getParent(), 0, buf); } } /** * Appends the label for a compilation unit to a StringBuffer. Considers the CU_* flags. */ public static void getCompilationUnitLabel(ICompilationUnit cu, int flags, StringBuffer buf) { if (getFlag(flags, CU_QUALIFIED)) { IPackageFragment pack= (IPackageFragment) cu.getParent(); if (!pack.isDefaultPackage()) { buf.append(pack.getElementName()); buf.append('.'); } } buf.append(cu.getElementName()); if (getFlag(flags, CU_POST_QUALIFIED)) { buf.append(CONCAT_STRING); getPackageFragmentLabel((IPackageFragment) cu.getParent(), 0, buf); } } /** * Appends the label for a package fragment to a StringBuffer. Considers the P_* flags. */ public static void getPackageFragmentLabel(IPackageFragment pack, int flags, StringBuffer buf) { if (getFlag(flags, P_QUALIFIED)) { getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf); buf.append('/'); } refreshPackageNamePattern(); if (pack.isDefaultPackage()) { buf.append(DEFAULT_PACKAGE); } else if (getFlag(flags, P_COMPRESSED) && fgPkgNameLength >= 0) { String name= pack.getElementName(); int start= 0; int dot= name.indexOf('.', start); while (dot > 0) { if (dot - start > fgPkgNameLength-1) { buf.append(fgPkgNamePrefix); if (fgPkgNameChars > 0) buf.append(name.substring(start, Math.min(start+ fgPkgNameChars, dot))); buf.append(fgPkgNamePostfix); } else buf.append(name.substring(start, dot + 1)); start= dot + 1; dot= name.indexOf('.', start); } buf.append(name.substring(start)); } else { buf.append(pack.getElementName()); } if (getFlag(flags, P_POST_QUALIFIED)) { buf.append(CONCAT_STRING); getPackageFragmentRootLabel((IPackageFragmentRoot) pack.getParent(), ROOT_QUALIFIED, buf); } } /** * Appends the label for a package fragment root to a StringBuffer. Considers the ROOT_* flags. */ public static void getPackageFragmentRootLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { if (root.isArchive()) getArchiveLabel(root, flags, buf); else getFolderLabel(root, flags, buf); } private static void getArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { // Handle variables different if (getFlag(flags, ROOT_VARIABLE) && getVariableLabel(root, flags, buf)) return; boolean external= root.isExternal(); if (external) getExternalArchiveLabel(root, flags, buf); else getInternalArchiveLabel(root, flags, buf); } private static boolean getVariableLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { try { IClasspathEntry rawEntry= root.getRawClasspathEntry(); if (rawEntry != null) { if (rawEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { buf.append(rawEntry.getPath().makeRelative()); buf.append(CONCAT_STRING); if (root.isExternal()) buf.append(root.getPath().toOSString()); else buf.append(root.getPath().makeRelative().toString()); return true; } } } catch (JavaModelException e) { JavaPlugin.log(e); // problems with class path } return false; } private static void getExternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { IPath path= root.getPath(); if (getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED)) { int segements= path.segmentCount(); if (segements > 0) { buf.append(path.segment(segements - 1)); if (segements > 1 || path.getDevice() != null) { buf.append(CONCAT_STRING); buf.append(path.removeLastSegments(1).toOSString()); } } else { buf.append(path.toOSString()); } } else { buf.append(path.toOSString()); } } private static void getInternalArchiveLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { IResource resource= root.getResource(); boolean rootQualified= getFlag(flags, ROOT_QUALIFIED); boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null; if (rootQualified) { buf.append(root.getPath().makeRelative().toString()); } else { buf.append(root.getElementName()); if (referencedQualified) { buf.append(CONCAT_STRING); buf.append(resource.getParent().getFullPath().makeRelative().toString()); } else if (getFlag(flags, ROOT_POST_QUALIFIED)) { buf.append(CONCAT_STRING); buf.append(root.getParent().getPath().makeRelative().toString()); } } } private static void getFolderLabel(IPackageFragmentRoot root, int flags, StringBuffer buf) { IResource resource= root.getResource(); boolean rootQualified= getFlag(flags, ROOT_QUALIFIED); boolean referencedQualified= getFlag(flags, REFERENCED_ROOT_POST_QUALIFIED) && JavaModelUtil.isReferenced(root) && resource != null; if (rootQualified) { buf.append(root.getPath().makeRelative().toString()); } else { if (resource != null) buf.append(resource.getProjectRelativePath().toString()); else buf.append(root.getElementName()); if (referencedQualified) { buf.append(CONCAT_STRING); buf.append(resource.getProject().getName()); } else if (getFlag(flags, ROOT_POST_QUALIFIED)) { buf.append(CONCAT_STRING); buf.append(root.getParent().getElementName()); } } } private static void refreshPackageNamePattern() { String pattern= getPkgNamePatternForPackagesView(); if (pattern.equals(fgPkgNamePattern)) return; else if (pattern.equals("")) { //$NON-NLS-1$ fgPkgNamePattern= ""; //$NON-NLS-1$ fgPkgNameLength= -1; return; } fgPkgNamePattern= pattern; int i= 0; fgPkgNameChars= 0; fgPkgNamePrefix= ""; //$NON-NLS-1$ fgPkgNamePostfix= ""; //$NON-NLS-1$ while (i < pattern.length()) { char ch= pattern.charAt(i); if (Character.isDigit(ch)) { fgPkgNameChars= ch-48; if (i > 0) fgPkgNamePrefix= pattern.substring(0, i); if (i >= 0) fgPkgNamePostfix= pattern.substring(i+1); fgPkgNameLength= fgPkgNamePrefix.length() + fgPkgNameChars + fgPkgNamePostfix.length(); return; } i++; } fgPkgNamePrefix= pattern; fgPkgNameLength= pattern.length(); } private static String getPkgNamePatternForPackagesView() { IPreferenceStore store= PreferenceConstants.getPreferenceStore(); if (!store.getBoolean(PreferenceConstants.APPEARANCE_COMPRESS_PACKAGE_NAMES)) return ""; //$NON-NLS-1$ return store.getString(PreferenceConstants.APPEARANCE_PKG_NAME_PATTERN_FOR_PKG_VIEW); } }
44,834
Bug 44834 Extract interface refactoring operation does not create necessary import statement [refactoring]
In 3.0 M3 "Extract interface" refactoring does not create appropriate import statement for the newly created interface thus resulting in broken builds. In the refactoring dialog of Extract interface "Change references to the class X into the references to the interfaces" option has to be turned on in order to re-create this bug. To recreate: 1. Create a new java project. 2. Create two top packages a and b 3. Create A.java in package a and B.java in package b (see below). 4. Go to file B.java highlight "B" in the class declaration and invoke Refactor->Extract Interface 5. In the Refactoring dialog, type the "Interface name", for example - Test. Select "Change references to the class B into the references to the interfaces" option as well as interfaceMethod. Click Ok. This refactoring operation will change the reference of class B in A class to interface Test but will not import Test thus breaking the build. A.java ------------- package a; import b.B; public class A { private B b; public A(){} } B.java -------------------- package b; public class B { public B(){super();} public void interfaceMethod(){} }
resolved fixed
f30bd97
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:57:34Z
2003-10-14T16:46:40Z
org.eclipse.jdt.ui/core
44,834
Bug 44834 Extract interface refactoring operation does not create necessary import statement [refactoring]
In 3.0 M3 "Extract interface" refactoring does not create appropriate import statement for the newly created interface thus resulting in broken builds. In the refactoring dialog of Extract interface "Change references to the class X into the references to the interfaces" option has to be turned on in order to re-create this bug. To recreate: 1. Create a new java project. 2. Create two top packages a and b 3. Create A.java in package a and B.java in package b (see below). 4. Go to file B.java highlight "B" in the class declaration and invoke Refactor->Extract Interface 5. In the Refactoring dialog, type the "Interface name", for example - Test. Select "Change references to the class B into the references to the interfaces" option as well as interfaceMethod. Click Ok. This refactoring operation will change the reference of class B in A class to interface Test but will not import Test thus breaking the build. A.java ------------- package a; import b.B; public class A { private B b; public A(){} } B.java -------------------- package b; public class B { public B(){super();} public void interfaceMethod(){} }
resolved fixed
f30bd97
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:57:34Z
2003-10-14T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceRefactoring.java
44,834
Bug 44834 Extract interface refactoring operation does not create necessary import statement [refactoring]
In 3.0 M3 "Extract interface" refactoring does not create appropriate import statement for the newly created interface thus resulting in broken builds. In the refactoring dialog of Extract interface "Change references to the class X into the references to the interfaces" option has to be turned on in order to re-create this bug. To recreate: 1. Create a new java project. 2. Create two top packages a and b 3. Create A.java in package a and B.java in package b (see below). 4. Go to file B.java highlight "B" in the class declaration and invoke Refactor->Extract Interface 5. In the Refactoring dialog, type the "Interface name", for example - Test. Select "Change references to the class B into the references to the interfaces" option as well as interfaceMethod. Click Ok. This refactoring operation will change the reference of class B in A class to interface Test but will not import Test thus breaking the build. A.java ------------- package a; import b.B; public class A { private B b; public A(){} } B.java -------------------- package b; public class B { public B(){super();} public void interfaceMethod(){} }
resolved fixed
f30bd97
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:57:34Z
2003-10-14T16:46:40Z
org.eclipse.jdt.ui/core
44,834
Bug 44834 Extract interface refactoring operation does not create necessary import statement [refactoring]
In 3.0 M3 "Extract interface" refactoring does not create appropriate import statement for the newly created interface thus resulting in broken builds. In the refactoring dialog of Extract interface "Change references to the class X into the references to the interfaces" option has to be turned on in order to re-create this bug. To recreate: 1. Create a new java project. 2. Create two top packages a and b 3. Create A.java in package a and B.java in package b (see below). 4. Go to file B.java highlight "B" in the class declaration and invoke Refactor->Extract Interface 5. In the Refactoring dialog, type the "Interface name", for example - Test. Select "Change references to the class B into the references to the interfaces" option as well as interfaceMethod. Click Ok. This refactoring operation will change the reference of class B in A class to interface Test but will not import Test thus breaking the build. A.java ------------- package a; import b.B; public class A { private B b; public A(){} } B.java -------------------- package b; public class B { public B(){super();} public void interfaceMethod(){} }
resolved fixed
f30bd97
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:57:34Z
2003-10-14T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceUtil.java
44,834
Bug 44834 Extract interface refactoring operation does not create necessary import statement [refactoring]
In 3.0 M3 "Extract interface" refactoring does not create appropriate import statement for the newly created interface thus resulting in broken builds. In the refactoring dialog of Extract interface "Change references to the class X into the references to the interfaces" option has to be turned on in order to re-create this bug. To recreate: 1. Create a new java project. 2. Create two top packages a and b 3. Create A.java in package a and B.java in package b (see below). 4. Go to file B.java highlight "B" in the class declaration and invoke Refactor->Extract Interface 5. In the Refactoring dialog, type the "Interface name", for example - Test. Select "Change references to the class B into the references to the interfaces" option as well as interfaceMethod. Click Ok. This refactoring operation will change the reference of class B in A class to interface Test but will not import Test thus breaking the build. A.java ------------- package a; import b.B; public class A { private B b; public A(){} } B.java -------------------- package b; public class B { public B(){super();} public void interfaceMethod(){} }
resolved fixed
f30bd97
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:57:34Z
2003-10-14T16:46:40Z
org.eclipse.jdt.ui/core
44,834
Bug 44834 Extract interface refactoring operation does not create necessary import statement [refactoring]
In 3.0 M3 "Extract interface" refactoring does not create appropriate import statement for the newly created interface thus resulting in broken builds. In the refactoring dialog of Extract interface "Change references to the class X into the references to the interfaces" option has to be turned on in order to re-create this bug. To recreate: 1. Create a new java project. 2. Create two top packages a and b 3. Create A.java in package a and B.java in package b (see below). 4. Go to file B.java highlight "B" in the class declaration and invoke Refactor->Extract Interface 5. In the Refactoring dialog, type the "Interface name", for example - Test. Select "Change references to the class B into the references to the interfaces" option as well as interfaceMethod. Click Ok. This refactoring operation will change the reference of class B in A class to interface Test but will not import Test thus breaking the build. A.java ------------- package a; import b.B; public class A { private B b; public A(){} } B.java -------------------- package b; public class B { public B(){super();} public void interfaceMethod(){} }
resolved fixed
f30bd97
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-05T17:57:34Z
2003-10-14T16:46:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/UseSupertypeWherePossibleRefactoring.java
45,178
Bug 45178 Exception when closing rename dialog with read only files [refactoring]
if the resource is read-only you get a modal dialog "the selected elements contain read-only resources. Do you still want to move them ?" when pressing on close { upper right X ) you get java.lang.ArrayIndexOutOfBoundsException: -1 see attached log
resolved fixed
e283030
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-08T08:07:29Z
2003-10-19T21:46:40Z
org.eclipse.jdt.ui/ui
45,178
Bug 45178 Exception when closing rename dialog with read only files [refactoring]
if the resource is read-only you get a modal dialog "the selected elements contain read-only resources. Do you still want to move them ?" when pressing on close { upper right X ) you get java.lang.ArrayIndexOutOfBoundsException: -1 see attached log
resolved fixed
e283030
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-08T08:07:29Z
2003-10-19T21:46:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/ReorgQueries.java
46,658
Bug 46658 File search window too wide
20031111 - Select a element in the Java editor, press CTRL + H - Switch to the file tab - the search window is getting larger for no reasons (it takes the full screen width)
verified fixed
380dac5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-08T13:46:50Z
2003-11-14T11:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.DialogPage; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.text.ITextSelection; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.search.ui.ISearchPage; import org.eclipse.search.ui.ISearchPageContainer; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.search.ui.SearchUI; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.browsing.LogicalPackage; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.RowLayouter; public class JavaSearchPage extends DialogPage implements ISearchPage, IJavaSearchConstants { public static final String EXTENSION_POINT_ID= "org.eclipse.jdt.ui.JavaSearchPage"; //$NON-NLS-1$ // Dialog store id constants private final static String PAGE_NAME= "JavaSearchPage"; //$NON-NLS-1$ private final static String STORE_CASE_SENSITIVE= PAGE_NAME + "CASE_SENSITIVE"; //$NON-NLS-1$ private static List fgPreviousSearchPatterns= new ArrayList(20); private SearchPatternData fInitialData; private IStructuredSelection fStructuredSelection; private IJavaElement fJavaElement; private boolean fFirstTime= true; private IDialogSettings fDialogSettings; private boolean fIsCaseSensitive; private Combo fPattern; private ISearchPageContainer fContainer; private Button fCaseSensitive; private Button[] fSearchFor; private String[] fSearchForText= { SearchMessages.getString("SearchPage.searchFor.type"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.method"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.package"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.constructor"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.searchFor.field")}; //$NON-NLS-1$ private Button[] fLimitTo; private String[] fLimitToText= { SearchMessages.getString("SearchPage.limitTo.declarations"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.implementors"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.references"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.allOccurrences"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.readReferences"), //$NON-NLS-1$ SearchMessages.getString("SearchPage.limitTo.writeReferences")}; //$NON-NLS-1$ private static class SearchPatternData { int searchFor; int limitTo; String pattern; boolean isCaseSensitive; IJavaElement javaElement; int scope; IWorkingSet[] workingSets; public SearchPatternData(int s, int l, boolean i, String p, IJavaElement element) { this(s, l, p, i, element, ISearchPageContainer.WORKSPACE_SCOPE, null); } public SearchPatternData(int s, int l, String p, boolean i, IJavaElement element, int scope, IWorkingSet[] workingSets) { searchFor= s; limitTo= l; pattern= p; isCaseSensitive= i; javaElement= element; this.scope= scope; this.workingSets= workingSets; } } //---- Action Handling ------------------------------------------------ public boolean performAction() { SearchUI.activateSearchResultView(); SearchPatternData data= getPatternData(); IWorkspace workspace= JavaPlugin.getWorkspace(); // Setup search scope IJavaSearchScope scope= null; String scopeDescription= ""; //$NON-NLS-1$ switch (getContainer().getSelectedScope()) { case ISearchPageContainer.WORKSPACE_SCOPE: scopeDescription= SearchMessages.getString("WorkspaceScope"); //$NON-NLS-1$ scope= SearchEngine.createWorkspaceScope(); break; case ISearchPageContainer.SELECTION_SCOPE: scopeDescription= SearchMessages.getString("SelectionScope"); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(fStructuredSelection); break; case ISearchPageContainer.SELECTED_PROJECTS_SCOPE: scope= JavaSearchScopeFactory.getInstance().createJavaProjectSearchScope(fStructuredSelection); IProject[] projects= JavaSearchScopeFactory.getInstance().getJavaProjects(scope); if (projects.length > 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectsScope", projects[0].getName()); //$NON-NLS-1$ else if (projects.length == 1) scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", projects[0].getName()); //$NON-NLS-1$ else scopeDescription= SearchMessages.getFormattedString("EnclosingProjectScope", ""); //$NON-NLS-1$ //$NON-NLS-2$ break; case ISearchPageContainer.WORKING_SET_SCOPE: IWorkingSet[] workingSets= getContainer().getSelectedWorkingSets(); // should not happen - just to be sure if (workingSets == null || workingSets.length < 1) return false; scopeDescription= SearchMessages.getFormattedString("WorkingSetScope", SearchUtil.toString(workingSets)); //$NON-NLS-1$ scope= JavaSearchScopeFactory.getInstance().createJavaSearchScope(getContainer().getSelectedWorkingSets()); SearchUtil.updateLRUWorkingSets(getContainer().getSelectedWorkingSets()); } JavaSearchResultCollector collector= new JavaSearchResultCollector(); JavaSearchOperation op= null; if (data.javaElement != null && getPattern().equals(fInitialData.pattern)) { op= new JavaSearchOperation(workspace, data.javaElement, data.limitTo, scope, scopeDescription, collector); if (data.limitTo == IJavaSearchConstants.REFERENCES) SearchUtil.warnIfBinaryConstant(data.javaElement, getShell()); } else { data.javaElement= null; op= new JavaSearchOperation(workspace, data.pattern, data.isCaseSensitive, data.searchFor, data.limitTo, scope, scopeDescription, collector); } Shell shell= getControl().getShell(); try { getContainer().getRunnableContext().run(true, true, op); } catch (InvocationTargetException ex) { ExceptionHandler.handle(ex, shell, SearchMessages.getString("Search.Error.search.title"), SearchMessages.getString("Search.Error.search.message")); //$NON-NLS-2$ //$NON-NLS-1$ return false; } catch (InterruptedException ex) { return false; } return true; } private int getLimitTo() { for (int i= 0; i < fLimitTo.length; i++) { if (fLimitTo[i].getSelection()) return i; } return -1; } private void setLimitTo(int searchFor) { fLimitTo[DECLARATIONS].setEnabled(true); fLimitTo[IMPLEMENTORS].setEnabled(false); fLimitTo[REFERENCES].setEnabled(true); fLimitTo[ALL_OCCURRENCES].setEnabled(true); fLimitTo[READ_ACCESSES].setEnabled(false); fLimitTo[WRITE_ACCESSES].setEnabled(false); if (!(searchFor == TYPE || searchFor == INTERFACE) && fLimitTo[IMPLEMENTORS].getSelection()) { fLimitTo[IMPLEMENTORS].setSelection(false); fLimitTo[REFERENCES].setSelection(true); } if (!(searchFor == FIELD) && (getLimitTo() == READ_ACCESSES || getLimitTo() == WRITE_ACCESSES)) { fLimitTo[getLimitTo()].setSelection(false); fLimitTo[REFERENCES].setSelection(true); } switch (searchFor) { case TYPE: case INTERFACE: fLimitTo[IMPLEMENTORS].setEnabled(true); break; case FIELD: fLimitTo[READ_ACCESSES].setEnabled(true); fLimitTo[WRITE_ACCESSES].setEnabled(true); break; default : break; } } private String[] getPreviousSearchPatterns() { // Search results are not persistent int patternCount= fgPreviousSearchPatterns.size(); String [] patterns= new String[patternCount]; for (int i= 0; i < patternCount; i++) patterns[i]= ((SearchPatternData) fgPreviousSearchPatterns.get(patternCount - 1 - i)).pattern; return patterns; } private int getSearchFor() { for (int i= 0; i < fSearchFor.length; i++) { if (fSearchFor[i].getSelection()) return i; } Assert.isTrue(false, "shouldNeverHappen"); //$NON-NLS-1$ return -1; } private String getPattern() { return fPattern.getText(); } /** * Return search pattern data and update previous searches. * An existing entry will be updated. */ private SearchPatternData getPatternData() { String pattern= getPattern(); SearchPatternData match= null; int i= 0; int size= fgPreviousSearchPatterns.size(); while (match == null && i < size) { match= (SearchPatternData) fgPreviousSearchPatterns.get(i); i++; if (!pattern.equals(match.pattern)) match= null; } if (match == null) { match= new SearchPatternData( getSearchFor(), getLimitTo(), pattern, fCaseSensitive.getSelection(), fJavaElement, getContainer().getSelectedScope(), getContainer().getSelectedWorkingSets()); fgPreviousSearchPatterns.add(match); } else { match.searchFor= getSearchFor(); match.limitTo= getLimitTo(); match.isCaseSensitive= fCaseSensitive.getSelection(); match.javaElement= fJavaElement; match.scope= getContainer().getSelectedScope(); match.workingSets= getContainer().getSelectedWorkingSets(); } return match; } /* * Implements method from IDialogPage */ public void setVisible(boolean visible) { if (visible && fPattern != null) { if (fFirstTime) { fFirstTime= false; // Set item and text here to prevent page from resizing fPattern.setItems(getPreviousSearchPatterns()); initSelections(); } fPattern.setFocus(); getContainer().setPerformActionEnabled(fPattern.getText().length() > 0); } super.setVisible(visible); } public boolean isValid() { return true; } //---- Widget creation ------------------------------------------------ /** * Creates the page's content. */ public void createControl(Composite parent) { initializeDialogUnits(parent); readConfiguration(); GridData gd; Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); layout.horizontalSpacing= 10; result.setLayout(layout); result.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); RowLayouter layouter= new RowLayouter(layout.numColumns); gd= new GridData(); gd.horizontalAlignment= GridData.FILL; gd.verticalAlignment= GridData.VERTICAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_FILL; layouter.setDefaultGridData(gd, 0); layouter.setDefaultGridData(gd, 1); layouter.setDefaultSpan(); layouter.perform(createExpression(result)); layouter.perform(createSearchFor(result), createLimitTo(result), -1); SelectionAdapter javaElementInitializer= new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { if (getSearchFor() == fInitialData.searchFor) fJavaElement= fInitialData.javaElement; else fJavaElement= null; setLimitTo(getSearchFor()); updateCaseSensitiveCheckbox(); } }; fSearchFor[TYPE].addSelectionListener(javaElementInitializer); fSearchFor[METHOD].addSelectionListener(javaElementInitializer); fSearchFor[FIELD].addSelectionListener(javaElementInitializer); fSearchFor[CONSTRUCTOR].addSelectionListener(javaElementInitializer); fSearchFor[PACKAGE].addSelectionListener(javaElementInitializer); setControl(result); Dialog.applyDialogFont(result); WorkbenchHelp.setHelp(result, IJavaHelpContextIds.JAVA_SEARCH_PAGE); } private Control createExpression(Composite parent) { Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(2, false); result.setLayout(layout); GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; gd.horizontalIndent= 0; result.setLayoutData(gd); // Pattern text + info Label label= new Label(result, SWT.LEFT); label.setText(SearchMessages.getString("SearchPage.expression.label")); //$NON-NLS-1$ gd= new GridData(GridData.BEGINNING); gd.horizontalSpan= 2; // gd.horizontalIndent= -gd.horizontalIndent; label.setLayoutData(gd); // Pattern combo fPattern= new Combo(result, SWT.SINGLE | SWT.BORDER); fPattern.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { handlePatternSelected(); } }); fPattern.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { getContainer().setPerformActionEnabled(getPattern().length() > 0); updateCaseSensitiveCheckbox(); } }); gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalIndent= -gd.horizontalIndent; fPattern.setLayoutData(gd); // Ignore case checkbox fCaseSensitive= new Button(result, SWT.CHECK); fCaseSensitive.setText(SearchMessages.getString("SearchPage.expression.caseSensitive")); //$NON-NLS-1$ gd= new GridData(); fCaseSensitive.setLayoutData(gd); fCaseSensitive.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { fIsCaseSensitive= fCaseSensitive.getSelection(); writeConfiguration(); } }); return result; } private void updateCaseSensitiveCheckbox() { if (fInitialData != null && getPattern().equals(fInitialData.pattern) && fJavaElement != null) { fCaseSensitive.setEnabled(false); fCaseSensitive.setSelection(true); } else { fCaseSensitive.setEnabled(true); fCaseSensitive.setSelection(fIsCaseSensitive); } } private void handlePatternSelected() { if (fPattern.getSelectionIndex() < 0) return; int index= fgPreviousSearchPatterns.size() - 1 - fPattern.getSelectionIndex(); fInitialData= (SearchPatternData) fgPreviousSearchPatterns.get(index); for (int i= 0; i < fSearchFor.length; i++) fSearchFor[i].setSelection(false); for (int i= 0; i < fLimitTo.length; i++) fLimitTo[i].setSelection(false); fSearchFor[fInitialData.searchFor].setSelection(true); setLimitTo(fInitialData.searchFor); fLimitTo[fInitialData.limitTo].setSelection(true); fPattern.setText(fInitialData.pattern); fIsCaseSensitive= fInitialData.isCaseSensitive; fJavaElement= fInitialData.javaElement; fCaseSensitive.setEnabled(fJavaElement == null); fCaseSensitive.setSelection(fInitialData.isCaseSensitive); if (fInitialData.workingSets != null) getContainer().setSelectedWorkingSets(fInitialData.workingSets); else getContainer().setSelectedScope(fInitialData.scope); } private Control createSearchFor(Composite parent) { Group result= new Group(parent, SWT.NONE); result.setText(SearchMessages.getString("SearchPage.searchFor.label")); //$NON-NLS-1$ GridLayout layout= new GridLayout(); layout.numColumns= 3; result.setLayout(layout); fSearchFor= new Button[fSearchForText.length]; for (int i= 0; i < fSearchForText.length; i++) { Button button= new Button(result, SWT.RADIO); button.setText(fSearchForText[i]); fSearchFor[i]= button; } // Fill with dummy radio buttons Button filler= new Button(result, SWT.RADIO); filler.setVisible(false); filler= new Button(result, SWT.RADIO); filler.setVisible(false); return result; } private Control createLimitTo(Composite parent) { Group result= new Group(parent, SWT.NONE); result.setText(SearchMessages.getString("SearchPage.limitTo.label")); //$NON-NLS-1$ GridLayout layout= new GridLayout(); layout.numColumns= 2; result.setLayout(layout); fLimitTo= new Button[fLimitToText.length]; for (int i= 0; i < fLimitToText.length; i++) { Button button= new Button(result, SWT.RADIO); button.setText(fLimitToText[i]); fLimitTo[i]= button; } return result; } private void initSelections() { fStructuredSelection= asStructuredSelection(); fInitialData= tryStructuredSelection(fStructuredSelection); if (fInitialData == null) fInitialData= trySimpleTextSelection(getContainer().getSelection()); if (fInitialData == null) fInitialData= getDefaultInitValues(); fJavaElement= fInitialData.javaElement; fCaseSensitive.setSelection(fInitialData.isCaseSensitive); fCaseSensitive.setEnabled(fInitialData.javaElement == null); fSearchFor[fInitialData.searchFor].setSelection(true); setLimitTo(fInitialData.searchFor); fLimitTo[fInitialData.limitTo].setSelection(true); fPattern.setText(fInitialData.pattern); } private SearchPatternData tryStructuredSelection(IStructuredSelection selection) { if (selection == null || selection.size() > 1) return null; Object o= selection.getFirstElement(); if (o instanceof IJavaElement) { return determineInitValuesFrom((IJavaElement)o); } else if (o instanceof ISearchResultViewEntry) { IJavaElement element= SearchUtil.getJavaElement(((ISearchResultViewEntry)o).getSelectedMarker()); return determineInitValuesFrom(element); } else if (o instanceof LogicalPackage) { LogicalPackage lp= (LogicalPackage)o; return new SearchPatternData(PACKAGE, REFERENCES, fIsCaseSensitive, lp.getElementName(), null); } else if (o instanceof IAdaptable) { IJavaElement element= (IJavaElement)((IAdaptable)o).getAdapter(IJavaElement.class); if (element != null) { return determineInitValuesFrom(element); } else { IWorkbenchAdapter adapter= (IWorkbenchAdapter)((IAdaptable)o).getAdapter(IWorkbenchAdapter.class); if (adapter != null) return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, adapter.getLabel(o), null); } } return null; } private SearchPatternData determineInitValuesFrom(IJavaElement element) { if (element == null) return null; int searchFor= UNKNOWN; int limitTo= UNKNOWN; String pattern= null; switch (element.getElementType()) { case IJavaElement.PACKAGE_FRAGMENT: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.PACKAGE_FRAGMENT_ROOT: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.PACKAGE_DECLARATION: searchFor= PACKAGE; limitTo= REFERENCES; pattern= element.getElementName(); break; case IJavaElement.IMPORT_DECLARATION: pattern= element.getElementName(); IImportDeclaration declaration= (IImportDeclaration)element; if (declaration.isOnDemand()) { searchFor= PACKAGE; int index= pattern.lastIndexOf('.'); pattern= pattern.substring(0, index); } else { searchFor= TYPE; } limitTo= DECLARATIONS; break; case IJavaElement.TYPE: searchFor= TYPE; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName((IType)element); break; case IJavaElement.COMPILATION_UNIT: ICompilationUnit cu= (ICompilationUnit)element; String mainTypeName= element.getElementName().substring(0, element.getElementName().indexOf(".")); //$NON-NLS-1$ IType mainType= cu.getType(mainTypeName); mainTypeName= JavaModelUtil.getTypeQualifiedName(mainType); try { mainType= JavaModelUtil.findTypeInCompilationUnit(cu, mainTypeName); if (mainType == null) { // fetch type which is declared first in the file IType[] types= cu.getTypes(); if (types.length > 0) mainType= types[0]; else break; } } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } searchFor= TYPE; element= mainType; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName(mainType); break; case IJavaElement.CLASS_FILE: IClassFile cf= (IClassFile)element; try { mainType= cf.getType(); } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } if (mainType == null) break; element= mainType; searchFor= TYPE; limitTo= REFERENCES; pattern= JavaModelUtil.getFullyQualifiedName(mainType); break; case IJavaElement.FIELD: searchFor= FIELD; limitTo= REFERENCES; IType type= ((IField)element).getDeclaringType(); StringBuffer buffer= new StringBuffer(); buffer.append(JavaModelUtil.getFullyQualifiedName(type)); buffer.append('.'); buffer.append(element.getElementName()); pattern= buffer.toString(); break; case IJavaElement.METHOD: searchFor= METHOD; try { IMethod method= (IMethod)element; if (method.isConstructor()) searchFor= CONSTRUCTOR; } catch (JavaModelException ex) { ExceptionHandler.handle(ex, SearchMessages.getString("Search.Error.javaElementAccess.title"), SearchMessages.getString("Search.Error.javaElementAccess.message")); //$NON-NLS-2$ //$NON-NLS-1$ break; } limitTo= REFERENCES; pattern= PrettySignature.getMethodSignature((IMethod)element); break; } if (searchFor != UNKNOWN && limitTo != UNKNOWN && pattern != null) return new SearchPatternData(searchFor, limitTo, true, pattern, element); return null; } private SearchPatternData trySimpleTextSelection(ISelection selection) { SearchPatternData result= null; if (selection instanceof ITextSelection) { BufferedReader reader= new BufferedReader(new StringReader(((ITextSelection)selection).getText())); String text; try { text= reader.readLine(); if (text == null) text= ""; //$NON-NLS-1$ } catch (IOException ex) { text= ""; //$NON-NLS-1$ } result= new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, text, null); } return result; } private SearchPatternData getDefaultInitValues() { return new SearchPatternData(TYPE, REFERENCES, fIsCaseSensitive, "", null); //$NON-NLS-1$ } /* * Implements method from ISearchPage */ public void setContainer(ISearchPageContainer container) { fContainer= container; } /** * Returns the search page's container. */ private ISearchPageContainer getContainer() { return fContainer; } /** * Returns the structured selection from the selection. */ private IStructuredSelection asStructuredSelection() { IWorkbenchWindow wbWindow= PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (wbWindow != null) { IWorkbenchPage page= wbWindow.getActivePage(); if (page != null) { IWorkbenchPart part= page.getActivePart(); if (part != null) try { return SelectionConverter.getStructuredSelection(part); } catch (JavaModelException ex) { } } } return StructuredSelection.EMPTY; } //--------------- Configuration handling -------------- /** * Returns the page settings for this Java search page. * * @return the page settings to be used */ private IDialogSettings getDialogSettings() { IDialogSettings settings= JavaPlugin.getDefault().getDialogSettings(); fDialogSettings= settings.getSection(PAGE_NAME); if (fDialogSettings == null) fDialogSettings= settings.addNewSection(PAGE_NAME); return fDialogSettings; } /** * Initializes itself from the stored page settings. */ private void readConfiguration() { IDialogSettings s= getDialogSettings(); fIsCaseSensitive= s.getBoolean(STORE_CASE_SENSITIVE); } /** * Stores it current configuration in the dialog store. */ private void writeConfiguration() { IDialogSettings s= getDialogSettings(); s.put(STORE_CASE_SENSITIVE, fIsCaseSensitive); } }
47,210
Bug 47210 [refactoring] change method signature - misleading message
1) open the change method signature dialog 2) flip to the Exceptions tab ->message at the bottom: Specify the new order of parameters and/or their new names. The message should be specific to the current tab and say: Specify the exceptions that should be added or removed
resolved fixed
d27a7b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-08T18:04:11Z
2003-11-21T13:06:40Z
org.eclipse.jdt.ui/ui
47,210
Bug 47210 [refactoring] change method signature - misleading message
1) open the change method signature dialog 2) flip to the Exceptions tab ->message at the bottom: Specify the new order of parameters and/or their new names. The message should be specific to the current tab and say: Specify the exceptions that should be added or removed
resolved fixed
d27a7b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-08T18:04:11Z
2003-11-21T13:06:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ChangeSignatureWizard.java
32,478
Bug 32478 Create inner subclass generate invalid import
When we have a class with an inner protected class like that, package test1; public class Parent { protected class Inner { } } and an other one like that package test2; import test1.Parent; public class Child extends Parent { } and we want to generate a inner class in Child that extends the inner class Protected.Inner, we obtain package test2; import test1.Parent; import test1.Parent.Inner; public class Child extends Parent { public class Generated extends Inner { } } but the import statement is not valid. It should not be generated.
resolved fixed
fc4893f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-08T19:29:00Z
2003-02-21T12:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.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.text.ITextSelection; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.window.Window; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.core.*; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.formatter.CodeFormatter; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.CodeGeneration; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.dom.TokenScanner; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.CodeFormatterUtil; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.*; /** * The class <code>NewTypeWizardPage</code> contains controls and validation routines * for a 'New Type WizardPage'. Implementors decide which components to add and to enable. * Implementors can also customize the validation code. <code>NewTypeWizardPage</code> * is intended to serve as base class of all wizards that create types like applets, servlets, classes, * interfaces, etc. * <p> * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an * example usage of <code>NewTypeWizardPage</code>. * </p> * * @see org.eclipse.jdt.ui.wizards.NewClassWizardPage * @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage * * @since 2.0 */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { /** * Class used in stub creation routines to add needed imports to a * compilation unit. */ public static class ImportsManager { private IImportsStructure fImportsStructure; /* package */ ImportsManager(IImportsStructure structure) { fImportsStructure= structure; } /* package */ IImportsStructure getImportsStructure() { return fImportsStructure; } /** * Adds a new import declaration that is sorted in the existing imports. * If an import already exists or the import would conflict with another import * of an other type with the same simple name the import is not added. * * @param qualifiedTypeName The fully qualified name of the type to import * (dot separated) * @return Returns the simple type name that can be used in the code or the * fully qualified type name if an import conflict prevented the import */ public String addImport(String qualifiedTypeName) { return fImportsStructure.addImport(qualifiedTypeName); } } /** Public access flag. See The Java Virtual Machine Specification for more details. */ public int F_PUBLIC = Flags.AccPublic; /** Private access flag. See The Java Virtual Machine Specification for more details. */ public int F_PRIVATE = Flags.AccPrivate; /** Protected access flag. See The Java Virtual Machine Specification for more details. */ public int F_PROTECTED = Flags.AccProtected; /** Static access flag. See The Java Virtual Machine Specification for more details. */ public int F_STATIC = Flags.AccStatic; /** Final access flag. See The Java Virtual Machine Specification for more details. */ public int F_FINAL = Flags.AccFinal; /** Abstract property flag. See The Java Virtual Machine Specification for more details. */ public int F_ABSTRACT = Flags.AccAbstract; private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$ /** Field ID of the package input field */ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ /** Field ID of the eclosing type input field */ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ /** Field ID of the enclosing type checkbox */ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ /** Field ID of the type name input field */ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ /** Field ID of the super type input field */ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ /** Field ID of the super interfaces input field */ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ /** Field ID of the modifier checkboxes */ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ /** Field ID of the method stubs checkboxes */ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; /** * Creates a new <code>NewTypeWizardPage</code> * * @param isClass <code>true</code> if a new class is to be created; otherwise * an interface is to be created * @param pageName the wizard page's name */ public NewTypeWizardPage(boolean isClass, String pageName) { super(pageName); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the page with a given selection. * * @param elem the selection used to intialize this page or <code> * null</code> if no selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= cu.findPrimaryType(); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e); // ignore this exception now } } String typeName= ""; //$NON-NLS-1$ ITextSelection selection= getCurrentTextSelection(); if (selection != null) { String text= selection.getText(); if (JavaConventions.validateJavaTypeName(text).isOK()) { typeName= text; } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName(typeName, true); setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); } /** * Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { // #6891 Composite tabGroup= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; tabGroup.setLayout(layout); fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= getMaxFieldWidth(); gd.horizontalSpan= 2; c.setLayoutData(gd); Button button= fEnclosingTypeDialogField.getChangeControl(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = SWTUtil.getButtonHeightHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); } /** * Creates the controls for the type name field. Expects a <code>GridLayout</code> with at * least 2 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the modifiers radio/ceckbox buttons. Expects a * <code>GridLayout</code> with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> * with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with * at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; gd.widthHint= getMaxFieldWidth(); } /** * Sets the focus on the type name input field. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(ListDialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(ListDialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } public void doubleClicked(ListDialogField field) { } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons || field == fAccMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /* * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Returns the text of the package input field. * * @return the text of the package input field */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Returns the text of the enclosing type input field. * * @return the text of the enclosing type input field */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * * @return a package fragement or <code>null</code> if the input * could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment to the given value. The method updates the model * and the text of the control. * * @param pack the package fragement to be set * @param canBeModified if <code>true</code> the package fragment is * editable; otherwise it is read-only. */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the enclosing type corresponding to the current input. * * @return the enclosing type or <code>null</code> if the enclosing type is * not selected or the input could not be resolved */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the enclosing type. The method updates the underlying model * and the text of the control. * * @param type the enclosing type * @param canBeModified if <code>true</code> the enclosing type field is * editable; otherwise it is read-only. */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns the selection state of the enclosing type checkbox. * * @return the seleciton state of the enclosing type checkbox */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type checkbox's selection state. * * @param isSelected the checkbox's selection state * @param canBeModified if <code>true</code> the enclosing type checkbox is * modifiable; otherwise it is read-only. */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Returns the type name entered into the type input field. * * @return the type name */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name input field's text to the given value. Method doesn't update * the model. * * @param name the new type name * @param canBeModified if <code>true</code> the enclosing type name field is * editable; otherwise it is read-only. */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Returns the selected modifiers. * * @return the selected modifiers * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= F_PUBLIC; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= F_PRIVATE; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= F_PROTECTED; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= F_ABSTRACT; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= F_FINAL; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= F_STATIC; } return mdf; } /** * Sets the modifiers. * * @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>, * <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code> * or <code>F_STATIC</code> or, a valid combination. * @param canBeModified if <code>true</code> the modifier fields are * editable; otherwise they are read-only * @see Flags */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Returns the content of the superclass input field. * * @return the superclass name */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * * @param name the new superclass name * @param canBeModified if <code>true</code> the superclass name field is * editable; otherwise it is read-only. */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Returns the chosen super interfaces. * * @return a list of chosen super interfaces. The list's elements * are of type <code>String</code> */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * * @param interfacesNames a list of super interface. The method requires that * the list's elements are of type <code>String</code> * @param canBeModified if <code>true</code> the super interface field is * editable; otherwise it is read-only. */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * A hook method that gets called when the package field has changed. The method * validates the package name and returns the status of the validation. The validation * also updates the package fragment model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { if (root.getJavaProject().exists() && packName.length() > 0) { try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage= root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= getPackageText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Hook method that gets called when the enclosing type name has changed. The method * validates the enclosing type and returns the status of the validation. It also updates the * enclosing type model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= findType(root.getJavaProject(), enclName); if (type == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e); return status; } } /** * Hook method that gets called when the type name has changed. The method validates the * type name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.getResource().exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Hook method that gets called when the superclass name has changed. The method * validates the superclass name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { if (!jproject.exists()) { return null; } IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= jproject.findType(res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= jproject.findType(packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(sclassName); } } return type; } private IType findType(IJavaProject project, String typeName) throws JavaModelException { if (project.exists()) { return project.findType(typeName); } return null; } /** * Hook method that gets called when the list of super interface has changed. The method * validates the superinterfaces and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= findType(root.getJavaProject(), intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, checking is an extra } } } return status; } /** * Hook method that gets called when the modifiers have changed. The method validates * the modifiers and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null && froot.exists()) { packages= froot.getChildren(); } } catch (JavaModelException e) { JavaPlugin.log(e); } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); IPackageFragment pack= getPackageFragment(); if (pack != null) { dialog.setInitialSelections(new Object[] { pack }); } if (dialog.open() == Window.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ dialog.setFilter(getSuperClass()); if (dialog.open() == Window.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$NON-NLS-1$ //$NON-NLS-2$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.message")); //$NON-NLS-1$ dialog.open(); return; } // ---- creation ---------------- /** * Creates the new type using the entered field values. * * @param monitor a progress monitor to report progress. */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ ICompilationUnit createdWorkingCopy= null; try { IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= getTypeName(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; IPreferenceStore store= PreferenceConstants.getPreferenceStore(); String[] prefOrder= JavaPreferencesSettings.getImportOrderPreference(store); int threshold= JavaPreferencesSettings.getImportNumberThreshold(store); String lineDelimiter= null; if (!isInnerClass) { lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$ // create a working copy with a new owner createdWorkingCopy= parentCU.getWorkingCopy(null); // use the compiler template a first time to read the imports String content= CodeGeneration.getCompilationUnitContent(createdWorkingCopy, null, "", lineDelimiter); //$NON-NLS-1$ if (content != null) { createdWorkingCopy.getBuffer().setContents(content); } imports= new ImportsStructure(createdWorkingCopy, prefOrder, threshold, true); // add an import that will be removed again. Having this import solves 14661 imports.addImport(pack.getElementName(), getTypeName()); String typeContent= constructTypeStub(new ImportsManager(imports), lineDelimiter); String cuContent= constructCUContent(parentCU, typeContent, lineDelimiter); createdWorkingCopy.getBuffer().setContents(cuContent); createdType= createdWorkingCopy.getType(clName); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); // add imports that will be removed again. Having the imports solves 14661 IType[] topLevelTypes= parentCU.getTypes(); for (int i= 0; i < topLevelTypes.length; i++) { imports.addImport(topLevelTypes[i].getFullyQualifiedName('.')); } lineDelimiter= StubUtility.getLineDelimiterUsed(enclosingType); StringBuffer content= new StringBuffer(); if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) { String comment= getTypeComment(parentCU, lineDelimiter); if (comment != null) { content.append(comment); content.append(lineDelimiter); } } content.append(constructTypeStub(new ImportsManager(imports), lineDelimiter)); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content.toString(), sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so types can be resolved correctly boolean needsSave= !imports.getCompilationUnit().isWorkingCopy(); imports.create(needsSave, new SubProgressMonitor(monitor, 1)); ICompilationUnit cu= createdType.getCompilationUnit(); synchronized(cu) { cu.reconcile(); } createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1)); // add imports imports.create(needsSave, new SubProgressMonitor(monitor, 1)); synchronized(cu) { cu.reconcile(); } ISourceRange range= createdType.getSourceRange(); IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); String formattedContent= CodeFormatterUtil.format(CodeFormatter.K_CLASS_BODY_DECLARATIONS, originalContent, indent, null, lineDelimiter, null); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment= getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } cu.commit(false, new SubProgressMonitor(monitor, 1)); } else { if (needsSave) { buf.save(null, false); } monitor.worked(1); } if (createdWorkingCopy != null) { fCreatedType= (IType) createdType.getPrimaryElement(); } else { fCreatedType= createdType; } } finally { if (createdWorkingCopy != null) { createdWorkingCopy.destroy(); } monitor.done(); } } /** * Uses the New Java file template from the code template page to generate a * compilation unit with the given type content. * @param cu The new created compilation unit * @param typeContent The content of the type, including signature and type * body. * @param lineDelimiter The line delimiter to be used. * @return String Returns the result of evaluating the new file template * with the given type content. * @throws CoreException * @since 2.1 */ protected String constructCUContent(ICompilationUnit cu, String typeContent, String lineDelimiter) throws CoreException { String typeComment= getTypeComment(cu, lineDelimiter); IPackageFragment pack= (IPackageFragment) cu.getParent(); String content= CodeGeneration.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter); if (content != null) { CompilationUnit unit= AST.parseCompilationUnit(content.toCharArray()); if ((pack.isDefaultPackage() || unit.getPackage() != null) && !unit.types().isEmpty()) { return content; } } StringBuffer buf= new StringBuffer(); if (!pack.isDefaultPackage()) { buf.append("package ").append(pack.getElementName()).append(';'); //$NON-NLS-1$ } buf.append(lineDelimiter).append(lineDelimiter); if (typeComment != null) { buf.append(typeComment).append(lineDelimiter); } buf.append(typeContent); return buf.toString(); } /** * Returns the created type. The method only returns a valid type * after <code>createType</code> has been called. * * @return the created type * @see #createType(IProgressMonitor) */ public IType getCreatedType() { return fCreatedType; } // ---- construct cu body---------------- private void writeSuperClass(StringBuffer buf, ImportsManager imports) { String typename= getSuperClass(); if (fIsClass && typename.length() > 0 && !"java.lang.Object".equals(typename)) { //$NON-NLS-1$ buf.append(" extends "); //$NON-NLS-1$ String qualifiedName= fSuperClass != null ? JavaModelUtil.getFullyQualifiedName(fSuperClass) : typename; buf.append(imports.addImport(qualifiedName)); } } private void writeSuperInterfaces(StringBuffer buf, ImportsManager imports) { List interfaces= getSuperInterfaces(); int last= interfaces.size() - 1; if (last >= 0) { if (fIsClass) { buf.append(" implements "); //$NON-NLS-1$ } else { buf.append(" extends "); //$NON-NLS-1$ } for (int i= 0; i <= last; i++) { String typename= (String) interfaces.get(i); buf.append(imports.addImport(typename)); if (i < last) { buf.append(','); } } } } /* * Called from createType to construct the source for this type */ private String constructTypeStub(ImportsManager imports, String lineDelimiter) { StringBuffer buf= new StringBuffer(); int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append('{'); buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead */ protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { //deprecated } /** * Hook method that gets called from <code>createType</code> to support adding of * unanticipated methods, fields, and inner types to the created type. * <p> * Implementers can use any methods defined on <code>IType</code> to manipulate the * new type. * </p> * <p> * The source code of the new type will be formtted using the platform's formatter. Needed * imports are added by the wizard at the end of the type creation process using the given * import manager. * </p> * * @param newType the new type created via <code>createType</code> * @param imports an import manager which can be used to add new imports * @param monitor a progress monitor to report progress. Must not be <code>null</code> * * @see #createType(IProgressMonitor) */ protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { // call for compatibility createTypeMembers(newType, imports.getImportsStructure(), monitor); // default implementation does nothing // example would be // String mainMathod= "public void foo(Vector vec) {}" // createdType.createMethod(main, null, false, null); // imports.addImport("java.lang.Vector"); } /** * @deprecated Instead of file templates, the new type code template * specifies the stub for a compilation unit. */ protected String getFileComment(ICompilationUnit parentCU) { return null; } private boolean isValidComment(String template) { IScanner scanner= ToolFactory.createScanner(true, false, false, false); scanner.setSource(template.toCharArray()); try { int next= scanner.getNextToken(); while (TokenScanner.isComment(next)) { next= scanner.getNextToken(); } return next == ITerminalSymbols.TokenNameEOF; } catch (InvalidInputException e) { } return false; } /** * Hook method that gets called from <code>createType</code> to retrieve * a type comment. This default implementation returns the content of the * 'type comment' template. * * @return the type comment or <code>null</code> if a type comment * is not desired */ protected String getTypeComment(ICompilationUnit parentCU, String lineDelimiter) { try { StringBuffer typeName= new StringBuffer(); if (isEnclosingTypeSelected()) { typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); } typeName.append(getTypeName()); String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), lineDelimiter); if (comment != null && isValidComment(comment)) { return comment; } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * @deprecated Use getTypeComment(ICompilationUnit, String) */ protected String getTypeComment(ICompilationUnit parentCU) { if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) { return getTypeComment(parentCU, String.valueOf('\n')); } return null; } /** * @deprecated Use getTemplate(String,ICompilationUnit,int) */ protected String getTemplate(String name, ICompilationUnit parentCU) { return getTemplate(name, parentCU, 0); } /** * Returns the string resulting from evaluation the given template in * the context of the given compilation unit. This accesses the normal * template page, not the code templates. To use code templates use * <code>constructCUContent</code> to construct a compilation unit stub or * getTypeComment for the comment of the type. * * @param name the template to be evaluated * @param parentCU the templates evaluation context * @param pos a source offset into the parent compilation unit. The * template is evalutated at the given source offset */ protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { try { Template[] templates= Templates.getInstance().getTemplates(name); if (templates.length > 0) { return JavaContext.evaluateTemplate(templates[0], parentCU, pos); } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor); } /** * Creates the bodies of all unimplemented methods and constructors and adds them to the type. * Method is typically called by implementers of <code>NewTypeWizardPage</code> to add * needed method and constructors. * * @param type the type for which the new methods and constructor are to be created * @param doConstructors if <code>true</code> unimplemented constructors are created * @param doUnimplementedMethods if <code>true</code> unimplemented methods are created * @param imports an import manager to add all neded import statements * @param monitor a progress monitor to report progress */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException { ArrayList newMethods= new ArrayList(); ITypeHierarchy hierarchy= null; CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (doConstructors) { hierarchy= type.newSupertypeHierarchy(monitor); IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure()); if (constructors != null) { for (int i= 0; i < constructors.length; i++) { newMethods.add(constructors[i]); } } } } if (doUnimplementedMethods) { if (hierarchy == null) { hierarchy= type.newSupertypeHierarchy(monitor); } String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, imports.getImportsStructure()); if (unimplemented != null) { for (int i= 0; i < unimplemented.length; i++) { newMethods.add(unimplemented[i]); } } } IMethod[] createdMethods= new IMethod[newMethods.size()]; for (int i= 0; i < newMethods.size(); i++) { String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n createdMethods[i]= type.createMethod(content, null, false, null); } return createdMethods; } // ---- creation ---------------- /** * Returns the runnable that creates the type using the current settings. * The returned runnable must be executed in the UI thread. * * @return the runnable to create the new type */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
37,353
Bug 37353 add variable button can't add variable only edit. [build path}
Project->properties->java build path->Library tab->add variable button will only allow you to extend or edit a variable not add a variable. The only way to add a classpath variable is to go Window->preferences->java->classpath variables->new button.
resolved fixed
f2e3fde
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T09:51:04Z
2003-05-07T20:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/NewVariableEntryDialog.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; import java.util.ArrayList; import java.util.List; 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.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.IDialogConstants; import org.eclipse.jface.preference.IPreferenceNode; import org.eclipse.jface.preference.IPreferencePage; import org.eclipse.jface.preference.PreferenceDialog; import org.eclipse.jface.preference.PreferenceManager; import org.eclipse.jface.preference.PreferenceNode; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jface.window.Window; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.preferences.ClasspathVariablesPreferencePage; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class NewVariableEntryDialog extends StatusDialog { private class VariablesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(ListDialogField field, int index) { switch (index) { case IDX_EXTEND: /* extend */ extendButtonPressed(); break; case IDX_CONFIG: /* config */ configButtonPressed(); break; } } public void selectionChanged(ListDialogField field) { doSelectionChanged(); } public void doubleClicked(ListDialogField field) { doDoubleClick(); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { } } private final int IDX_EXTEND= 0; private final int IDX_CONFIG= 2; private ListDialogField fVariablesList; private boolean fCanExtend; private boolean fIsValidSelection; private IPath[] fResultPaths; public NewVariableEntryDialog(Shell parent) { super(parent); int shellStyle= getShellStyle(); setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE); updateStatus(new StatusInfo(IStatus.ERROR, "")); //$NON-NLS-1$ String[] buttonLabels= new String[] { /* IDX_EXTEND */ NewWizardMessages.getString("NewVariableEntryDialog.vars.extend"), //$NON-NLS-1$ null, /* IDX_CONFIG */ NewWizardMessages.getString("NewVariableEntryDialog.vars.config"), //$NON-NLS-1$ }; VariablesAdapter adapter= new VariablesAdapter(); CPVariableElementLabelProvider labelProvider= new CPVariableElementLabelProvider(false); fVariablesList= new ListDialogField(adapter, buttonLabels, labelProvider); fVariablesList.setDialogFieldListener(adapter); fVariablesList.setLabelText(NewWizardMessages.getString("NewVariableEntryDialog.vars.label")); //$NON-NLS-1$ fVariablesList.enableButton(IDX_EXTEND, false); fVariablesList.setViewerSorter(new ViewerSorter() { public int compare(Viewer viewer, Object e1, Object e2) { if (e1 instanceof CPVariableElement && e2 instanceof CPVariableElement) { return ((CPVariableElement)e1).getName().compareTo(((CPVariableElement)e2).getName()); } return super.compare(viewer, e1, e2); } }); initializeElements(); fCanExtend= false; fIsValidSelection= false; fResultPaths= null; } private void initializeElements() { String[] entries= JavaCore.getClasspathVariableNames(); ArrayList elements= new ArrayList(entries.length); for (int i= 0; i < entries.length; i++) { String name= entries[i]; IPath entryPath= JavaCore.getClasspathVariable(name); if (entryPath != null) { elements.add(new CPVariableElement(name, entryPath, false)); } } fVariablesList.setElements(elements); } /* (non-Javadoc) * @see Window#configureShell(Shell) */ protected void configureShell(Shell shell) { super.configureShell(shell); WorkbenchHelp.setHelp(shell, IJavaHelpContextIds.NEW_VARIABLE_ENTRY_DIALOG); } /* (non-Javadoc) * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= (Composite) super.createDialogArea(parent); GridLayout layout= (GridLayout) composite.getLayout(); layout.numColumns= 2; fVariablesList.doFillIntoGrid(composite, 3); LayoutUtil.setHorizontalSpan(fVariablesList.getLabelControl(null), 2); GridData listData= (GridData) fVariablesList.getListControl(null).getLayoutData(); listData.grabExcessHorizontalSpace= true; listData.heightHint= convertHeightInCharsToPixels(10); applyDialogFont(composite); return composite; } public IPath[] getResult() { return fResultPaths; } /* * @see IDoubleClickListener#doubleClick(DoubleClickEvent) */ private void doDoubleClick() { if (fIsValidSelection) { okPressed(); } else if (fCanExtend) { extendButtonPressed(); } } private void doSelectionChanged() { boolean isValidSelection= true; boolean canExtend= false; StatusInfo status= new StatusInfo(); List selected= fVariablesList.getSelectedElements(); int nSelected= selected.size(); if (nSelected > 0) { fResultPaths= new Path[nSelected]; for (int i= 0; i < nSelected; i++) { CPVariableElement curr= (CPVariableElement) selected.get(i); fResultPaths[i]= new Path(curr.getName()); if (!curr.getPath().toFile().isFile()) { status.setInfo(NewWizardMessages.getString("NewVariableEntryDialog.info.isfolder")); //$NON-NLS-1$ canExtend= true; } } } else { isValidSelection= false; status.setInfo(NewWizardMessages.getString("NewVariableEntryDialog.info.noselection")); //$NON-NLS-1$ } if (isValidSelection && nSelected > 1) { String str= NewWizardMessages.getFormattedString("NewVariableEntryDialog.info.selected", String.valueOf(nSelected)); //$NON-NLS-1$ status.setInfo(str); } fCanExtend= nSelected == 1 && canExtend; fVariablesList.enableButton(0, fCanExtend); updateStatus(status); fIsValidSelection= isValidSelection; Button okButton= getButton(IDialogConstants.OK_ID); if (okButton != null && !okButton.isDisposed()) { okButton.setEnabled(isValidSelection); } } private IPath[] chooseExtensions(CPVariableElement elem) { File file= elem.getPath().toFile(); JARFileSelectionDialog dialog= new JARFileSelectionDialog(getShell(), true, false); dialog.setTitle(NewWizardMessages.getString("NewVariableEntryDialog.ExtensionDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getFormattedString("NewVariableEntryDialog.ExtensionDialog.description", elem.getName())); //$NON-NLS-1$ dialog.setInput(file); if (dialog.open() == Window.OK) { Object[] selected= dialog.getResult(); IPath[] paths= new IPath[selected.length]; for (int i= 0; i < selected.length; i++) { IPath filePath= new Path(((File) selected[i]).getPath()); IPath resPath= new Path(elem.getName()); for (int k= elem.getPath().segmentCount(); k < filePath.segmentCount(); k++) { resPath= resPath.append(filePath.segment(k)); } paths[i]= resPath; } return paths; } return null; } protected void extendButtonPressed() { List selected= fVariablesList.getSelectedElements(); if (selected.size() == 1) { IPath[] extendedPaths= chooseExtensions((CPVariableElement) selected.get(0)); if (extendedPaths != null) { fResultPaths= extendedPaths; super.buttonPressed(IDialogConstants.OK_ID); } } } protected void configButtonPressed() { ClasspathVariablesPreferencePage page= new ClasspathVariablesPreferencePage(); showPreferencePage(ClasspathVariablesPreferencePage.ID, page); initializeElements(); } private boolean showPreferencePage(String id, IPreferencePage page) { final IPreferenceNode targetNode = new PreferenceNode(id, page); PreferenceManager manager = new PreferenceManager(); manager.addToRoot(targetNode); final PreferenceDialog dialog = new PreferenceDialog(getShell(), manager); final boolean [] result = new boolean[] { false }; BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() { public void run() { dialog.create(); dialog.setMessage(targetNode.getLabelText()); result[0]= (dialog.open() == Window.OK); } }); return result[0]; } }
45,179
Bug 45179 Save dialog state of rename dialog [refactoring]
when you are making batch refactor you use some specifig kind of setting for it like : refactor -> rename has following choices : Update references to renamed classes (checked by default) Update references in javadocs Update references in regular comments Update references in string literals Update fully qualifed names in non Java file ( force preview ) File name patterns : [ ] - this one is saved all other are not, it would be a nice feature to save all thouse settings so there is no need to check all of them all the time
resolved fixed
7114d5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T09:59:58Z
2003-10-19T21:46:40Z
org.eclipse.jdt.ui/ui
45,179
Bug 45179 Save dialog state of rename dialog [refactoring]
when you are making batch refactor you use some specifig kind of setting for it like : refactor -> rename has following choices : Update references to renamed classes (checked by default) Update references in javadocs Update references in regular comments Update references in string literals Update fully qualifed names in non Java file ( force preview ) File name patterns : [ ] - this one is saved all other are not, it would be a nice feature to save all thouse settings so there is no need to check all of them all the time
resolved fixed
7114d5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T09:59:58Z
2003-10-19T21:46:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/RenameFieldWizard.java
45,179
Bug 45179 Save dialog state of rename dialog [refactoring]
when you are making batch refactor you use some specifig kind of setting for it like : refactor -> rename has following choices : Update references to renamed classes (checked by default) Update references in javadocs Update references in regular comments Update references in string literals Update fully qualifed names in non Java file ( force preview ) File name patterns : [ ] - this one is saved all other are not, it would be a nice feature to save all thouse settings so there is no need to check all of them all the time
resolved fixed
7114d5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T09:59:58Z
2003-10-19T21:46:40Z
org.eclipse.jdt.ui/ui
45,179
Bug 45179 Save dialog state of rename dialog [refactoring]
when you are making batch refactor you use some specifig kind of setting for it like : refactor -> rename has following choices : Update references to renamed classes (checked by default) Update references in javadocs Update references in regular comments Update references in string literals Update fully qualifed names in non Java file ( force preview ) File name patterns : [ ] - this one is saved all other are not, it would be a nice feature to save all thouse settings so there is no need to check all of them all the time
resolved fixed
7114d5d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T09:59:58Z
2003-10-19T21:46:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/reorg/RenameInputWizardPage.java
24,894
Bug 24894 Ctrl+A in Type Hierarchy works strange [type hierarchy]
Build 20021016 This problem is caused because of the two panes in the view. If I select the toolbar of the lower pane and then press Ctrl+A I expect all members to be selected. This does not work in most of the cases: I have to click into the list and then press Ctrl+A.
resolved fixed
4f6edb5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T13:43:02Z
2002-10-17T10:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.typehierarchy; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.ViewForm; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DropTarget; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.KeyListener; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ScrollBar; import org.eclipse.swt.widgets.ToolBar; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.action.Separator; import org.eclipse.jface.action.ToolBarManager; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.AbstractTreeViewer; import org.eclipse.jface.viewers.IBasicPropertyConstants; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPartListener2; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartReference; import org.eclipse.ui.IWorkingSetManager; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionFactory; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.IShowInSource; import org.eclipse.ui.part.IShowInTargetList; import org.eclipse.ui.part.PageBook; import org.eclipse.ui.part.ShowInContext; import org.eclipse.ui.part.ViewPart; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.ITypeHierarchyViewPart; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.internal.corext.util.AllTypesCache; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.AddMethodStubAction; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.actions.SelectAllAction; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.JdtViewerDragAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of input elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private IDialogSettings fDialogSettings; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private IPropertyChangeListener fPropertyChangeListener; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private IPartListener2 fPartListener; private int fCurrentOrientation; private boolean fLinkingEnabled; private boolean fIsVisible; private boolean fNeedRefresh; private boolean fIsEnableMemberFilter; private boolean fIsRefreshRunnablePosted; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private MethodsViewer fMethodsViewer; private SashForm fTypeMethodsSplitter; private PageBook fViewerbook; private PageBook fPagebook; private Label fNoHierarchyShownLabel; private Label fEmptyTypesViewer; private ViewForm fTypeViewerViewForm; private ViewForm fMethodViewerViewForm; private CLabel fMethodViewerPaneLabel; private JavaUILabelProvider fPaneLabelProvider; private ToggleViewAction[] fViewActions; private ToggleLinkingAction fToggleLinkingAction; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private EnableMemberFilterAction fEnableMemberFilterAction; private ShowQualifiedTypeNamesAction fShowQualifiedTypeNamesAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; private SelectAllAction fSelectAllAction; private WorkingSetFilterActionGroup fWorkingSetActionGroup; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fIsVisible= false; fIsRefreshRunnablePosted= false; boolean isReconciled= PreferenceConstants.UPDATE_WHILE_EDITING.equals(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.UPDATE_JAVA_VIEWS)); fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fHierarchyLifeCycle.setReconciled(isReconciled); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); fPropertyChangeListener= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { doPropertyChange(event); } }; PreferenceConstants.getPreferenceStore().addPropertyChangeListener(fPropertyChangeListener); fIsEnableMemberFilter= false; fInputHistory= new ArrayList(); fAllViewers= null; fViewActions= new ToggleViewAction[] { new ToggleViewAction(this, VIEW_ID_TYPE), new ToggleViewAction(this, VIEW_ID_SUPER), new ToggleViewAction(this, VIEW_ID_SUB) }; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); fHistoryDropDownAction= new HistoryDropDownAction(this); fHistoryDropDownAction.setEnabled(false); fToggleOrientationActions= new ToggleOrientationAction[] { new ToggleOrientationAction(this, VIEW_ORIENTATION_VERTICAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_HORIZONTAL), new ToggleOrientationAction(this, VIEW_ORIENTATION_SINGLE) }; fEnableMemberFilterAction= new EnableMemberFilterAction(this, false); fShowQualifiedTypeNamesAction= new ShowQualifiedTypeNamesAction(this, false); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener2() { public void partVisible(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part == TypeHierarchyViewPart.this) { visibilityChanged(true); } } public void partHidden(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part == TypeHierarchyViewPart.this) { visibilityChanged(false); } } public void partActivated(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partInputChanged(IWorkbenchPartReference ref) { IWorkbenchPart part= ref.getPart(false); if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPartReference ref) {} public void partClosed(IWorkbenchPartReference ref) {} public void partDeactivated(IWorkbenchPartReference ref) {} public void partOpened(IWorkbenchPartReference ref) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; fLinkingEnabled= PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR); } /** * Method doPropertyChange. * @param event */ protected void doPropertyChange(PropertyChangeEvent event) { String property= event.getProperty(); if (fMethodsViewer != null) { if (PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER.equals(property)) { fMethodsViewer.refresh(); } } if (IWorkingSetManager.CHANGE_WORKING_SET_CONTENT_CHANGE.equals(property)) { updateHierarchyViewer(true); } else if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) { } } /** * Adds the entry if new. Inserted at the beginning of the history entries list. */ private void addHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { fInputHistory.remove(entry); } fInputHistory.add(0, entry); fHistoryDropDownAction.setEnabled(true); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty()); } /** * Goes to the selected entry, without updating the order of history entries. */ public void gotoHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { updateInput(entry); } } /** * Gets all history entries. */ public IJavaElement[] getHistoryEntries() { if (fInputHistory.size() > 0) { updateHistoryEntries(); } return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]); } /** * Sets the history entries */ public void setHistoryEntries(IJavaElement[] elems) { fInputHistory.clear(); for (int i= 0; i < elems.length; i++) { fInputHistory.add(elems[i]); } updateHistoryEntries(); } /** * Selects an member in the methods list or in the current hierarchy. */ public void selectMember(IMember member) { if (member.getElementType() != IJavaElement.TYPE) { // methods are working copies if (fHierarchyLifeCycle.isReconciled()) { member= JavaModelUtil.toWorkingCopy(member); } Control methodControl= fMethodsViewer.getControl(); if (methodControl != null && !methodControl.isDisposed()) { methodControl.setFocus(); } fMethodsViewer.setSelection(new StructuredSelection(member), true); } else { Control viewerControl= getCurrentViewer().getControl(); if (viewerControl != null && !viewerControl.isDisposed()) { viewerControl.setFocus(); } // types are originals member= JavaModelUtil.toOriginal(member); if (!member.equals(fSelectedType)) { getCurrentViewer().setSelection(new StructuredSelection(member), true); } } } /** * @deprecated */ public IType getInput() { if (fInputElement instanceof IType) { return (IType) fInputElement; } return null; } /** * Sets the input to a new type * @deprecated */ public void setInput(IType type) { setInputElement(type); } /** * Returns the input element of the type hierarchy. * Can be of type <code>IType</code> or <code>IPackageFragment</code> */ public IJavaElement getInputElement() { return fInputElement; } /** * Sets the input to a new element. */ public void setInputElement(IJavaElement element) { if (element != null) { if (element instanceof IMember) { if (element.getElementType() != IJavaElement.TYPE) { element= ((IMember) element).getDeclaringType(); } element= JavaModelUtil.toOriginal((IMember) element); if (!element.exists()) { MessageDialog.openError(getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.error.message")); //$NON-NLS-1$ //$NON-NLS-2$ return; } } else { int kind= element.getElementType(); if (kind != IJavaElement.JAVA_PROJECT && kind != IJavaElement.PACKAGE_FRAGMENT_ROOT && kind != IJavaElement.PACKAGE_FRAGMENT) { element= null; JavaPlugin.logErrorMessage("Invalid type hierarchy input type.");//$NON-NLS-1$ } } } if (element != null && !element.equals(fInputElement)) { addHistoryEntry(element); } updateInput(element); } /** * Changes the input to a new type */ private void updateInput(IJavaElement inputElement) { IJavaElement prevInput= fInputElement; // Make sure the UI got repainted before we execute a long running // operation. This can be removed if we refresh the hierarchy in a // separate thread. // Work-araound for http://dev.eclipse.org/bugs/show_bug.cgi?id=30881 processOutstandingEvents(); if (inputElement == null) { clearInput(); } else { fInputElement= inputElement; try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, JavaPlugin.getActiveWorkbenchWindow()); // fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(inputElement, getSite().getWorkbenchWindow()); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$ clearInput(); return; } catch (InterruptedException e) { return; } if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!inputElement.equals(prevInput)) { updateHierarchyViewer(true); } IType root= getSelectableType(inputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); fPagebook.showPage(fTypeMethodsSplitter); } } private void processOutstandingEvents() { Display display= getDisplay(); if (display != null && !display.isDisposed()) display.update(); } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(false); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); if (fMethodsViewer != null) { fMethodsViewer.dispose(); } if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } getSite().getPage().removePartListener(fPartListener); if (fActionGroups != null) fActionGroups.dispose(); if (fWorkingSetActionGroup != null) { fWorkingSetActionGroup.dispose(); } super.dispose(); } /** * Answer the property defined by key. */ public Object getAdapter(Class key) { if (key == IShowInSource.class) { return getShowInSource(); } if (key == IShowInTargetList.class) { return new IShowInTargetList() { public String[] getShowInTargetIds() { return new String[] { JavaUI.ID_PACKAGES, IPageLayout.ID_RES_NAV }; } }; } return super.getAdapter(key); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW); fAllViewers= new TypeHierarchyViewer[3]; fAllViewers[VIEW_ID_SUPER]= superTypesViewer; fAllViewers[VIEW_ID_SUB]= subTypesViewer; fAllViewers[VIEW_ID_TYPE]= vajViewer; int currViewerIndex; try { currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); if (currViewerIndex < 0 || currViewerIndex > 2) { currViewerIndex= VIEW_ID_TYPE; } } catch (NumberFormatException e) { currViewerIndex= VIEW_ID_TYPE; } fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setInput(fAllViewers[i]); } // force the update fCurrentViewerIndex= -1; setView(currViewerIndex); return fViewerbook; } private KeyListener createKeyListener() { return new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F5) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null) { fHierarchyLifeCycle.typeHierarchyChanged(hierarchy); doTypeHierarchyChangedOnViewers(null); } updateHierarchyViewer(false); return; } else if (event.character == SWT.DEL) { if (fCCPActionGroup.getDeleteAction().isEnabled()) fCCPActionGroup.getDeleteAction().run(); return; } } } }; } private void initializeTypesViewer(final TypeHierarchyViewer typesViewer, KeyListener keyListener, String cotextHelpId) { typesViewer.getControl().setVisible(false); typesViewer.getControl().addKeyListener(keyListener); typesViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillTypesViewerContextMenu(typesViewer, menu); } }, cotextHelpId, getSite()); typesViewer.addPostSelectionChangedListener(fSelectionChangedListener); typesViewer.setQualifiedTypeName(isShowQualifiedTypeNames()); typesViewer.setWorkingSetFilter(fWorkingSetActionGroup.getWorkingSetFilter()); } private Control createMethodViewerControl(Composite parent) { fMethodsViewer= new MethodsViewer(parent, fHierarchyLifeCycle, this); fMethodsViewer.initContextMenu(new IMenuListener() { public void menuAboutToShow(IMenuManager menu) { fillMethodsViewerContextMenu(menu); } }, IContextMenuConstants.TARGET_ID_MEMBERS_VIEW, getSite()); fMethodsViewer.addPostSelectionChangedListener(fSelectionChangedListener); Control control= fMethodsViewer.getTable(); control.addKeyListener(createKeyListener()); return control; } private void initDragAndDrop() { Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance() }; int ops= DND.DROP_MOVE | DND.DROP_COPY | DND.DROP_LINK; for (int i= 0; i < fAllViewers.length; i++) { addDragAdapters(fAllViewers[i], ops, transfers); addDropAdapters(fAllViewers[i], ops | DND.DROP_DEFAULT, transfers); } addDragAdapters(fMethodsViewer, ops, transfers); //dnd on empty hierarchy DropTarget dropTarget = new DropTarget(fNoHierarchyShownLabel, ops | DND.DROP_DEFAULT); dropTarget.setTransfer(transfers); dropTarget.addDropListener(new TypeHierarchyTransferDropAdapter(this, fAllViewers[0])); } private void addDropAdapters(AbstractTreeViewer viewer, int ops, Transfer[] transfers){ TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new TypeHierarchyTransferDropAdapter(this, viewer) }; viewer.addDropSupport(ops, transfers, new DelegatingDropAdapter(dropListeners)); } private void addDragAdapters(StructuredViewer viewer, int ops, Transfer[] transfers) { TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(viewer) }; viewer.addDragSupport(ops, transfers, new JdtViewerDragAdapter(viewer, dragListeners)); } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); fWorkingSetActionGroup= new WorkingSetFilterActionGroup(JavaUI.ID_TYPE_HIERARCHY, container.getShell(), fPropertyChangeListener); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ initDragAndDrop(); MenuManager menu= new MenuManager(); menu.add(fFocusOnTypeAction); fNoHierarchyShownLabel.setMenu(menu.createContextMenu(fNoHierarchyShownLabel)); fPagebook.showPage(fNoHierarchyShownLabel); int orientation; try { orientation= fDialogSettings.getInt(DIALOGSTORE_VIEWORIENTATION); if (orientation < 0 || orientation > 2) { orientation= VIEW_ORIENTATION_VERTICAL; } } catch (NumberFormatException e) { orientation= VIEW_ORIENTATION_VERTICAL; } // force the update fCurrentOrientation= -1; // will fill the main tool bar setOrientation(orientation); if (fMemento != null) { // restore state before creating action restoreLinkingEnabled(fMemento); } fToggleLinkingAction= new ToggleLinkingAction(this); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fViewActions.length; i++) { viewMenu.add(fViewActions[i]); } viewMenu.add(new Separator()); fWorkingSetActionGroup.contributeToMenu(viewMenu); viewMenu.add(new Separator()); IMenuManager layoutSubMenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.layout.submenu")); //$NON-NLS-1$ viewMenu.add(layoutSubMenu); for (int i= 0; i < fToggleOrientationActions.length; i++) { layoutSubMenu.add(fToggleOrientationActions[i]); } viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); viewMenu.add(fShowQualifiedTypeNamesAction); viewMenu.add(fToggleLinkingAction); // fill the method viewer toolbar ToolBarManager lowertbmanager= new ToolBarManager(methodViewerToolBar); lowertbmanager.add(fEnableMemberFilterAction); lowertbmanager.add(new Separator()); fMethodsViewer.contributeToToolBar(lowertbmanager); lowertbmanager.update(true); // selection provider int nHierarchyViewers= fAllViewers.length; Viewer[] trackedViewers= new Viewer[nHierarchyViewers + 1]; for (int i= 0; i < nHierarchyViewers; i++) { trackedViewers[i]= fAllViewers[i]; } trackedViewers[nHierarchyViewers]= fMethodsViewer; fSelectionProviderMediator= new SelectionProviderMediator(trackedViewers); IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fSelectionProviderMediator.addSelectionChangedListener(new StatusBarUpdater(slManager)); getSite().setSelectionProvider(fSelectionProviderMediator); getSite().getPage().addPartListener(fPartListener); // see http://bugs.eclipse.org/bugs/show_bug.cgi?id=33657 IJavaElement input= null; //determineInputElement(); if (fMemento != null) { restoreState(fMemento, input); } else if (input != null) { setInputElement(input); } else { setViewerVisibility(false); } WorkbenchHelp.setHelp(fPagebook, IJavaHelpContextIds.TYPE_HIERARCHY_VIEW); fActionGroups= new CompositeActionGroup(new ActionGroup[] { new NewWizardsActionGroup(this.getSite()), new OpenEditorActionGroup(this), new OpenViewActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new GenerateActionGroup(this), new RefactorActionGroup(this), new JavaSearchActionGroup(this) }); fActionGroups.fillActionBars(actionBars); fSelectAllAction= new SelectAllAction(fMethodsViewer); actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), fSelectAllAction); } /** * called from ToggleOrientationAction. * @param orientation VIEW_ORIENTATION_SINGLE, VIEW_ORIENTATION_HORIZONTAL or VIEW_ORIENTATION_VERTICAL */ public void setOrientation(int orientation) { if (fCurrentOrientation != orientation) { boolean methodViewerNeedsUpdate= false; if (fMethodViewerViewForm != null && !fMethodViewerViewForm.isDisposed() && fTypeMethodsSplitter != null && !fTypeMethodsSplitter.isDisposed()) { if (orientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(false); enableMemberFilter(false); updateMethodViewer(null); } else { if (fCurrentOrientation == VIEW_ORIENTATION_SINGLE) { fMethodViewerViewForm.setVisible(true); methodViewerNeedsUpdate= true; } boolean horizontal= orientation == VIEW_ORIENTATION_HORIZONTAL; fTypeMethodsSplitter.setOrientation(horizontal ? SWT.HORIZONTAL : SWT.VERTICAL); } updateMainToolbar(orientation); fTypeMethodsSplitter.layout(); } for (int i= 0; i < fToggleOrientationActions.length; i++) { fToggleOrientationActions[i].setChecked(orientation == fToggleOrientationActions[i].getOrientation()); } fCurrentOrientation= orientation; if (methodViewerNeedsUpdate) { updateMethodViewer(fSelectedType); } fDialogSettings.put(DIALOGSTORE_VIEWORIENTATION, orientation); } } private void updateMainToolbar(int orientation) { IActionBars actionBars= getViewSite().getActionBars(); IToolBarManager tbmanager= actionBars.getToolBarManager(); if (orientation == VIEW_ORIENTATION_HORIZONTAL) { clearMainToolBar(tbmanager); ToolBar typeViewerToolBar= new ToolBar(fTypeViewerViewForm, SWT.FLAT | SWT.WRAP); fillMainToolBar(new ToolBarManager(typeViewerToolBar)); fTypeViewerViewForm.setTopLeft(typeViewerToolBar); } else { fTypeViewerViewForm.setTopLeft(null); fillMainToolBar(tbmanager); } } private void fillMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.add(fHistoryDropDownAction); for (int i= 0; i < fViewActions.length; i++) { tbmanager.add(fViewActions[i]); } tbmanager.update(false); } private void clearMainToolBar(IToolBarManager tbmanager) { tbmanager.removeAll(); tbmanager.update(false); } /** * Creates the context menu for the hierarchy viewers */ private void fillTypesViewerContextMenu(TypeHierarchyViewer viewer, IMenuManager menu) { JavaPlugin.createStandardGroups(menu); menu.appendToGroup(IContextMenuConstants.GROUP_SHOW, new Separator(GROUP_FOCUS)); // viewer entries viewer.contributeToContextMenu(menu); if (fFocusOnSelectionAction.canActionBeAdded()) menu.appendToGroup(GROUP_FOCUS, fFocusOnSelectionAction); menu.appendToGroup(GROUP_FOCUS, fFocusOnTypeAction); fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Creates the context menu for the method viewer */ private void fillMethodsViewerContextMenu(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); // viewer entries fMethodsViewer.contributeToContextMenu(menu); if (fSelectedType != null && fAddStubAction.init(fSelectedType, fMethodsViewer.getSelection())) { menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, fAddStubAction); } fActionGroups.setContext(new ActionContext(getSite().getSelectionProvider().getSelection())); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } /** * Toggles between the empty viewer page and the hierarchy */ private void setViewerVisibility(boolean showHierarchy) { if (showHierarchy) { fViewerbook.showPage(getCurrentViewer().getControl()); } else { fViewerbook.showPage(fEmptyTypesViewer); } } /** * Sets the member filter. <code>null</code> disables member filtering. */ private void setMemberFilter(IMember[] memberFilter) { Assert.isNotNull(fAllViewers); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setMemberFilter(memberFilter); } } private IType getSelectableType(IJavaElement elem) { if (elem.getElementType() != IJavaElement.TYPE) { return null; //(IType) getCurrentViewer().getTreeRootType(); } else { return (IType) elem; } } private void internalSelectType(IMember elem, boolean reveal) { TypeHierarchyViewer viewer= getCurrentViewer(); viewer.removePostSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); viewer.addPostSelectionChangedListener(fSelectionChangedListener); } /** * When the input changed or the hierarchy pane becomes visible, * <code>updateHierarchyViewer<code> brings up the correct view and refreshes * the current tree */ private void updateHierarchyViewer(final boolean doExpand) { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(doExpand); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); if (!isChildVisible(fViewerbook, getCurrentViewer().getControl())) { setViewerVisibility(true); } } else { fEmptyTypesViewer.setText(TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.nodecl", fInputElement.getElementName())); //$NON-NLS-1$ setViewerVisibility(false); } } } private void updateMethodViewer(final IType input) { if (!fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input == fMethodsViewer.getInput()) { if (input != null) { Runnable runnable= new Runnable() { public void run() { fMethodsViewer.refresh(); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); } } else { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } Runnable runnable= new Runnable() { public void run() { fMethodsViewer.setInput(input); // refresh } }; BusyIndicator.showWhile(getDisplay(), runnable); } } } protected void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(true); } else { typeSelectionChanged(e.getSelection()); fSelectAllAction.setEnabled(false); } } private void methodSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (fIsEnableMemberFilter) { IMember[] memberFilter= null; if (nSelected > 0) { memberFilter= new IMember[nSelected]; selected.toArray(memberFilter); } setMemberFilter(memberFilter); updateHierarchyViewer(true); updateTitle(); internalSelectType(fSelectedType, true); } if (nSelected == 1) { revealElementInEditor(selected.get(0), fMethodsViewer); } } } private void typeSelectionChanged(ISelection sel) { if (sel instanceof IStructuredSelection) { List selected= ((IStructuredSelection)sel).toList(); int nSelected= selected.size(); if (nSelected != 0) { List types= new ArrayList(nSelected); for (int i= nSelected-1; i >= 0; i--) { Object elem= selected.get(i); if (elem instanceof IType && !types.contains(elem)) { types.add(elem); } } if (types.size() == 1) { fSelectedType= (IType) types.get(0); updateMethodViewer(fSelectedType); } else if (types.size() == 0) { // method selected, no change } if (nSelected == 1) { revealElementInEditor(selected.get(0), getCurrentViewer()); } } else { fSelectedType= null; updateMethodViewer(null); } } } private void revealElementInEditor(Object elem, Viewer originViewer) { // only allow revealing when the type hierarchy is the active pagae // no revealing after selection events due to model changes if (getSite().getPage().getActivePart() != this) { return; } if (fSelectionProviderMediator.getViewerInFocus() != originViewer) { return; } IEditorPart editorPart= EditorUtility.isOpenInEditor(elem); if (editorPart != null && (elem instanceof IJavaElement)) { getSite().getPage().removePartListener(fPartListener); getSite().getPage().bringToTop(editorPart); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } } private Display getDisplay() { if (fPagebook != null && !fPagebook.isDisposed()) { return fPagebook.getDisplay(); } return null; } private boolean isChildVisible(Composite pb, Control child) { Control[] children= pb.getChildren(); for (int i= 0; i < children.length; i++) { if (children[i] == child && children[i].isVisible()) return true; } return false; } private void updateTitle() { String viewerTitle= getCurrentViewer().getTitle(); String tooltip; String title; if (fInputElement != null) { String[] args= new String[] { viewerTitle, JavaElementLabels.getElementLabel(fInputElement, JavaElementLabels.ALL_DEFAULT) }; title= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.title", args); //$NON-NLS-1$ tooltip= TypeHierarchyMessages.getFormattedString("TypeHierarchyViewPart.tooltip", args); //$NON-NLS-1$ } else { title= viewerTitle; tooltip= viewerTitle; } setTitle(title); setTitleToolTip(tooltip); } private void updateToolbarButtons() { boolean isType= fInputElement instanceof IType; for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; if (action.getViewerIndex() == VIEW_ID_TYPE) { action.setEnabled(fInputElement != null); } else { action.setEnabled(isType); } } } /** * Sets the current view (see view id) * called from ToggleViewAction. Must be called after creation of the viewpart. */ public void setView(int viewerIndex) { Assert.isNotNull(fAllViewers); if (viewerIndex < fAllViewers.length && fCurrentViewerIndex != viewerIndex) { fCurrentViewerIndex= viewerIndex; updateHierarchyViewer(true); if (fInputElement != null) { ISelection currSelection= getCurrentViewer().getSelection(); if (currSelection == null || currSelection.isEmpty()) { internalSelectType(getSelectableType(fInputElement), false); currSelection= getCurrentViewer().getSelection(); } if (!fIsEnableMemberFilter) { typeSelectionChanged(currSelection); } } updateTitle(); fDialogSettings.put(DIALOGSTORE_HIERARCHYVIEW, viewerIndex); getCurrentViewer().getTree().setFocus(); } for (int i= 0; i < fViewActions.length; i++) { ToggleViewAction action= fViewActions[i]; action.setChecked(fCurrentViewerIndex == action.getViewerIndex()); } } /** * Gets the curret active view index. */ public int getViewIndex() { return fCurrentViewerIndex; } private TypeHierarchyViewer getCurrentViewer() { return fAllViewers[fCurrentViewerIndex]; } /** * called from EnableMemberFilterAction. * Must be called after creation of the viewpart. */ public void enableMemberFilter(boolean on) { if (on != fIsEnableMemberFilter) { fIsEnableMemberFilter= on; if (!on) { IType methodViewerInput= (IType) fMethodsViewer.getInput(); setMemberFilter(null); updateHierarchyViewer(true); updateTitle(); if (methodViewerInput != null && getCurrentViewer().isElementShown(methodViewerInput)) { // avoid that the method view changes content by selecting the previous input internalSelectType(methodViewerInput, true); } else if (fSelectedType != null) { // choose a input that exists internalSelectType(fSelectedType, true); updateMethodViewer(fSelectedType); } } else { methodSelectionChanged(fMethodsViewer.getSelection()); } } fEnableMemberFilterAction.setChecked(on); } /** * called from ShowQualifiedTypeNamesAction. Must be called after creation * of the viewpart. */ public void showQualifiedTypeNames(boolean on) { if (fAllViewers == null) { return; } for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setQualifiedTypeName(on); } } private boolean isShowQualifiedTypeNames() { return fShowQualifiedTypeNamesAction.isChecked(); } /** * Called from ITypeHierarchyLifeCycleListener. * Can be called from any thread */ protected void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { if (!fIsVisible) { fNeedRefresh= true; return; } if (fIsRefreshRunnablePosted) { return; } Display display= getDisplay(); if (display != null) { fIsRefreshRunnablePosted= true; display.asyncExec(new Runnable() { public void run() { try { if (fPagebook != null && !fPagebook.isDisposed()) { doTypeHierarchyChangedOnViewers(changedTypes); } } finally { fIsRefreshRunnablePosted= false; } } }); } } protected void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, getSite().getWorkbenchWindow()); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getSite().getShell(), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.title"), TypeHierarchyMessages.getString("TypeHierarchyViewPart.exception.message")); //$NON-NLS-1$ //$NON-NLS-2$ clearInput(); return; } catch (InterruptedException e) { return; } fMethodsViewer.refresh(); updateHierarchyViewer(false); } else { // elements in hierarchy modified Object methodViewerInput= fMethodsViewer.getInput(); fMethodsViewer.refresh(); fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(methodViewerInput)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(methodViewerInput)); if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(false); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { String handleIndentifier= fInputElement.getHandleIdentifier(); if (fInputElement instanceof IType) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) { // for startup performance reasons do not try to recover huge hierarchies handleIndentifier= null; } } memento.putString(TAG_INPUT, handleIndentifier); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fWorkingSetActionGroup.saveState(memento); fMethodsViewer.saveState(memento); saveLinkingEnabled(memento); } private void saveLinkingEnabled(IMemento memento) { memento.putInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, fLinkingEnabled ? 1 : 0); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; fWorkingSetActionGroup.restoreState(memento); String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (input != null && !input.exists()) { input= null; } if (!AllTypesCache.isIndexUpToDate()) { input= null; } } setInputElement(input); Integer viewerIndex= memento.getInteger(TAG_VIEW); if (viewerIndex != null) { setView(viewerIndex.intValue()); } Integer orientation= memento.getInteger(TAG_ORIENTATION); if (orientation != null) { setOrientation(orientation.intValue()); } Integer ratio= memento.getInteger(TAG_RATIO); if (ratio != null) { fTypeMethodsSplitter.setWeights(new int[] { ratio.intValue(), 1000 - ratio.intValue() }); } ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); if (bar != null) { Integer vScroll= memento.getInteger(TAG_VERTICAL_SCROLL); if (vScroll != null) { bar.setSelection(vScroll.intValue()); } } //String selectionId= memento.getString(TAG_SELECTION); // do not restore type hierarchy contents // if (selectionId != null) { // IJavaElement elem= JavaCore.create(selectionId); // if (getCurrentViewer().isElementShown(elem) && elem instanceof IMember) { // internalSelectType((IMember)elem, false); // } // } fMethodsViewer.restoreState(memento); } private void restoreLinkingEnabled(IMemento memento) { Integer val= memento.getInteger(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR); if (val != null) { fLinkingEnabled= val.intValue() != 0; } } /** * view part becomes visible */ protected void visibilityChanged(boolean isVisible) { fIsVisible= isVisible; if (isVisible && fNeedRefresh) { doTypeHierarchyChangedOnViewers(null); } fNeedRefresh= false; } /** * Link selection to active editor. */ protected void editorActivated(IEditorPart editor) { if (!isLinkingEnabled()) { return; } if (fInputElement == null) { // no type hierarchy shown return; } IJavaElement elem= (IJavaElement)editor.getEditorInput().getAdapter(IJavaElement.class); try { TypeHierarchyViewer currentViewer= getCurrentViewer(); if (elem instanceof IClassFile) { IType type= ((IClassFile)elem).getType(); if (currentViewer.isElementShown(type)) { internalSelectType(type, true); updateMethodViewer(type); } } else if (elem instanceof ICompilationUnit) { IType[] allTypes= ((ICompilationUnit)elem).getAllTypes(); for (int i= 0; i < allTypes.length; i++) { if (currentViewer.isElementShown(allTypes[i])) { internalSelectType(allTypes[i], true); updateMethodViewer(allTypes[i]); return; } } } } catch (JavaModelException e) { JavaPlugin.log(e); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return fInputElement; } /** * Returns the <code>IShowInSource</code> for this view. */ protected IShowInSource getShowInSource() { return new IShowInSource() { public ShowInContext getShowInContext() { return new ShowInContext( null, getSite().getSelectionProvider().getSelection()); } }; } boolean isLinkingEnabled() { return fLinkingEnabled; } public void setLinkingEnabled(boolean enabled) { fLinkingEnabled= enabled; PreferenceConstants.getPreferenceStore().setValue(PreferenceConstants.LINK_TYPEHIERARCHY_TO_EDITOR, enabled); if (enabled) { IEditorPart editor = getSite().getPage().getActiveEditor(); if (editor != null) { editorActivated(editor); } } } public void clearNeededRefresh() { fNeedRefresh= false; } }
47,674
Bug 47674 Formatting problem with paste
M5: - create class Bar with this code: public class Bar { void foo() { int i= 1; if (i == 2) { i= 1; } i= 2; } } - select full line "i= 2" and cut to clipboard - paste line inside if-statement Observe: the closing bracket is indented public class Bar { void foo() { int i= 1; if (i == 2) { i= 1; i= 2; } } }
resolved fixed
7586211
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T14:47:28Z
2003-11-27T21:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaAutoIndentStrategy.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Nikolay Metchev - Fixed bug 29909 *******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.BadPartitioningException; import org.eclipse.jface.text.DefaultAutoIndentStrategy; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.DocumentCommand; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.ITypedRegion; import org.eclipse.jface.text.Region; import org.eclipse.jface.text.TextUtilities; import org.eclipse.jface.text.rules.DefaultPartitioner; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.texteditor.ITextEditorExtension3; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.DoStatement; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ForStatement; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.WhileStatement; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.corext.Assert; import org.eclipse.jdt.internal.corext.dom.NodeFinder; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.text.FastJavaPartitionScanner; import org.eclipse.jdt.internal.ui.text.IJavaPartitions; import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner; import org.eclipse.jdt.internal.ui.text.JavaIndenter; import org.eclipse.jdt.internal.ui.text.Symbols; /** * Auto indent strategy sensitive to brackets. */ public class JavaAutoIndentStrategy extends DefaultAutoIndentStrategy { private static class CompilationUnitInfo { public char[] buffer; public int delta; public CompilationUnitInfo(char[] buffer, int delta) { this.buffer= buffer; this.delta= delta; } } private boolean fCloseBrace; private boolean fIsSmartMode; private String fPartitioning; /** * Creates a new Java auto indent strategy for the given document partitioning. * * @param partitioning the document partitioning */ public JavaAutoIndentStrategy(String partitioning) { fPartitioning= partitioning; } private int getBracketCount(IDocument d, int startOffset, int endOffset, boolean ignoreCloseBrackets) throws BadLocationException { int bracketCount= 0; while (startOffset < endOffset) { char curr= d.getChar(startOffset); startOffset++; switch (curr) { case '/' : if (startOffset < endOffset) { char next= d.getChar(startOffset); if (next == '*') { // a comment starts, advance to the comment end startOffset= getCommentEnd(d, startOffset + 1, endOffset); } else if (next == '/') { // '//'-comment: nothing to do anymore on this line startOffset= endOffset; } } break; case '*' : if (startOffset < endOffset) { char next= d.getChar(startOffset); if (next == '/') { // we have been in a comment: forget what we read before bracketCount= 0; startOffset++; } } break; case '{' : bracketCount++; ignoreCloseBrackets= false; break; case '}' : if (!ignoreCloseBrackets) { bracketCount--; } break; case '"' : case '\'' : startOffset= getStringEnd(d, startOffset, endOffset, curr); break; default : } } return bracketCount; } // ----------- bracket counting ------------------------------------------------------ private int getCommentEnd(IDocument d, int offset, int endOffset) throws BadLocationException { while (offset < endOffset) { char curr= d.getChar(offset); offset++; if (curr == '*') { if (offset < endOffset && d.getChar(offset) == '/') { return offset + 1; } } } return endOffset; } private String getIndentOfLine(IDocument d, int line) throws BadLocationException { if (line > -1) { int start= d.getLineOffset(line); int end= start + d.getLineLength(line) - 1; int whiteEnd= findEndOfWhiteSpace(d, start, end); return d.get(start, whiteEnd - start); } else { return ""; //$NON-NLS-1$ } } private int getStringEnd(IDocument d, int offset, int endOffset, char ch) throws BadLocationException { while (offset < endOffset) { char curr= d.getChar(offset); offset++; if (curr == '\\') { // ignore escaped characters offset++; } else if (curr == ch) { return offset; } } return endOffset; } private void smartIndentAfterClosingBracket(IDocument d, DocumentCommand c) { if (c.offset == -1 || d.getLength() == 0) return; try { int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); int start= d.getLineOffset(line); int whiteend= findEndOfWhiteSpace(d, start, c.offset); JavaHeuristicScanner scanner= new JavaHeuristicScanner(d); JavaIndenter indenter= new JavaIndenter(d, scanner); // shift only when line does not contain any text up to the closing bracket if (whiteend == c.offset) { // evaluate the line with the opening bracket that matches out closing bracket int reference= indenter.findReferencePosition(c.offset, false, true, false, false); int indLine= d.getLineOfOffset(reference); if (indLine != -1 && indLine != line) { // take the indent of the found line StringBuffer replaceText= new StringBuffer(getIndentOfLine(d, indLine)); // add the rest of the current line including the just added close bracket replaceText.append(d.get(whiteend, c.offset - whiteend)); replaceText.append(c.text); // modify document command c.length += c.offset - start; c.offset= start; c.text= replaceText.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } } private void smartIndentAfterOpeningBracket(IDocument d, DocumentCommand c) { if (c.offset < 1 || d.getLength() == 0) return; JavaHeuristicScanner scanner= new JavaHeuristicScanner(d); int p= (c.offset == d.getLength() ? c.offset - 1 : c.offset); try { // current line int line= d.getLineOfOffset(p); int lineOffset= d.getLineOffset(line); // line of last javacode int pos= scanner.findNonWhitespaceBackward(p, JavaHeuristicScanner.UNBOUND); if (pos == -1) return; int lastLine= d.getLineOfOffset(pos); // only shift if the last java line is further up and is a braceless block candidate if (lastLine < line) { if (scanner.isBracelessBlockStart(pos + 1, JavaHeuristicScanner.UNBOUND)) { // if the last line was a braceless block candidate, we have indented // after the new line. This has to be undone as we *are* starting a block // on the new line StringBuffer replace= new StringBuffer(getIndentOfLine(d, lastLine)); c.length += replace.length(); replace.append(c.text); c.offset= lineOffset; c.text= replace.toString(); } } } catch (BadLocationException e) { JavaPlugin.log(e); } } private void smartIndentAfterNewLine(IDocument d, DocumentCommand c) { JavaHeuristicScanner scanner= new JavaHeuristicScanner(d); JavaIndenter indenter= new JavaIndenter(d, scanner); StringBuffer indent= indenter.computeIndentation(c.offset); if (indent == null) indent= new StringBuffer(); //$NON-NLS-1$ int docLength= d.getLength(); if (c.offset == -1 || docLength == 0) return; try { int p= (c.offset == docLength ? c.offset - 1 : c.offset); int line= d.getLineOfOffset(p); StringBuffer buf= new StringBuffer(c.text + indent); IRegion reg= d.getLineInformation(line); int lineEnd= reg.getOffset() + reg.getLength(); int contentStart= findEndOfWhiteSpace(d, c.offset, lineEnd); c.length= Math.max(contentStart - c.offset, 0); int start= reg.getOffset(); ITypedRegion region= TextUtilities.getPartition(d, fPartitioning, start); if (IJavaPartitions.JAVA_DOC.equals(region.getType())) start= d.getLineInformationOfOffset(region.getOffset()).getOffset(); if (getBracketCount(d, start, c.offset, true) > 0 && closeBrace() && !isClosed(d, c.offset, c.length)) { c.caretOffset= c.offset + buf.length(); c.shiftsCaret= false; // copy old content of line behind insertion point to new line // unless we think we are inserting an anonymous type definition if (c.offset == 0 || !(computeAnonymousPosition(d, c.offset - 1, fPartitioning, lineEnd) != -1)) { if (lineEnd - contentStart > 0) { c.length= lineEnd - c.offset; buf.append(d.get(contentStart, lineEnd - contentStart).toCharArray()); } } buf.append(getLineDelimiter(d)); StringBuffer reference= indenter.getReferenceIndentation(c.offset); if (reference != null) buf.append(reference); buf.append('}'); } c.text= buf.toString(); } catch (BadLocationException e) { JavaPlugin.log(e); } } /** * Computes an insert position for an opening brace if <code>offset</code> maps to a position in * <code>document</code> with a expression in parenthesis that will take a block after the closing parenthesis. * * @param document the document being modified * @param offset the offset of the caret position, relative to the line start. * @param partitioning the document partitioning * @param max the max position * @return an insert position relative to the line start if <code>line</code> contains a parenthesized expression that can be followed by a block, -1 otherwise */ private static int computeAnonymousPosition(IDocument document, int offset, String partitioning, int max) { // find the opening parenthesis for every closing parenthesis on the current line after offset // return the position behind the closing parenthesis if it looks like a method declaration // or an expression for an if, while, for, catch statement JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); int pos= offset; int length= max; int scanTo= scanner.scanForward(pos, length, '}'); if (scanTo == -1) scanTo= length; int closingParen= findClosingParenToLeft(scanner, pos) - 1; while (true) { int startScan= closingParen + 1; closingParen= scanner.scanForward(startScan, scanTo, ')'); if (closingParen == -1) break; int openingParen= scanner.findOpeningPeer(closingParen - 1, '(', ')'); // no way an expression at the beginning of the document can mean anything if (openingParen < 1) break; // only select insert positions for parenthesis currently embracing the caret if (openingParen > pos) continue; if (looksLikeAnonymousClassDef(document, partitioning, scanner, openingParen - 1)) return closingParen + 1; } return -1; } /** * Finds a closing parenthesis to the left of <code>position</code> in document, where that parenthesis is only * separated by whitespace from <code>position</code>. If no such parenthesis can be found, <code>position</code> is returned. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return the position of a closing parenthesis left to <code>position</code> separated only by whitespace, or <code>position</code> if no parenthesis can be found */ private static int findClosingParenToLeft(JavaHeuristicScanner scanner, int position) { if (position < 1) return position; if (scanner.previousToken(position - 1, JavaHeuristicScanner.UNBOUND) == Symbols.TokenRPAREN) return scanner.getPosition() + 1; return position; } /** * Checks whether the content of <code>document</code> in the range (<code>offset</code>, <code>length</code>) * contains the <code>new</code> keyword. * * @param document the document being modified * @param offset the first character position in <code>document</code> to be considered * @param length the length of the character range to be considered * @param partitioning the document partitioning * @return <code>true</code> if the specified character range contains a <code>new</code> keyword, <code>false</code> otherwise. */ private static boolean isNewMatch(IDocument document, int offset, int length, String partitioning) { Assert.isTrue(length >= 0); Assert.isTrue(offset >= 0); Assert.isTrue(offset + length < document.getLength() + 1); try { String text= document.get(offset, length); int pos= text.indexOf("new"); //$NON-NLS-1$ while (pos != -1 && !isDefaultPartition(document, pos + offset, partitioning)) pos= text.indexOf("new", pos + 2); //$NON-NLS-1$ if (pos < 0) return false; if (pos != 0 && Character.isJavaIdentifierPart(text.charAt(pos - 1))) return false; if (pos + 3 < length && Character.isJavaIdentifierPart(text.charAt(pos + 3))) return false; return true; } catch (BadLocationException e) { } return false; } /** * Checks whether the content of <code>document</code> at <code>position</code> looks like an * anonymous class definition. <code>position</code> must be to the left of the opening * parenthesis of the definition's parameter list. * * @param document the document being modified * @param position the first character position in <code>document</code> to be considered * @param partitioning the document partitioning * @return <code>true</code> if the content of <code>document</code> looks like an anonymous class definition, <code>false</code> otherwise */ private static boolean looksLikeAnonymousClassDef(IDocument document, String partitioning, JavaHeuristicScanner scanner, int position) { int previousCommaOrParen= scanner.scanBackward(position - 1, JavaHeuristicScanner.UNBOUND, new char[] {',', '('}); if (previousCommaOrParen == -1 || position < previousCommaOrParen + 5) // 2 for borders, 3 for "new" return false; if (isNewMatch(document, previousCommaOrParen + 1, position - previousCommaOrParen - 2, partitioning)) return true; return false; } /** * Checks whether <code>position</code> resides in a default (Java) partition of <code>document</code>. * * @param document the document being modified * @param position the position to be checked * @param partitioning the document partitioning * @return <code>true</code> if <code>position</code> is in the default partition of <code>document</code>, <code>false</code> otherwise */ private static boolean isDefaultPartition(IDocument document, int position, String partitioning) { Assert.isTrue(position >= 0); Assert.isTrue(position <= document.getLength()); try { ITypedRegion region= TextUtilities.getPartition(document, partitioning, position); return region.getType().equals(IDocument.DEFAULT_CONTENT_TYPE); } catch (BadLocationException e) { } return false; } private boolean isClosed(IDocument document, int offset, int length) { CompilationUnitInfo info= getCompilationUnitForMethod(document, offset, fPartitioning); if (info == null) return false; CompilationUnit compilationUnit= null; try { compilationUnit= AST.parseCompilationUnit(info.buffer); } catch (ArrayIndexOutOfBoundsException x) { // work around for parser problem return false; } IProblem[] problems= compilationUnit.getProblems(); for (int i= 0; i != problems.length; ++i) { if (problems[i].getID() == IProblem.UnmatchedBracket) return true; } final int relativeOffset= offset - info.delta; ASTNode node= NodeFinder.perform(compilationUnit, relativeOffset, length); if (node == null) return false; if (length == 0) { while (node != null && (relativeOffset == node.getStartPosition() || relativeOffset == node.getStartPosition() + node.getLength())) node= node.getParent(); } switch (node.getNodeType()) { case ASTNode.BLOCK: return areBlocksConsistent(document, offset, fPartitioning); case ASTNode.IF_STATEMENT: { IfStatement ifStatement= (IfStatement) node; Expression expression= ifStatement.getExpression(); IRegion expressionRegion= createRegion(expression, info.delta); Statement thenStatement= ifStatement.getThenStatement(); IRegion thenRegion= createRegion(thenStatement, info.delta); // between expression and then statement if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= thenRegion.getOffset()) return thenStatement != null; Statement elseStatement= ifStatement.getElseStatement(); IRegion elseRegion= createRegion(elseStatement, info.delta); IRegion elseToken= null; if (elseStatement != null) { int sourceOffset= thenRegion.getOffset() + thenRegion.getLength(); int sourceLength= elseRegion.getOffset() - sourceOffset; elseToken= getToken(document, new Region(sourceOffset, sourceLength), ITerminalSymbols.TokenNameelse); } // between 'else' keyword and else statement if (elseToken.getOffset() + elseToken.getLength() <= offset && offset + length < elseRegion.getOffset()) return elseStatement != null; } break; case ASTNode.WHILE_STATEMENT: case ASTNode.FOR_STATEMENT: { Expression expression= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getExpression() : ((ForStatement) node).getExpression(); IRegion expressionRegion= createRegion(expression, info.delta); Statement body= node.getNodeType() == ASTNode.WHILE_STATEMENT ? ((WhileStatement) node).getBody() : ((ForStatement) node).getBody(); IRegion bodyRegion= createRegion(body, info.delta); // between expression and body statement if (expressionRegion.getOffset() + expressionRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset()) return body != null; } break; case ASTNode.DO_STATEMENT: { DoStatement doStatement= (DoStatement) node; IRegion doRegion= createRegion(doStatement, info.delta); Statement body= doStatement.getBody(); IRegion bodyRegion= createRegion(body, info.delta); if (doRegion.getOffset() + doRegion.getLength() <= offset && offset + length <= bodyRegion.getOffset()) return body != null; } break; } return true; } private static String getLineDelimiter(IDocument document) { try { if (document.getNumberOfLines() > 1) return document.getLineDelimiter(0); } catch (BadLocationException e) { JavaPlugin.log(e); } return System.getProperty("line.separator"); //$NON-NLS-1$ } private static void smartPaste(IDocument document, DocumentCommand command) { try { JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); JavaIndenter indenter= new JavaIndenter(document, scanner); int offset= command.offset; // reference position to get the indent from int refPos= indenter.findReferencePosition(offset); if (refPos == JavaHeuristicScanner.NOT_FOUND) return; IRegion region= document.getLineInformationOfOffset(refPos); int lineOffset= region.getOffset(); // get the base indentation from the reference position int endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset, JavaHeuristicScanner.UNBOUND); if (endOfWS == JavaHeuristicScanner.NOT_FOUND) endOfWS= lineOffset; String baseIndent= document.get(lineOffset, endOfWS - lineOffset); if (refPos == JavaHeuristicScanner.NOT_FOUND) return; // eat any WS before the insertion to the beginning of the line region= document.getLineInformationOfOffset(offset); String notSelected= document.get(region.getOffset(), offset - region.getOffset()); if (notSelected.trim().length() == 0) { command.length += notSelected.length(); command.offset= region.getOffset(); } // prefix: the part we need for formatting but won't paste String prefix= baseIndent + document.get(refPos, command.offset - refPos); Document temp= new Document(prefix + command.text); // eat any WS after the insertion, up to the delimiter, if the pasted text ends with // a newline (with optional WS on the new line). region= temp.getLineInformation(temp.getNumberOfLines() - 1); boolean eatAfterSpace= temp.get(region.getOffset(), region.getLength()).trim().length() == 0; String afterContent= new String(); if (eatAfterSpace) { int selectionEnd= command.offset + command.length; region= document.getLineInformationOfOffset(selectionEnd); endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(selectionEnd, region.getOffset() + region.getLength()); if (endOfWS != JavaHeuristicScanner.NOT_FOUND) { int token= scanner.nextToken(selectionEnd, region.getOffset() + region.getLength()); if (token != Symbols.TokenEOF && token != Symbols.TokenCASE) { // doesn't work nicely with case command.length += endOfWS - selectionEnd; afterContent= document.get(endOfWS, scanner.getPosition() - endOfWS); } } else { // simulate something to get the indentation command.length += region.getOffset() + region.getLength() - selectionEnd; afterContent= "x"; //$NON-NLS-1$ } } // add context behind the insertion temp.replace(temp.getLength(), 0, afterContent); scanner= new JavaHeuristicScanner(temp); indenter= new JavaIndenter(temp, scanner); String[] types= new String[] { IJavaPartitions.JAVA_DOC, IJavaPartitions.JAVA_MULTI_LINE_COMMENT, IJavaPartitions.JAVA_SINGLE_LINE_COMMENT, IJavaPartitions.JAVA_STRING, IJavaPartitions.JAVA_CHARACTER, IDocument.DEFAULT_CONTENT_TYPE }; DefaultPartitioner partitioner= new DefaultPartitioner(new FastJavaPartitionScanner(), types); partitioner.connect(temp); temp.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner); int lines= temp.getNumberOfLines(); for (int l= document.computeNumberOfLines(prefix); l < lines; l++) { // we don't change the number of lines while adding indents IRegion r= temp.getLineInformation(l); lineOffset= r.getOffset(); int lineLength= r.getLength(); if (lineLength == 0) // don't format empty lines continue; if (lineOffset < temp.getLength() - 1) { // special single line comment handling: if comment starts at the start of the line, leave it alone. String s= temp.get(lineOffset, 2); if ("//".equals(s)) { //$NON-NLS-1$ continue; } } StringBuffer indent= indenter.computeIndentation(lineOffset); if (indent == null) // bail out return; // add single character for *-ed multiline comments ITypedRegion partition= temp.getPartition(IJavaPartitions.JAVA_PARTITIONING, lineOffset); String type= partition.getType(); if (type.equals(IJavaPartitions.JAVA_DOC) || type.equals(IJavaPartitions.JAVA_MULTI_LINE_COMMENT)) if (partition.getOffset() != lineOffset) // not for first line indent.append(' '); endOfWS= scanner.findNonWhitespaceForwardInAnyPartition(lineOffset, lineOffset + lineLength); if (endOfWS == JavaHeuristicScanner.NOT_FOUND) endOfWS= lineOffset + lineLength; int wsLen= Math.max(endOfWS - lineOffset, 0); temp.replace(lineOffset, wsLen, indent.toString()); } temp.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, null); partitioner.disconnect(); command.text= temp.get(prefix.length(), temp.getLength() - prefix.length() - afterContent.length()); } catch (BadLocationException e) { JavaPlugin.log(e); } catch (BadPartitioningException e) { JavaPlugin.log(e); } } private boolean isLineDelimiter(IDocument document, String text) { String[] delimiters= document.getLegalLineDelimiters(); if (delimiters != null) return TextUtilities.equals(delimiters, text) > -1; return false; } private void smartIndentAfterBlockDelimiter(IDocument document, DocumentCommand command) { if (command.text.charAt(0) == '}') smartIndentAfterClosingBracket(document, command); else if (command.text.charAt(0) == '{') smartIndentAfterOpeningBracket(document, command); } /* * @see org.eclipse.jface.text.IAutoIndentStrategy#customizeDocumentCommand(org.eclipse.jface.text.IDocument, org.eclipse.jface.text.DocumentCommand) */ public void customizeDocumentCommand(IDocument d, DocumentCommand c) { clearCachedValues(); if (!isSmartMode() || c.doit == false) return; if (c.length == 0 && c.text != null && isLineDelimiter(d, c.text)) smartIndentAfterNewLine(d, c); else if (c.text.length() == 1) smartIndentAfterBlockDelimiter(d, c); else if (c.text.length() > 1 && getPreferenceStore().getBoolean(PreferenceConstants.EDITOR_SMART_PASTE)) smartPaste(d, c); } private static IPreferenceStore getPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } private boolean closeBrace() { return fCloseBrace; } private boolean isSmartMode() { return fIsSmartMode; } private void clearCachedValues() { IPreferenceStore preferenceStore= getPreferenceStore(); fCloseBrace= preferenceStore.getBoolean(PreferenceConstants.EDITOR_CLOSE_BRACES); fIsSmartMode= computeSmartMode(); } private boolean computeSmartMode() { IWorkbenchPage page= JavaPlugin.getActivePage(); if (page != null) { IEditorPart part= page.getActiveEditor(); if (part instanceof ITextEditorExtension3) { ITextEditorExtension3 extension= (ITextEditorExtension3) part; return extension.getInsertMode() == ITextEditorExtension3.SMART_INSERT; } } return false; } private static CompilationUnitInfo getCompilationUnitForMethod(IDocument document, int offset, String partitioning) { try { JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); IRegion sourceRange= scanner.findSurroundingBlock(offset); if (sourceRange == null) return null; String source= document.get(sourceRange.getOffset(), sourceRange.getLength()); StringBuffer contents= new StringBuffer(); contents.append("class ____C{void ____m()"); //$NON-NLS-1$ final int methodOffset= contents.length(); contents.append(source); contents.append('}'); char[] buffer= contents.toString().toCharArray(); return new CompilationUnitInfo(buffer, sourceRange.getOffset() - methodOffset); } catch (BadLocationException e) { JavaPlugin.log(e); } return null; } private static boolean areBlocksConsistent(IDocument document, int offset, String partitioning) { if (offset < 1 || offset >= document.getLength()) return false; int begin= offset; int end= offset - 1; JavaHeuristicScanner scanner= new JavaHeuristicScanner(document); while (true) { begin= scanner.findOpeningPeer(begin - 1, '{', '}'); end= scanner.findClosingPeer(end + 1, '{', '}'); if (begin == -1 && end == -1) return true; if (begin == -1 || end == -1) return false; } } private static IRegion createRegion(ASTNode node, int delta) { return node == null ? null : new Region(node.getStartPosition() + delta, node.getLength()); } private static IRegion getToken(IDocument document, IRegion scanRegion, int tokenId) { try { final String source= document.get(scanRegion.getOffset(), scanRegion.getLength()); IScanner scanner= ToolFactory.createScanner(false, false, false, false); scanner.setSource(source.toCharArray()); int id= scanner.getNextToken(); while (id != ITerminalSymbols.TokenNameEOF && id != tokenId) id= scanner.getNextToken(); if (id == ITerminalSymbols.TokenNameEOF) return null; int tokenOffset= scanner.getCurrentTokenStartPosition(); int tokenLength= scanner.getCurrentTokenEndPosition() + 1 - tokenOffset; // inclusive end return new Region(tokenOffset + scanRegion.getOffset(), tokenLength); } catch (InvalidInputException x) { return null; } catch (BadLocationException x) { return null; } } }
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAddRecursive1_in.java
package p; public class A { int i; void m(int i) {this.i = i;} } class Super extends A { void m(int i) { super.m(1); } } class Recursive extends A { void m(int i) { if (true) m(i); } } class ThisRecursive extends A { void m(int i) { this.m(i); } } class AlmostRecursive extends A { void m(int i) { new A().m(i); } } class RecursiveOrNot extends A { void m(int i) { new RecursiveOrNot().m(i); } } class NonRecursive extends A { void m(int i) { int k= i; } } class Calling extends A { void bar() { m(17); } } class Calling2 { void bar() { new A().m(17); } } class Calling3 { void bar() { new Recursive().m(17); } }
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testAddRecursive1_out.java
package p; public class A { int i; void m(int i, boolean bool) {this.i = i;} } class Super extends A { void m(int i, boolean bool) { super.m(1, bool); } } class Recursive extends A { void m(int i, boolean bool) { if (true) m(i, bool); } } class ThisRecursive extends A { void m(int i, boolean bool) { this.m(i, bool); } } class AlmostRecursive extends A { void m(int i, boolean bool) { new A().m(i, true); } } class RecursiveOrNot extends A { void m(int i, boolean bool) { new RecursiveOrNot().m(i, bool); } } class NonRecursive extends A { void m(int i, boolean bool) { int k= i; } } class Calling extends A { void bar() { m(17, true); } } class Calling2 { void bar() { new A().m(17, true); } } class Calling3 { void bar() { new Recursive().m(17, true); } }
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testInStatic01_in.java
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testInStatic01_out.java
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testInStatic02_in.java
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/resources/ChangeSignature/canModify/A_testInStatic02_out.java
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui.tests.refactoring/test
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
cases/org/eclipse/jdt/ui/tests/refactoring/ChangeSignatureTests.java
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
org.eclipse.jdt.ui/core
47,062
Bug 47062 Change method signature: Refactor fails for methods/ctors used in static initializers [refactoring]
I have type-safe enum code similar to the class below. If I try to make any change to the constructor or static method using "Change Method Signature", the operation fails with "Internal error while creating a change object". This only happens when the method in question is called from a static initializer as in the example. Using build 200311190010. public class Example { /* This block breaks refactoring on constructor or factory. */ public static final Example A = new Example("A", "A"); public static final Example B = Example.getExample("B", "B"); /* This block breaks refactoring on constructor or factory. */ public static final Example C; public static final Example D; static { C = new Example("C", "C"); D = Example.getExample("D", "D"); } public Example(String arg1, String arg2) { } public static Example getExample(String arg1, String arg2) { return new Example(arg1, arg2); } } *** Error Log: !SESSION Nov 20, 2003 09:31:18.796 -------------------------------------------- - java.version=1.4.2_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 D:\workspace\axiope -install file:C:/eclipse/ !ENTRY org.eclipse.jdt.ui 4 10001 Nov 20, 2003 09:31:18.796 !MESSAGE Internal Error !STACK 0 java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:283) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.createChange (RefactoringWizard.java:377) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:297) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.computeUserInputSucce ssorPage(RefactoringWizard.java:293) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.getNextPage (UserInputWizardPage.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.previewPressed (RefactoringWizardDialog2.java:418) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.access$3 (RefactoringWizardDialog2.java:416) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2 $1.widgetSelected(RefactoringWizardDialog2.java:547) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.jface.window.Window.runEventLoop(Window.java:583) at org.eclipse.jface.window.Window.open(Window.java:563) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.ui.actions.ModifyParametersAction.startRefactoring (ModifyParametersAction.java:180) at org.eclipse.jdt.ui.actions.ModifyParametersAction.run (ModifyParametersAction.java:124) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2187) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1877) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:858) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:461) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.core.launcher.Main.basicRun(Main.java:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.isRecursiveReference(ChangeSignatureRefactoring.java:1401) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.reshuffleElements(ChangeSignatureRefactoring.java:1162) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateReferenceNode(ChangeSignatureRefactoring.java:1156) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.updateMethodOccurrenceNode(ChangeSignatureRefactoring.java:987) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.createChangeManager(ChangeSignatureRefactoring.java:966) at org.eclipse.jdt.internal.corext.refactoring.structure.ChangeSignatureRefactorin g.checkInput(ChangeSignatureRefactoring.java:521) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run (ModalContext.java:101)
resolved fixed
6e86b02
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:14:01Z
2003-11-20T09:20:00Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ChangeSignatureRefactoring.java
47,875
Bug 47875 Java search: too many cascading menus
- remove everything except reference. Inline reference in main menu - make it work in progress (per default enabled)
resolved fixed
32c5937
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:28:08Z
2003-12-02T10:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/WorkInProgressPreferencePage.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.preferences; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.texteditor.ExtendedTextEditorPreferenceConstants; import org.eclipse.ui.texteditor.quickdiff.QuickDiff; import org.eclipse.ui.texteditor.quickdiff.ReferenceProviderDescriptor; import org.eclipse.jdt.ui.PreferenceConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Preference page for work in progress. */ public class WorkInProgressPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { /** prefix for resources */ private static final String PREFIX= "WorkInProgress."; //$NON-NLS-1$ public final static String PREF_FORMATTER= "use_new_formatter"; //$NON-NLS-1$ /** * All FieldEditors except <code>smartTyping</code>, whose enable state * is controlled by the smartTyping preference. */ private Set fSmartTypingItems= new HashSet(); private List fCheckBoxes; private List fRadioButtons; private List fTextControls; /** List for the reference provider default. */ private org.eclipse.swt.widgets.List fQuickDiffProviderList; /** The reference provider default's list model. */ private String[][] fQuickDiffProviderListModel; /** Button controlling default setting of the selected reference provider. */ private Button fSetDefaultButton; /** * creates a new preference page. */ public WorkInProgressPreferencePage() { setPreferenceStore(getPreferenceStore()); fRadioButtons= new ArrayList(); fCheckBoxes= new ArrayList(); fTextControls= new ArrayList(); List providers= new QuickDiff().getReferenceProviderDescriptors(); fQuickDiffProviderListModel= createQuickDiffReferenceListModel(providers); } private String[][] createQuickDiffReferenceListModel(List providers) { ArrayList listModelItems= new ArrayList(); for (Iterator it= providers.iterator(); it.hasNext();) { ReferenceProviderDescriptor provider= (ReferenceProviderDescriptor) it.next(); String label= provider.getLabel(); int i= label.indexOf('&'); while (i >= 0) { if (i < label.length()) label= label.substring(0, i) + label.substring(i+1); else label.substring(0, i); i= label.indexOf('&'); } listModelItems.add(new String[] { provider.getId(), label }); } String[][] items= new String[listModelItems.size()][]; listModelItems.toArray(items); return items; } private void handleProviderListSelection() { int i= fQuickDiffProviderList.getSelectionIndex(); boolean b= getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0]); fSetDefaultButton.setEnabled(!b); } private Button addCheckBox(Composite parent, String label, String key) { GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); Button button= new Button(parent, SWT.CHECK); button.setText(label); button.setData(key); button.setLayoutData(gd); button.setSelection(getPreferenceStore().getBoolean(key)); fCheckBoxes.add(button); return button; } /* * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { super.createControl(parent); WorkbenchHelp.setHelp(getControl(), "WORK_IN_PROGRESS_PREFERENCE_PAGE"); //$NON-NLS-1$ } protected Control createContents(Composite parent) { initializeDialogUnits(parent); Composite result= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN); layout.marginWidth= 0; layout.verticalSpacing= convertVerticalDLUsToPixels(10); layout.horizontalSpacing= convertHorizontalDLUsToPixels(IDialogConstants.HORIZONTAL_SPACING); result.setLayout(layout); Group group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "editor")); //$NON-NLS-1$ addCheckBox(group, PreferencesMessages.getString(PREFIX + "markOccurrences"), PreferenceConstants.EDITOR_MARK_OCCURRENCES); //$NON-NLS-1$ createSpacer(group, 1); Label label= new Label(group, SWT.NONE); label.setText(PreferencesMessages.getString(PREFIX + "smartTyping.label")); //$NON-NLS-1$ Button button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartSemicolon"), PreferenceConstants.EDITOR_SMART_SEMICOLON); //$NON-NLS-1$ fSmartTypingItems.add(button); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartOpeningBrace"), PreferenceConstants.EDITOR_SMART_OPENING_BRACE); //$NON-NLS-1$ fSmartTypingItems.add(button); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "smartTyping.smartTab"), PreferenceConstants.EDITOR_SMART_TAB); //$NON-NLS-1$ fSmartTypingItems.add(button); /* line change bar */ group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "quickdiff")); //$NON-NLS-1$ Label l= new Label(group, SWT.LEFT ); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "showQuickDiffPerDefault"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_ALWAYS_ON); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickdiff.characterMode"), ExtendedTextEditorPreferenceConstants.QUICK_DIFF_CHARACTER_MODE); //$NON-NLS-1$ l= new Label(group, SWT.LEFT ); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.heightHint= convertHeightInCharsToPixels(1) / 2; l.setLayoutData(gd); l= new Label(group, SWT.LEFT); l.setText(PreferencesMessages.getString(PREFIX + "quickdiff.referenceprovidertitle")); //$NON-NLS-1$ gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; l.setLayoutData(gd); Composite editorComposite= new Composite(group, SWT.NONE); layout= new GridLayout(); layout.numColumns= 2; layout.marginHeight= 0; layout.marginWidth= 0; editorComposite.setLayout(layout); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gd.horizontalSpan= 2; editorComposite.setLayoutData(gd); fQuickDiffProviderList= new org.eclipse.swt.widgets.List(editorComposite, SWT.SINGLE | SWT.V_SCROLL | SWT.BORDER); gd= new GridData(GridData.VERTICAL_ALIGN_BEGINNING | GridData.FILL_HORIZONTAL); gd.heightHint= convertHeightInCharsToPixels(4); fQuickDiffProviderList.setLayoutData(gd); Composite stylesComposite= new Composite(editorComposite, SWT.NONE); layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 2; stylesComposite.setLayout(layout); stylesComposite.setLayoutData(new GridData(GridData.FILL_BOTH)); fSetDefaultButton= new Button(stylesComposite, SWT.PUSH); fSetDefaultButton.setText(PreferencesMessages.getString(PREFIX + "quickdiff.setDefault")); //$NON-NLS-1$ gd= new GridData(GridData.FILL_HORIZONTAL); gd.horizontalAlignment= GridData.BEGINNING; gd.horizontalSpan= 2; fSetDefaultButton.setLayoutData(gd); fQuickDiffProviderList.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { handleProviderListSelection(); } }); fSetDefaultButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { // do nothing } public void widgetSelected(SelectionEvent e) { int i= fQuickDiffProviderList.getSelectionIndex(); for (int j= 0; j < fQuickDiffProviderListModel.length; j++) { if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[j][0])) { fQuickDiffProviderList.remove(j); fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1], j); } if (i == j) { fQuickDiffProviderList.remove(j); fQuickDiffProviderList.add(fQuickDiffProviderListModel[j][1] + " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"), j); //$NON-NLS-1$//$NON-NLS-2$ } } fSetDefaultButton.setEnabled(false); fQuickDiffProviderList.setSelection(i); fQuickDiffProviderList.redraw(); getPreferenceStore().setValue(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER, fQuickDiffProviderListModel[i][0]); } }); for (int i= 0; i < fQuickDiffProviderListModel.length; i++) { String sLabel= fQuickDiffProviderListModel[i][1]; if (getPreferenceStore().getString(ExtendedTextEditorPreferenceConstants.QUICK_DIFF_DEFAULT_PROVIDER).equals(fQuickDiffProviderListModel[i][0])) sLabel += " " + PreferencesMessages.getString(PREFIX + "quickdiff.defaultlabel"); //$NON-NLS-1$ //$NON-NLS-2$ fQuickDiffProviderList.add(sLabel); } fQuickDiffProviderList.getDisplay().asyncExec(new Runnable() { public void run() { if (fQuickDiffProviderList != null && !fQuickDiffProviderList.isDisposed()) { fQuickDiffProviderList.select(0); handleProviderListSelection(); } } }); group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "quickassist.group")); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "quickassist.option"), PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB); //$NON-NLS-1$ //$NON-NLS-2$ group= new Group(result, SWT.NONE); group.setLayout(new GridLayout()); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setText(PreferencesMessages.getString(PREFIX + "formatter")); //$NON-NLS-1$ button= addCheckBox(group, PreferencesMessages.getString(PREFIX + "formatter.option"), PREF_FORMATTER); //$NON-NLS-1$ return result; } /* * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } protected void createSpacer(Composite composite, int columnSpan) { Label label= new Label(composite, SWT.NONE); GridData gd= new GridData(); gd.horizontalSpan= columnSpan; label.setLayoutData(gd); } /* * @see org.eclipse.jface.preference.PreferencePage#doGetPreferenceStore() */ protected IPreferenceStore doGetPreferenceStore() { return JavaPlugin.getDefault().getPreferenceStore(); } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); button.setSelection(store.getDefaultBoolean(key)); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); String[] info= (String[]) button.getData(); button.setSelection(info[1].equals(store.getDefaultString(info[0]))); } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); text.setText(store.getDefaultString(key)); } handleProviderListSelection(); super.performDefaults(); } /* * @see IPreferencePage#performOk() */ public boolean performOk() { IPreferenceStore store= getPreferenceStore(); for (int i= 0; i < fCheckBoxes.size(); i++) { Button button= (Button) fCheckBoxes.get(i); String key= (String) button.getData(); store.setValue(key, button.getSelection()); } for (int i= 0; i < fRadioButtons.size(); i++) { Button button= (Button) fRadioButtons.get(i); if (button.getSelection()) { String[] info= (String[]) button.getData(); store.setValue(info[0], info[1]); } } for (int i= 0; i < fTextControls.size(); i++) { Text text= (Text) fTextControls.get(i); String key= (String) text.getData(); store.setValue(key, text.getText()); } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } /** * @param store */ public static void initDefaults(IPreferenceStore store) { store.setDefault(PreferenceConstants.EDITOR_SMART_SEMICOLON, false); store.setDefault(PreferenceConstants.EDITOR_SMART_OPENING_BRACE, false); store.setDefault(PreferenceConstants.APPEARANCE_QUICKASSIST_LIGHTBULB, false); store.setDefault(PREF_FORMATTER, false); store.setDefault(PreferenceConstants.EDITOR_MARK_OCCURRENCES, false); } }
47,875
Bug 47875 Java search: too many cascading menus
- remove everything except reference. Inline reference in main menu - make it work in progress (per default enabled)
resolved fixed
32c5937
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T16:28:08Z
2003-12-02T10:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/JavaSearchActionGroup.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.ui.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 > 2) { 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); } }
48,338
Bug 48338 JavaSearchResultCollector should not create 'Searching' subtask [search]
Build 20031203 org.eclipse.jdt.internal.ui.search.JavaSearchResultCollector.aboutToStart() creates a subtask 'Searching'. This looks awkward as the search infrastructure is also printing this message.
resolved fixed
2b5bb03
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T17:48:12Z
2003-12-09T14:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/JavaSearchResultCollector.java
/******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import java.text.MessageFormat; import java.util.HashMap; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.search.ui.IActionGroupFactory; import org.eclipse.search.ui.ISearchResultView; import org.eclipse.search.ui.SearchUI; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.search.IJavaSearchResultCollector; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.OptionalMessageDialog; public class JavaSearchResultCollector implements IJavaSearchResultCollector { private static final String MATCH= SearchMessages.getString("SearchResultCollector.match"); //$NON-NLS-1$ private static final String MATCHES= SearchMessages.getString("SearchResultCollector.matches"); //$NON-NLS-1$ private static final String DONE= SearchMessages.getString("SearchResultCollector.done"); //$NON-NLS-1$ private static final String SEARCHING= SearchMessages.getString("SearchResultCollector.searching"); //$NON-NLS-1$ private static final Boolean POTENTIAL_MATCH_VALUE= new Boolean(true); private static final String POTENTIAL_MATCH_DIALOG_ID= "Search.PotentialMatchDialog"; //$NON-NLS-1$ private IProgressMonitor fMonitor; private ISearchResultView fView; private JavaSearchOperation fOperation; private int fMatchCount= 0; private int fPotentialMatchCount= 0; private long fLastUpdateTime; private Integer[] fMessageFormatArgs= new Integer[1]; private class ActionGroupFactory implements IActionGroupFactory { public ActionGroup createActionGroup(ISearchResultView part) { return new SearchViewActionGroup(part); } } public JavaSearchResultCollector() { // This ensures that the image class is loaded correctly JavaPlugin.getDefault().getImageRegistry(); } /** * @see IJavaSearchResultCollector#aboutToStart(). */ public void aboutToStart() { fPotentialMatchCount= 0; fView= SearchUI.getSearchResultView(); fMatchCount= 0; fLastUpdateTime= 0; if (fView != null) { fView.searchStarted( new ActionGroupFactory(), fOperation.getSingularLabel(), fOperation.getPluralLabelPattern(), fOperation.getImageDescriptor(), JavaSearchPage.EXTENSION_POINT_ID, new JavaSearchResultLabelProvider(), new GotoMarkerAction(), new GroupByKeyComputer(), fOperation); } if (!getProgressMonitor().isCanceled()) getProgressMonitor().subTask(SEARCHING); } /** * @see IJavaSearchResultCollector#accept */ public void accept(IResource resource, int start, int end, IJavaElement enclosingElement, int accuracy) throws CoreException { if (enclosingElement == null || accuracy == POTENTIAL_MATCH && SearchUI.arePotentialMatchesIgnored()) return; IMarker marker= resource.createMarker(SearchUI.SEARCH_MARKER); HashMap attributes; Object groupKey= enclosingElement; attributes= new HashMap(7); if (accuracy == POTENTIAL_MATCH) { fPotentialMatchCount++; attributes.put(SearchUI.POTENTIAL_MATCH, POTENTIAL_MATCH_VALUE); if (groupKey == null) groupKey= "?:null"; //$NON-NLS-1$ else groupKey= "?:" + enclosingElement.getHandleIdentifier(); //$NON-NLS-1$ } ICompilationUnit cu= SearchUtil.findCompilationUnit(enclosingElement); if (cu != null && cu.isWorkingCopy()) attributes.put(IJavaSearchUIConstants.ATT_IS_WORKING_COPY, new Boolean(true)); //$NON-NLS-1$ JavaCore.addJavaElementMarkerAttributes(attributes, enclosingElement); attributes.put(IJavaSearchUIConstants.ATT_JE_HANDLE_ID, enclosingElement.getHandleIdentifier()); attributes.put(IMarker.CHAR_START, new Integer(Math.max(start, 0))); attributes.put(IMarker.CHAR_END, new Integer(Math.max(end, 0))); if (enclosingElement instanceof IMember && ((IMember)enclosingElement).isBinary()) attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CF_EDITOR); else attributes.put(IWorkbenchPage.EDITOR_ID_ATTR, JavaUI.ID_CU_EDITOR); marker.setAttributes(attributes); if (fView != null) fView.addMatch(enclosingElement.getElementName(), groupKey, resource, marker); fMatchCount++; if (!getProgressMonitor().isCanceled() && System.currentTimeMillis() - fLastUpdateTime > 1000) { getProgressMonitor().subTask(getFormattedMatchesString(fMatchCount)); fLastUpdateTime= System.currentTimeMillis(); } } /** * @see IJavaSearchResultCollector#done(). */ public void done() { if (!getProgressMonitor().isCanceled()) { String matchesString= getFormattedMatchesString(fMatchCount); getProgressMonitor().setTaskName(MessageFormat.format(DONE, new String[]{matchesString})); } if (fView != null) { if (fPotentialMatchCount > 0) explainPotentialMatch(fPotentialMatchCount); fView.searchFinished(); } // Cut no longer unused references because the collector might be re-used fView= null; fMonitor= null; } private void explainPotentialMatch(final int potentialMatchCount) { // Make sure we are doing it in the right thread. final Shell shell= fView.getSite().getShell(); final String title; if (potentialMatchCount == 1) title= new String(SearchMessages.getString("Search.potentialMatchDialog.title.foundPotentialMatch")); //$NON-NLS-1$ else title= new String(SearchMessages.getFormattedString("Search.potentialMatchDialog.title.foundPotentialMatches", "" + potentialMatchCount)); //$NON-NLS-1$ //$NON-NLS-2$ shell.getDisplay().syncExec(new Runnable() { public void run() { OptionalMessageDialog.open( POTENTIAL_MATCH_DIALOG_ID, //$NON-NLS-1$, shell, title, null, SearchMessages.getString("Search.potentialMatchDialog.message"), //$NON-NLS-1$, MessageDialog.INFORMATION, new String[] { IDialogConstants.OK_LABEL }, 0); } }); } /* * @see IJavaSearchResultCollector#getProgressMonitor(). */ public IProgressMonitor getProgressMonitor() { return fMonitor; } void setProgressMonitor(IProgressMonitor pm) { fMonitor= pm; } void setOperation(JavaSearchOperation operation) { fOperation= operation; } private String getFormattedMatchesString(int count) { if (fMatchCount == 1) return MATCH; fMessageFormatArgs[0]= new Integer(count); return MessageFormat.format(MATCHES, fMessageFormatArgs); } }
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test51_in.java
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/canRename/A_test51_out.java
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
org.eclipse.jdt.ui.tests.refactoring/resources/RenameTemp/cannotRename/A_testFail32.java
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
org.eclipse.jdt.ui.tests.refactoring/test
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/RenameTempTests.java
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
org.eclipse.jdt.ui/core
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RefactoringAnalyzeUtil.java
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
org.eclipse.jdt.ui/core
47,822
Bug 47822 refactor rename duplicate local variable throws NPE [refactoring]
refactor rename the second b in the following example: ------------------------------------------------------- public class Test { public static void main(String[] args) { final int a = 3; final int b = 3; final int b = 3;//<-- refactor rename this variable final int b = 3; } } ------------------------------------------------------ the following occurs: java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.run (RefactoringWizardDialog2.java:271) at org.eclipse.jdt.internal.ui.refactoring.PerformRefactoringUtil.performRefactori ng(PerformRefactoringUtil.java:53) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:409) at org.eclipse.jdt.internal.ui.refactoring.UserInputWizardPage.performFinish (UserInputWizardPage.java:119) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizard.performFinish (RefactoringWizard.java:472) at org.eclipse.jdt.internal.ui.refactoring.RefactoringWizardDialog2.okPressed (RefactoringWizardDialog2.java:395) at org.eclipse.jface.dialogs.Dialog.buttonPressed(Dialog.java:263) at org.eclipse.jface.dialogs.Dialog$1.widgetSelected(Dialog.java:430) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:89) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.jface.window.Window.runEventLoop(Window.java:586) at org.eclipse.jface.window.Window.open(Window.java:566) at org.eclipse.jdt.internal.ui.refactoring.actions.RefactoringStarter.activate (RefactoringStarter.java:56) at org.eclipse.jdt.internal.ui.refactoring.actions.RenameTempAction.run (RenameTempAction.java:88) at org.eclipse.jdt.ui.actions.RenameAction.run(RenameAction.java:125) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun (SelectionDispatchAction.java:196) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run (SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent (RetargetAction.java:212) at org.eclipse.ui.internal.WWinPluginAction.runWithEvent (WWinPluginAction.java:212) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:542) at org.eclipse.jface.action.ActionContributionItem.access$4 (ActionContributionItem.java:494) at org.eclipse.jface.action.ActionContributionItem$6.handleEvent (ActionContributionItem.java:466) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:847) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:2296) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1977) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1405) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1381) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench (Workbench.java:237) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run (IDEApplication.java:47) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:852) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:462) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.NullPointerException at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llBindingKey(RefactoringAnalyzeUtil.java:91) at org.eclipse.jdt.internal.corext.refactoring.rename.RefactoringAnalyzeUtil.getFu llDeclarationBindingKey(RefactoringAnalyzeUtil.java:164) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.analyz eAST(RenameTempRefactoring.java:273) at org.eclipse.jdt.internal.corext.refactoring.rename.RenameTempRefactoring.checkI nput(RenameTempRefactoring.java:249) at org.eclipse.jdt.internal.ui.refactoring.CheckConditionsOperation.run (CheckConditionsOperation.java:65) at org.eclipse.jdt.internal.ui.refactoring.CreateChangeOperation.run (CreateChangeOperation.java:100) at org.eclipse.jdt.internal.ui.refactoring.PerformChangeOperation.run (PerformChangeOperation.java:138) at org.eclipse.jface.operation.ModalContext.runInCurrentThread (ModalContext.java:302) ... 45 more -------------------------------------------------------------------
resolved fixed
0cca1ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-09T18:53:22Z
2003-12-01T17:33:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/rename/RenameTempRefactoring.java
48,360
Bug 48360 ArrayIndexOutOfBoundsException when using escape key [reorg]
Using 1209, I got the following stack trace when trying to use Ctrl + C for copying and then cancelling it with the escape key. STEPS TO REPRODUCE: 1) Select a folder 2) Copy it in a folder that already contains a folder with the same name 3) You get a dialog asking if you want to override the existing file 4) Cancel it using the Esc key. 5) You get the exception. If you use the cancel button, it works fine. java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:313) at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:252) at org.eclipse.jface.dialogs.ProgressMonitorDialog.run(ProgressMonitorDialog.java:394) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper.perform(RefactoringExecutionHelper.java:131) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgCopyStarter.run(ReorgCopyStarter.java:70) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction$JavaElementAndResourcePaster.paste(PasteAction.java:404) at org.eclipse.jdt.internal.ui.refactoring.reorg.PasteAction.run(PasteAction.java:189) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.dispatchRun(SelectionDispatchAction.java:194) at org.eclipse.jdt.ui.actions.SelectionDispatchAction.run(SelectionDispatchAction.java:172) at org.eclipse.jface.action.Action.runWithEvent(Action.java:842) at org.eclipse.ui.actions.RetargetAction.runWithEvent(RetargetAction.java:212) at org.eclipse.ui.internal.commands.ActionHandler.execute(ActionHandler.java:40) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.executeCommand(WorkbenchKeyboard.java:341) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.press(WorkbenchKeyboard.java:673) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.processKeyEvent(WorkbenchKeyboard.java:711) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.filterKeySequenceBindings(WorkbenchKeyboard.java:410) at org.eclipse.ui.internal.keys.WorkbenchKeyboard.access$0(WorkbenchKeyboard.java:372) at org.eclipse.ui.internal.keys.WorkbenchKeyboard$1.handleEvent(WorkbenchKeyboard.java:205) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:82) at org.eclipse.swt.widgets.Display.filterEvent(Display.java:692) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:846) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:871) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:856) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1716) at org.eclipse.swt.widgets.Control.sendKeyEvent(Control.java:1712) at org.eclipse.swt.widgets.Control.WM_CHAR(Control.java:3036) at org.eclipse.swt.widgets.Tree.WM_CHAR(Tree.java:1292) at org.eclipse.swt.widgets.Control.windowProc(Control.java:2939) at org.eclipse.swt.widgets.Display.windowProc(Display.java:2819) at org.eclipse.swt.internal.win32.OS.DispatchMessageW(Native Method) at org.eclipse.swt.internal.win32.OS.DispatchMessage(OS.java:1368) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1973) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1537) at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:1513) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:242) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:139) at org.eclipse.ui.internal.ide.IDEApplication.run(IDEApplication.java:47) at org.eclipse.core.internal.runtime.PlatformActivator$1.run(PlatformActivator.java:242) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:84) 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.internal.boot.OSGiBootLoader.basicRun(OSGiBootLoader.java:239) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:665) at org.eclipse.core.internal.boot.OSGiBootLoader.run(OSGiBootLoader.java:652) 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:299) at org.eclipse.core.launcher.Main.run(Main.java:767) at org.eclipse.core.launcher.Main.main(Main.java:601) Caused by: java.lang.ArrayIndexOutOfBoundsException: -1 at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgQueries$1.run(ReorgQueries.java:129) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:131) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:25) at org.eclipse.swt.widgets.Display.syncExec(Display.java:2611) at org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgQueries$YesYesToAllNoNoToAllQuery.confirm(ReorgQueries.java:96) at org.eclipse.jdt.internal.corext.refactoring.reorg.OverwriteHelper.overwrite(OverwriteHelper.java:206) at org.eclipse.jdt.internal.corext.refactoring.reorg.OverwriteHelper.overwrite(OverwriteHelper.java:197) at org.eclipse.jdt.internal.corext.refactoring.reorg.OverwriteHelper.confirmFolderOverwritting(OverwriteHelper.java:131) at org.eclipse.jdt.internal.corext.refactoring.reorg.OverwriteHelper.confirmOverwritting(OverwriteHelper.java:99) at org.eclipse.jdt.internal.corext.refactoring.reorg.OverwriteHelper.confirmOverwritting(OverwriteHelper.java:93) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory$FilesFoldersAndCusReorgPolicy.confirmOverwritting(ReorgPolicyFactory.java:470) at org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory$FilesFoldersAndCusReorgPolicy.checkInput(ReorgPolicyFactory.java:455) at org.eclipse.jdt.internal.corext.refactoring.reorg.CopyRefactoring.checkInput(CopyRefactoring.java:101) at org.eclipse.jdt.internal.corext.refactoring.base.Refactoring.checkPreconditions(Refactoring.java:79) at org.eclipse.jdt.internal.ui.refactoring.RefactoringExecutionHelper$Operation.run(RefactoringExecutionHelper.java:69) at org.eclipse.jface.operation.ModalContext.runInCurrentThread(ModalContext.java:302) ... 52 more
resolved fixed
ba138ba
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2003-12-10T10:37:30Z
2003-12-09T20:00:00Z
org.eclipse.jdt.ui/ui