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
11,703
Bug 11703 Outline sorting -> constructors should be before statics
build 2002-03-19 on Win98. - open a Java editor on a Java file - in the Outline view have "sort" and "hide fields" icons selected - note that the sort order seems to be statics then constructors then instance methods - in build 2002-03-14 constructors used to be listed at the top next to the class name - this is much more useful
resolved fixed
c59109a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-16T18:31:22Z
2002-03-19T20:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; 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.DragSource; 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.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.IPartListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; 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.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.ui.actions.ShowActionGroup; 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.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.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.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private boolean fIsEnableMemberFilter; 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 IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fHierarchyLifeCycle.setReconciled(JavaBasePreferencePage.reconcileJavaViews()); fTypeHierarchyLifeCycleListener= new ITypeHierarchyLifeCycleListener() { public void typeHierarchyChanged(TypeHierarchyLifeCycle typeHierarchy, IType[] changedTypes) { doTypeHierarchyChanged(typeHierarchy, changedTypes); } }; fHierarchyLifeCycle.addChangedListener(fTypeHierarchyLifeCycleListener); 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); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) {} public void partClosed(IWorkbenchPart part) {} public void partDeactivated(IWorkbenchPart part) {} public void partOpened(IWorkbenchPart part) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * 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) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } if (member.getElementType() != IJavaElement.TYPE) { if (fHierarchyLifeCycle.isReconciled() && cu != null) { try { member= (IMember) EditorUtility.getWorkingCopy(member); if (member == null) { return; } } catch (JavaModelException e) { JavaPlugin.log(e); return; } } 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(); } 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(); } ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(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; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); getSite().getPage().removePartListener(fPartListener); if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW); fAllViewers= new TypeHierarchyViewer[3]; fAllViewers[VIEW_ID_SUPER]= superTypesViewer; fAllViewers[VIEW_ID_SUB]= subTypesViewer; fAllViewers[VIEW_ID_TYPE]= vajViewer; int currViewerIndex; try { currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); if (currViewerIndex < 0 || currViewerIndex > 2) { currViewerIndex= VIEW_ID_TYPE; } } catch (NumberFormatException e) { currViewerIndex= VIEW_ID_TYPE; } fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setInput(fAllViewers[i]); } // force the update fCurrentViewerIndex= -1; setView(currViewerIndex); return fViewerbook; } private KeyListener createKeyListener() { return new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F5) { updateHierarchyViewer(); return; } else if (event.character == SWT.DEL){ if (fCCPActionGroup.getDeleteAction().isEnabled()) fCCPActionGroup.getDeleteAction().run(); return; } } viewPartKeyShortcuts(event); } }; } 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.addSelectionChangedListener(fSelectionChangedListener); } 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.addSelectionChangedListener(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){ Control control= viewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(viewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ 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); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fToggleOrientationActions.length; i++) { viewMenu.add(fToggleOrientationActions[i]); } viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); // 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); IJavaElement input= 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 OpenEditorActionGroup(this), new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); fActionGroups.fillActionBars(getViewSite().getActionBars()); initDragAndDrop(); } /** * 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); // IStructuredSelection selection= (IStructuredSelection)viewer.getSelection(); // if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { // addOpenPerspectiveItem(menu, selection); // } // addOpenWithMenu(menu, selection); 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); // // ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, viewer); // // // XXX workaround until we have fully converted the code to use the new action groups // fActionGroups.get(2).fillContextMenu(menu); // fActionGroups.get(3).fillContextMenu(menu); // fActionGroups.get(4).fillContextMenu(menu); } /** * 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); // //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); // addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); // ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, fMethodsViewer); // // // XXX workaround until we have fully converted the code to use the new action groups // fActionGroups.get(2).fillContextMenu(menu); // fActionGroups.get(3).fillContextMenu(menu); // fActionGroups.get(4).fillContextMenu(menu); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IJavaElement)) return; IResource resource= null; try { resource= ((IJavaElement)element).getUnderlyingResource(); } catch(JavaModelException e) { // ignore } if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } /** * 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) { ISelection sel= null; 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.removeSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); viewer.addSelectionChangedListener(fSelectionChangedListener); } private void internalSelectMember(IMember member) { fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener); fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY); fMethodsViewer.addSelectionChangedListener(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() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); // 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(IType input) { if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } fMethodsViewer.setInput(input); } } private void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); } else { typeSelectionChanged(e.getSelection()); } } 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(); 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)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } 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(); 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(); 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 ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { if (fPagebook != null && !fPagebook.isDisposed()) { doTypeHierarchyChangedOnViewers(changedTypes); } } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fMethodsViewer.refresh(); updateHierarchyViewer(); } else { // elements in hierarchy modified fMethodsViewer.refresh(); if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { IJavaElement elem= (IJavaElement) input; if (elem instanceof IMember) { return elem; } else { int kind= elem.getElementType(); if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) { return elem; } } } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { String handleIndentifier= fInputElement.getHandleIdentifier(); if (fInputElement instanceof IType) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) { // for startup performance reasons do not try to recover huge hierarchies handleIndentifier= null; } } memento.putString(TAG_INPUT, handleIndentifier); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (input != null && !input.exists()) { input= null; } } 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); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { 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.getStatus()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return fInputElement; } }
11,703
Bug 11703 Outline sorting -> constructors should be before statics
build 2002-03-19 on Win98. - open a Java editor on a Java file - in the Outline view have "sort" and "hide fields" icons selected - note that the sort order seems to be statics then constructors then instance methods - in build 2002-03-14 constructors used to be listed at the top next to the class name - this is much more useful
resolved fixed
c59109a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-16T18:31:22Z
2002-03-19T20:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/JavaElementSorter.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IStorage; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.ContentViewer; import org.eclipse.jface.viewers.IBaseLabelProvider; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerSorter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IInitializer; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Sorter for Java elements. Ordered by element category, then by element name. * Package fragment roots are sorted as ordered on the classpath. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class JavaElementSorter extends ViewerSorter { private static final int JAVAPROJECTS= 1; private static final int PACKAGEFRAGMENTROOTS= 2; private static final int PACKAGEFRAGMENT= 3; private static final int RESOURCEPACKAGES= 6; private static final int COMPILATIONUNITS= 4; private static final int CLASSFILES= 5; private static final int RESOURCEFOLDERS= 7; private static final int RESOURCES= 8; private static final int STORAGE= 9; private static final int PACKAGE_DECL= 10; private static final int IMPORT_CONTAINER= 11; private static final int IMPORT_DECLARATION= 12; private static final int TYPES= 13; private static final int STATIC_INIT= 14; private static final int STATIC_FIELDS= 15; private static final int STATIC_METHODS= 16; private static final int FIELDS= 17; private static final int CONSTRUCTORS= 18; private static final int INIT= 19; private static final int METHODS= 20; private static final int JAVAELEMENTS= 21; private static final int OTHERS= 22; public JavaElementSorter() { } /** * @deprecated Bug 22518. Method never used: does not override ViewerSorter#isSorterProperty(Object, String). * Method could be removed, but kept for API compatibility. */ public boolean isSorterProperty(Object element, Object property) { return true; } /* * @see ViewerSorter#category */ public int category(Object element) { if (element instanceof IJavaElement) { try { IJavaElement je= (IJavaElement) element; switch (je.getElementType()) { case IJavaElement.METHOD: { IMethod method= (IMethod) je; if (method.isConstructor()) return CONSTRUCTORS; int flags= method.getFlags(); return Flags.isStatic(flags) ? STATIC_METHODS : METHODS; } case IJavaElement.FIELD: { int flags= ((IField) je).getFlags(); return Flags.isStatic(flags) ? STATIC_FIELDS : FIELDS; } case IJavaElement.INITIALIZER: { int flags= ((IInitializer) je).getFlags(); return Flags.isStatic(flags) ? STATIC_INIT : INIT; } case IJavaElement.TYPE: return TYPES; case IJavaElement.PACKAGE_DECLARATION: return PACKAGE_DECL; case IJavaElement.IMPORT_CONTAINER: return IMPORT_CONTAINER; case IJavaElement.IMPORT_DECLARATION: return IMPORT_DECLARATION; case IJavaElement.PACKAGE_FRAGMENT: IPackageFragment pack= (IPackageFragment) je; if (pack.getParent().getUnderlyingResource() instanceof IProject) { return PACKAGEFRAGMENTROOTS; } if (!pack.hasChildren() && pack.getNonJavaResources().length > 0) { return RESOURCEPACKAGES; } return PACKAGEFRAGMENT; case IJavaElement.PACKAGE_FRAGMENT_ROOT: return PACKAGEFRAGMENTROOTS; case IJavaElement.JAVA_PROJECT: return JAVAPROJECTS; case IJavaElement.CLASS_FILE: return CLASSFILES; case IJavaElement.COMPILATION_UNIT: return COMPILATIONUNITS; } } catch (JavaModelException e) { if (!e.isDoesNotExist()) { JavaPlugin.log(e); } // let none existing elements pass: name can be retrieved without existence } return JAVAELEMENTS; } else if (element instanceof IFile) { return RESOURCES; } else if (element instanceof IContainer) { return RESOURCEFOLDERS; } else if (element instanceof IStorage) { return STORAGE; } return OTHERS; } /* * @see ViewerSorter#compare */ public int compare(Viewer viewer, Object e1, Object e2) { int cat1= category(e1); int cat2= category(e2); if (cat1 != cat2) return cat1 - cat2; if (cat1 == PACKAGEFRAGMENTROOTS) { IPackageFragmentRoot root1= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e1); IPackageFragmentRoot root2= JavaModelUtil.getPackageFragmentRoot((IJavaElement)e2); if (!root1.getPath().equals(root2.getPath())) { int p1= getClassPathIndex(root1); int p2= getClassPathIndex(root2); if (p1 != p2) { return p1 - p2; } } } // non - java resources are sorted using the label from the viewers label provider if (cat1 == RESOURCES || cat1 == RESOURCEFOLDERS || cat1 == STORAGE || cat1 == OTHERS) { return compareWithLabelProvider(viewer, e1, e2); } String name1= ((IJavaElement) e1).getElementName(); String name2= ((IJavaElement) e2).getElementName(); // java element are sorted by name int cmp= getCollator().compare(name1, name2); if (cmp != 0) { return cmp; } if (cat1 == METHODS || cat1 == STATIC_METHODS || cat1 == CONSTRUCTORS) { String[] params1= ((IMethod) e1).getParameterTypes(); String[] params2= ((IMethod) e2).getParameterTypes(); int len= Math.min(params1.length, params2.length); for (int i = 0; i < len; i++) { cmp= getCollator().compare(Signature.toString(params1[i]), Signature.toString(params2[i])); if (cmp != 0) { return cmp; } } return params1.length - params2.length; } return 0; } private int compareWithLabelProvider(Viewer viewer, Object e1, Object e2) { if (viewer instanceof ContentViewer) { IBaseLabelProvider prov = ((ContentViewer) viewer).getLabelProvider(); if (prov instanceof ILabelProvider) { ILabelProvider lprov= (ILabelProvider) prov; String name1 = lprov.getText(e1); String name2 = lprov.getText(e2); if (name1 != null && name2 != null) { return getCollator().compare(name1, name2); } } } return 0; // can't compare } private int getClassPathIndex(IPackageFragmentRoot root) { try { IPath rootPath= root.getPath(); IPackageFragmentRoot[] roots= root.getJavaProject().getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (roots[i].getPath().equals(rootPath)) { return i; } } } catch (JavaModelException e) { } return Integer.MAX_VALUE; } }
23,447
Bug 23447 Java super-class name does not carry on to dialogue box [code manipulation]
From WSAD Customer: When creating a new Java Class, when an incomplete super-classname is entered in the dialogue box and then the Browse button is clicked, nothing that appears in the Choose a type field. Ideally, it should have the incomplete name typed in the previous super-class field. How to recreate : In the Java perspective, - File -> New ->Class - In the resulting dialogue box, type "JPan" in the 'Superclass' field. Now click on Browse. - Ideally, the dialogue box that just opened up should already have JPan written in it and hence the list of selectable classes would be shortened.
resolved fixed
02d77b9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T08:45:37Z
2002-09-12T08:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.compiler.env.IConstants; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /** * The class <code>NewTypeWizardPage</code> contains controls and validation routines * for a 'New Type WizardPage'. Implementors decide which components to add and to enable. * Implementors can also customize the validation code. <code>NewTypeWizardPage</code> * is intended to serve as base class of all wizards that create types like applets, servlets, classes, * interfaces, etc. * <p> * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an * example usage of <code>NewTypeWizardPage</code>. * </p> * * @see org.eclipse.jdt.ui.wizards.NewClassWizardPage * @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage * * @since 2.0 */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { /** * Class used in stub creation routines to add needed imports to a * compilation unit. */ public static class ImportsManager { private IImportsStructure fImportsStructure; /* package */ ImportsManager(IImportsStructure structure) { fImportsStructure= structure; } /* package */ IImportsStructure getImportsStructure() { return fImportsStructure; } /** * Adds a new import declaration that is sorted in the existing imports. * If an import already exists or the import would conflict with another import * of an other type with the same simple name the import is not added. * * @param qualifiedTypeName The fully qualified name of the type to import * (dot separated) * @return Retuns 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 = IConstants.AccPublic; /** Private access flag. See The Java Virtual Machine Specification for more details. */ public int F_PRIVATE = IConstants.AccPrivate; /** Protected access flag. See The Java Virtual Machine Specification for more details. */ public int F_PROTECTED = IConstants.AccProtected; /** Static access flag. See The Java Virtual Machine Specification for more details. */ public int F_STATIC = IConstants.AccStatic; /** Final access flag. See The Java Virtual Machine Specification for more details. */ public int F_FINAL = IConstants.AccFinal; /** Abstract property flag. See The Java Virtual Machine Specification for more details. */ public int F_ABSTRACT = IConstants.AccAbstract; private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$ /** Field ID of the package input field */ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ /** Field ID of the eclosing type input field */ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ /** Field ID of the enclosing type checkbox */ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ /** Field ID of the type name input field */ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ /** Field ID of the super type input field */ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ /** Field ID of the super interfaces input field */ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ /** Field ID of the modifier checkboxes */ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ /** Field ID of the method stubs checkboxes */ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; /** * Creates a new <code>NewTypeWizardPage</code> * * @param isClass <code>true</code> if a new class is to be created; otherwise * an interface is to be created * @param pageName the wizard page's name */ public NewTypeWizardPage(boolean isClass, String pageName) { super(pageName); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the page with a given selection. * * @param elem the selection used to intialize this page or <code> * null</code> if no selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= cu.findPrimaryType(); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); } /** * Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { // #6891 Composite tabGroup= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; tabGroup.setLayout(layout); fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= getMaxFieldWidth(); gd.horizontalSpan= 2; c.setLayoutData(gd); Button button= fEnclosingTypeDialogField.getChangeControl(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); } /** * Creates the controls for the type name field. Expects a <code>GridLayout</code> with at * least 2 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the modifiers radio/ceckbox buttons. Expects a * <code>GridLayout</code> with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> * with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with * at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; gd.widthHint= getMaxFieldWidth(); } /** * Sets the focus on the type name input field. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /* * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Returns the text of the package input field. * * @return the text of the package input field */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Returns the text of the enclosing type input field. * * @return the text of the enclosing type input field */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * * @return a package fragement or <code>null</code> if the input * could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment to the given value. The method updates the model * and the text of the control. * * @param pack the package fragement to be set * @param canBeModified if <code>true</code> the package fragment is * editable; otherwise it is read-only. */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the enclosing type corresponding to the current input. * * @return the enclosing type or <code>null</code> if the enclosing type is * not selected or the input could not be resolved */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the enclosing type. The method updates the underlying model * and the text of the control. * * @param type the enclosing type * @param canBeModified if <code>true</code> the enclosing type field is * editable; otherwise it is read-only. */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns the selection state of the enclosing type checkbox. * * @return the seleciton state of the enclosing type checkbox */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type checkbox's selection state. * * @param isSelected the checkbox's selection state * @param canBeModified if <code>true</code> the enclosing type checkbox is * modifiable; otherwise it is read-only. */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Returns the type name entered into the type input field. * * @return the type name */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name input field's text to the given value. Method doesn't update * the model. * * @param name the new type name * @param canBeModified if <code>true</code> the enclosing type name field is * editable; otherwise it is read-only. */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Returns the selected modifiers. * * @return the selected modifiers * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= F_PUBLIC; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= F_PRIVATE; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= F_PROTECTED; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= F_ABSTRACT; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= F_FINAL; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= F_STATIC; } return mdf; } /** * Sets the modifiers. * * @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>, * <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code> * or <code>F_STATIC</code> or, a valid combination. * @param canBeModified if <code>true</code> the modifier fields are * editable; otherwise they are read-only * @see Flags */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Returns the content of the superclass input field. * * @return the superclass name */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * * @param name the new superclass name * @param canBeModified if <code>true</code> the superclass name field is * editable; otherwise it is read-only. */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Returns the chosen super interfaces. * * @return a list of chosen super interfaces. The list's elements * are of type <code>String</code> */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * * @param interfacesNames a list of super interface. The method requires that * the list's elements are of type <code>String</code> * @param canBeModified if <code>true</code> the super interface field is * editable; otherwise it is read-only. */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * A hook method that gets called when the package field has changed. The method * validates the package name and returns the status of the validation. The validation * also updates the package fragment model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { if (root.getJavaProject().exists() && packName.length() > 0) { try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage= root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= getPackageText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Hook method that gets called when the enclosing type name has changed. The method * validates the enclosing type and returns the status of the validation. It also updates the * enclosing type model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= root.getJavaProject().findType(enclName); if (type == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e); return status; } } /** * Hook method that gets called when the type name has changed. The method validates the * type name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Hook method that gets called when the superclass name has changed. The method * validates the superclass name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= jproject.findType(res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= jproject.findType(packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(sclassName); } } return type; } /** * Hook method that gets called when the list of super interface has changed. The method * validates the superinterfaces and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= root.getJavaProject().findType(intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, checking is an extra } } } return status; } /** * Hook method that gets called when the modifiers have changed. The method validates * the modifiers and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null) { packages= froot.getChildren(); } } catch (JavaModelException e) { JavaPlugin.log(e); } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); if (fCurrPackage != null) { dialog.setInitialSelections(new Object[] { fCurrPackage }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ if (fCurrEnclosingType != null) { dialog.setInitialSelections(new Object[] { fCurrEnclosingType }); dialog.setFilter(fCurrEnclosingType.getElementName().substring(0, 1)); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ if (fSuperClass != null) { dialog.setFilter(fSuperClass.getElementName()); } if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$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. The progress * monitor must not be <code>null</code> */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= getTypeName(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", packStatement, false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); // add an import that will be removed again. Having this import solves 14661 imports.addImport(pack.getElementName(), getTypeName()); String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, parentCU); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 3)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); // 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); String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, parentCU); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so types can be resolved correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1)); // add imports imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); ICompilationUnit cu= createdType.getCompilationUnit(); ISourceRange range; if (isInnerClass) { synchronized(cu) { cu.reconcile(); } range= createdType.getSourceRange(); } else { range= cu.getSourceRange(); } IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment= getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. 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, ICompilationUnit parentCU) { StringBuffer buf= new StringBuffer(); String typeComment= getTypeComment(parentCU); if (typeComment != null && typeComment.length() > 0) { buf.append(typeComment); buf.append(lineDelimiter); } int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append('{'); buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead */ protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { //deprecated } /** * Hook method that gets called from <code>createType</code> to support adding of * unanticipated methods, fields, and inner types to the created type. * <p> * Implementers can use any methods defined on <code>IType</code> to manipulate the * new type. * </p> * <p> * The source code of the new type will be formtted using the platform's formatter. Needed * imports are added by the wizard at the end of the type creation process using the given * import manager. * </p> * * @param newType the new type created via <code>createType</code> * @param imports an import manager which can be used to add new imports * @param monitor a progress monitor to report progress. Must not be <code>null</code> * * @see #createType(IProgressMonitor) */ protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { // call for compatibility createTypeMembers(newType, ((ImportsManager)imports).getImportsStructure(), monitor); // default implementation does nothing // example would be // String mainMathod= "public void foo(Vector vec) {}" // createdType.createMethod(main, null, false, null); // imports.addImport("java.lang.Vector"); } /** * Hook mathod that gets called from <code>createType</code> to retrieve * a file comment. This default implementation returns the content of the * 'filecomment' template. * * @return the file comment or <code>null</code> if a file comment * is not desired */ protected String getFileComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doFileComments()) { return getTemplate("filecomment", parentCU, 0); //$NON-NLS-1$ } return null; } /** * Hook method that gets called from <code>createType</code> to retrieve * a type comment. This default implementation returns the content of the * 'typecomment' template. * * @return the type comment or <code>null</code> if a type comment * is not desired */ protected String getTypeComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doCreateComments()) { return getTemplate("typecomment", parentCU, 0); //$NON-NLS-1$ } 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. * * @param name the template to be evaluated * @param parentCU the templates evaluation context * @param pos a source offset into the parent compilation unit. The * template is evalutated at the given source offset */ protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { try { Template[] templates= Templates.getInstance().getTemplates(name); if (templates.length > 0) { return JavaContext.evaluateTemplate(templates[0], parentCU, pos); } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor); } /** * Creates the bodies of all unimplemented methods and constructors and adds them to the type. * Method is typically called by implementers of <code>NewTypeWizardPage</code> to add * needed method and constructors. * * @param type the type for which the new methods and constructor are to be created * @param doConstructors if <code>true</code> unimplemented constructors are created * @param doUnimplementedMethods if <code>true</code> unimplemented methods are created * @param imports an import manager to add all neded import statements * @param monitor a progress monitor to report progress */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException { ArrayList newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure()); if (constructors != null) { for (int i= 0; i < constructors.length; i++) { newMethods.add(constructors[i]); } } } } if (doUnimplementedMethods) { String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports.getImportsStructure()); if (unimplemented != null) { for (int i= 0; i < unimplemented.length; i++) { newMethods.add(unimplemented[i]); } } } IMethod[] createdMethods= new IMethod[newMethods.size()]; for (int i= 0; i < newMethods.size(); i++) { String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n createdMethods[i]= type.createMethod(content, null, false, null); } return createdMethods; } // ---- creation ---------------- /** * Returns the runnable that creates the type using the current settings. * The returned runnable must be executed in the UI thread. * * @return the runnable to create the new type */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
23,585
Bug 23585 Reorder parameter refactoring of constructors broken [refactoring]
The following refactoring does not work: reorder parameters of constructors. This works for non-constructor methods but fails for constructors. A simple (double, double) will demonstrate the flaw. The constructor itself is changed but none of the constructor references are updated.
resolved fixed
9d740b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T08:52:27Z
2002-09-14T13:26:40Z
org.eclipse.jdt.ui/core
23,585
Bug 23585 Reorder parameter refactoring of constructors broken [refactoring]
The following refactoring does not work: reorder parameters of constructors. This works for non-constructor methods but fails for constructors. A simple (double, double) will demonstrate the flaw. The constructor itself is changed but none of the constructor references are updated.
resolved fixed
9d740b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T08:52:27Z
2002-09-14T13:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ModifyParametersRefactoring.java
23,585
Bug 23585 Reorder parameter refactoring of constructors broken [refactoring]
The following refactoring does not work: reorder parameters of constructors. This works for non-constructor methods but fails for constructors. A simple (double, double) will demonstrate the flaw. The constructor itself is changed but none of the constructor references are updated.
resolved fixed
9d740b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T08:52:27Z
2002-09-14T13:26:40Z
org.eclipse.jdt.ui/core
23,585
Bug 23585 Reorder parameter refactoring of constructors broken [refactoring]
The following refactoring does not work: reorder parameters of constructors. This works for non-constructor methods but fails for constructors. A simple (double, double) will demonstrate the flaw. The constructor itself is changed but none of the constructor references are updated.
resolved fixed
9d740b2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T08:52:27Z
2002-09-14T13:26:40Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ReorderParametersRefactoring.java
23,348
Bug 23348 Quickfix ignores read-only state [quick fix]
Build: 20020903 1. Create a new Java project. 2. Create a new Java file, A.java public class A { public void foo() { ba(); } public void bar() { } } 3. Save the file. 4. Mark it read-only. 5. Right click the error in the task list and select "Quick- fix..." 6. Select either of the options, the edits are made (in a read-only file!).
resolved fixed
3fdca60
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T08:55:22Z
2002-09-09T22:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/CorrectionMarkerResolutionGenerator.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.Position; import org.eclipse.jface.text.source.IAnnotationModel; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IMarkerResolution; import org.eclipse.ui.IMarkerResolutionGenerator; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaModelMarker; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.JavaMarkerAnnotation; /** */ public class CorrectionMarkerResolutionGenerator implements IMarkerResolutionGenerator { public static class CorrectionMarkerResolution implements IMarkerResolution { private IEditorInput fEditorInput; private ChangeCorrectionProposal fProposal; /** * Constructor for CorrectionMarkerResolution. */ public CorrectionMarkerResolution(IEditorInput editorInput, ChangeCorrectionProposal proposal) { fEditorInput= editorInput; fProposal= proposal; } /* (non-Javadoc) * @see IMarkerResolution#getLabel() */ public String getLabel() { return fProposal.getDisplayString(); } /* (non-Javadoc) * @see IMarkerResolution#run(IMarker) */ public void run(IMarker marker) { IDocument doc= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(fEditorInput); if (doc != null) { fProposal.apply(doc); } } } /** * Constructor for CorrectionMarkerResolutionGenerator. */ public CorrectionMarkerResolutionGenerator() { super(); } /* (non-Javadoc) * @see IMarkerResolutionGenerator#getResolutions(IMarker) */ public IMarkerResolution[] getResolutions(IMarker marker) { int id= marker.getAttribute(IJavaModelMarker.ID, -1); if (!JavaCorrectionProcessor.hasCorrections(id)) { return new IMarkerResolution[0]; } try { ICompilationUnit cu= getCompilationUnit(marker); if (cu != null) { IEditorInput input= EditorUtility.getEditorInput(cu); if (input != null) { // only works with element open in editor ProblemPosition pos= findProblemPosition(input, marker); if (pos != null) { ArrayList proposals= new ArrayList(); JavaCorrectionProcessor.collectCorrections(pos, proposals); int nProposals= proposals.size(); IMarkerResolution[] resolutions= new IMarkerResolution[nProposals]; for (int i= 0; i < nProposals; i++) { resolutions[i]= new CorrectionMarkerResolution(input, (ChangeCorrectionProposal) proposals.get(i)); } return resolutions; } } } } catch (JavaModelException e) { JavaPlugin.log(e); } return new IMarkerResolution[0]; } private ICompilationUnit getCompilationUnit(IMarker marker) { IResource res= marker.getResource(); if (res instanceof IFile && res.isAccessible()) { return JavaCore.createCompilationUnitFrom((IFile) res); } return null; } private ProblemPosition findProblemPosition(IEditorInput input, IMarker marker) throws JavaModelException { IAnnotationModel model= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getAnnotationModel(input); if (model != null) { Iterator iter= model.getAnnotationIterator(); while (iter.hasNext()) { Object curr= iter.next(); if (curr instanceof JavaMarkerAnnotation) { JavaMarkerAnnotation annot= (JavaMarkerAnnotation) curr; if (marker.equals(annot.getMarker())) { Position pos= model.getPosition(annot); if (pos != null) { ICompilationUnit cu= getCompilationUnit(marker); return new ProblemPosition(pos, annot, EditorUtility.getWorkingCopy(cu)); } } } } } return null; } }
22,994
Bug 22994 Choose Package subdialog of New Class dialog crashes if source dir is not on java build path [dialogs]
There is no code for checking whether given IPackageFragmentRoot exists. Simmilar problem is in Choose Source Dir dialog - it allows you to select project even if it is not a source folder.
resolved fixed
f30cca5
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T09:10:53Z
2002-08-29T16:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewContainerWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.views.contentoutline.ContentOutline; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * Wizard page that acts as a base class for wizard pages that create new Java elements. * The class provides a input field for source folders (called container in this class) and * API to validate the enter source folder name. * * @since 2.0 */ public abstract class NewContainerWizardPage extends NewElementWizardPage { /** Id of the container field */ protected static final String CONTAINER= "NewContainerWizardPage.container"; //$NON-NLS-1$ /** The status of the last validation. */ protected IStatus fContainerStatus; private StringButtonDialogField fContainerDialogField; /* * package fragment root corresponding to the input type (can be null) */ private IPackageFragmentRoot fCurrRoot; private IWorkspaceRoot fWorkspaceRoot; /** * Create a new <code>NewContainerWizardPage</code> * * @param name the wizard page's name */ public NewContainerWizardPage(String name) { super(name); fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); ContainerFieldAdapter adapter= new ContainerFieldAdapter(); fContainerDialogField= new StringButtonDialogField(adapter); fContainerDialogField.setDialogFieldListener(adapter); fContainerDialogField.setLabelText(NewWizardMessages.getString("NewContainerWizardPage.container.label")); //$NON-NLS-1$ fContainerDialogField.setButtonLabel(NewWizardMessages.getString("NewContainerWizardPage.container.button")); //$NON-NLS-1$ fContainerStatus= new StatusInfo(); fCurrRoot= null; } /** * Initializes the source folder field with a valid package fragement root. * The package fragement root is computed from the given Java element. * * @param elem the Java element used to compute the initial package * fragment root used as the source folder */ protected void initContainerPage(IJavaElement elem) { IPackageFragmentRoot initRoot= null; if (elem != null) { initRoot= JavaModelUtil.getPackageFragmentRoot(elem); if (initRoot == null || initRoot.isArchive()) { IJavaProject jproject= elem.getJavaProject(); if (jproject != null) { try { initRoot= null; IPackageFragmentRoot[] roots= jproject.getPackageFragmentRoots(); for (int i= 0; i < roots.length; i++) { if (roots[i].getKind() == IPackageFragmentRoot.K_SOURCE) { initRoot= roots[i]; break; } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } if (initRoot == null) { initRoot= jproject.getPackageFragmentRoot(""); //$NON-NLS-1$ } } } } setPackageFragmentRoot(initRoot, true); } /** * Utility method to inspect a selection to find a Java element. * * @param selection the selection to be inspected * @return a Java element to be used as the initial selection, or <code>null</code>, * if no Java element exists in the given selection */ protected IJavaElement getInitialJavaElement(IStructuredSelection selection) { IJavaElement jelem= null; if (selection != null && !selection.isEmpty()) { Object selectedElement= selection.getFirstElement(); if (selectedElement instanceof IAdaptable) { IAdaptable adaptable= (IAdaptable) selectedElement; jelem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (jelem == null) { IResource resource= (IResource) adaptable.getAdapter(IResource.class); if (resource != null && resource.getType() != IResource.ROOT) { while (jelem == null && resource.getType() != IResource.PROJECT) { resource= resource.getParent(); jelem= (IJavaElement) resource.getAdapter(IJavaElement.class); } if (jelem == null) { jelem= JavaCore.create(resource); // java project } } } } } if (jelem == null) { IWorkbenchPart part= JavaPlugin.getActivePage().getActivePart(); if (part instanceof ContentOutline) { part= JavaPlugin.getActivePage().getActiveEditor(); } if (part instanceof IViewPartInputProvider) { Object elem= ((IViewPartInputProvider)part).getViewPartInput(); if (elem instanceof IJavaElement) { jelem= (IJavaElement) elem; } } } if (jelem == null || jelem.getElementType() == IJavaElement.JAVA_MODEL) { IProject[] projects= getWorkspaceRoot().getProjects(); if (projects.length > 0) { jelem= JavaCore.create(projects[0]); } } return jelem; } /** * Returns the recommended maximum width for text fields (in pixels). This * method requires that createContent has been called before this method is * call. Subclasses may override to change the maximum width for text * fields. * * @return the recommended maximum width for text fields. */ protected int getMaxFieldWidth() { return convertWidthInCharsToPixels(40); } /** * Creates the necessary controls (label, text field and browse button) to edit * the source folder location. The method expects that the parent composite * uses a <code>GridLayout</code> as its layout manager and that the * grid layout has at least 3 columns. * * @param parent the parent composite * @param nColumns the number of columns to span. This number must be * greater or equal three */ protected void createContainerControls(Composite parent, int nColumns) { fContainerDialogField.doFillIntoGrid(parent, nColumns); LayoutUtil.setWidthHint(fContainerDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Sets the focus to the source folder's text field. */ protected void setFocusOnContainer() { fContainerDialogField.setFocus(); } // -------- ContainerFieldAdapter -------- private class ContainerFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { containerChangeControlPressed(field); } // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { containerDialogFieldChanged(field); } } private void containerChangeControlPressed(DialogField field) { // take the current jproject as init element of the dialog IPackageFragmentRoot root= getPackageFragmentRoot(); root= chooseSourceContainer(root); if (root != null) { setPackageFragmentRoot(root, true); } } private void containerDialogFieldChanged(DialogField field) { if (field == fContainerDialogField) { fContainerStatus= containerChanged(); } // tell all others handleFieldChanged(CONTAINER); } // ----------- validation ---------- /** * This method is a hook which gets called after the source folder's * text input field has changed. This default implementation updates * the model and returns an error status. The underlying model * is only valid if the returned status is OK. * * @return the model's error status */ protected IStatus containerChanged() { StatusInfo status= new StatusInfo(); fCurrRoot= null; String str= getPackageFragmentRootText(); if (str.length() == 0) { status.setError(NewWizardMessages.getString("NewContainerWizardPage.error.EnterContainerName")); //$NON-NLS-1$ return status; } IPath path= new Path(str); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { int resType= res.getType(); if (resType == IResource.PROJECT || resType == IResource.FOLDER) { IProject proj= res.getProject(); if (!proj.isOpen()) { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ProjectClosed", proj.getFullPath().toString())); //$NON-NLS-1$ return status; } IJavaProject jproject= JavaCore.create(proj); fCurrRoot= jproject.getPackageFragmentRoot(res); if (res.exists()) { try { if (!proj.hasNature(JavaCore.NATURE_ID)) { if (resType == IResource.PROJECT) { status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotInAJavaProject")); //$NON-NLS-1$ } return status; } } catch (CoreException e) { status.setWarning(NewWizardMessages.getString("NewContainerWizardPage.warning.NotAJavaProject")); //$NON-NLS-1$ } try { if (!jproject.isOnClasspath(fCurrRoot)) { status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ } } catch (JavaModelException e) { status.setWarning(NewWizardMessages.getFormattedString("NewContainerWizardPage.warning.NotOnClassPath", str)); //$NON-NLS-1$ } if (fCurrRoot.isArchive()) { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerIsBinary", str)); //$NON-NLS-1$ return status; } } return status; } else { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.NotAFolder", str)); //$NON-NLS-1$ return status; } } else { status.setError(NewWizardMessages.getFormattedString("NewContainerWizardPage.error.ContainerDoesNotExist", str)); //$NON-NLS-1$ return status; } } // -------- update message ---------------- /** * Hook method that gets called when a field on this page has changed. For this page the * method gets called when the source folder field changes. * <p> * Every sub type is responsible to call this method when a field on its page has changed. * Subtypes override (extend) the method to add verification when a own field has a * dependency to an other field. For example the class name input must be verified * again when the package field changes (check for duplicated class names). * * @param fieldName The name of the field that has changed (field id). For the * source folder the field id is <code>CONTAINER</code> */ protected void handleFieldChanged(String fieldName) { } // ---- get ---------------- /** * Returns the workspace root. * * @return the workspace root */ protected IWorkspaceRoot getWorkspaceRoot() { return fWorkspaceRoot; } /** * Returns the <code>IPackageFragmentRoot</code> that corresponds to the current * value of the source folder field. * * @return the IPackageFragmentRoot or <code>null</code> if the current source * folder value is not a valid package fragment root * */ public IPackageFragmentRoot getPackageFragmentRoot() { return fCurrRoot; } /** * Returns the current text of source folder text field. * * @return the text of the source folder text field */ public String getPackageFragmentRootText() { return fContainerDialogField.getText(); } /** * Sets the current source folder (model and text field) to the given package * fragment root. * * @param canBeModified if <code>false</code> the source folder field can * not be changed by the user. If <code>true</code> the field is editable */ public void setPackageFragmentRoot(IPackageFragmentRoot root, boolean canBeModified) { fCurrRoot= root; String str= (root == null) ? "" : root.getPath().makeRelative().toString(); //$NON-NLS-1$ fContainerDialogField.setText(str); fContainerDialogField.setEnabled(canBeModified); } // ------------- choose source container dialog private IPackageFragmentRoot chooseSourceContainer(IJavaElement initElement) { Class[] acceptedClasses= new Class[] { IPackageFragmentRoot.class, IJavaProject.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false) { public boolean isSelectedValid(Object element) { try { if (element instanceof IJavaProject) { IJavaProject jproject= (IJavaProject)element; IPath path= jproject.getProject().getFullPath(); return (jproject.findPackageFragmentRoot(path) != null); } else if (element instanceof IPackageFragmentRoot) { return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); } return true; } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // just log, no ui in validation } return false; } }; acceptedClasses= new Class[] { IJavaModel.class, IPackageFragmentRoot.class, IJavaProject.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses) { public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IPackageFragmentRoot) { try { return (((IPackageFragmentRoot)element).getKind() == IPackageFragmentRoot.K_SOURCE); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // just log, no ui in validation return false; } } return super.select(viewer, parent, element); } }; StandardJavaElementContentProvider provider= new StandardJavaElementContentProvider(); ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), labelProvider, provider); dialog.setValidator(validator); dialog.setSorter(new JavaElementSorter()); dialog.setTitle(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewContainerWizardPage.ChooseSourceContainerDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(JavaCore.create(fWorkspaceRoot)); dialog.setInitialSelection(initElement); if (dialog.open() == dialog.OK) { Object element= dialog.getFirstResult(); if (element instanceof IJavaProject) { IJavaProject jproject= (IJavaProject)element; return jproject.getPackageFragmentRoot(jproject.getProject()); } else if (element instanceof IPackageFragmentRoot) { return (IPackageFragmentRoot)element; } return null; } return null; } }
19,864
Bug 19864 Code completion does not filter fully qualified class names
Steps to reproduce: - Type: java.io. - Press CTRL+SPACE to make the Auto completion box appear. - Type: O The auto completion box then disapears. It should instead filter out those classes that do not begin with O. I'm using build 20020607.
resolved fixed
ff5b486
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T13:23:43Z
2002-06-11T01:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaCompletionProposal.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.contentassist.ICompletionProposalExtension; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.util.Assert; public class JavaCompletionProposal implements IJavaCompletionProposal, ICompletionProposalExtension { 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; private int fRelevance; /** * 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) { 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; 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; if (trigger == (char) 0) { replace(document, fReplacementOffset, fReplacementLength, 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; } replace(document, fReplacementOffset, fReplacementLength, buffer.toString()); } } catch (BadLocationException x) { // ignore } } // #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) { if (offset < fReplacementOffset) return false; /* * See http://dev.eclipse.org/bugs/show_bug.cgi?id=17667 String word= fReplacementString; */ String word= fDisplayString; 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; } /** * 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; } }
19,864
Bug 19864 Code completion does not filter fully qualified class names
Steps to reproduce: - Type: java.io. - Press CTRL+SPACE to make the Auto completion box appear. - Type: O The auto completion box then disapears. It should instead filter out those classes that do not begin with O. I'm using build 20020607.
resolved fixed
ff5b486
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T13:23:43Z
2002-06-11T01:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/JavaTypeCompletionProposal.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.java; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.BadLocationException; import org.eclipse.jface.text.IDocument; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; /** * If passed compilation unit is not null, the replacement string will be seen as a qualified type name. */ public class JavaTypeCompletionProposal extends JavaCompletionProposal { private ICompilationUnit fCompilationUnit; public JavaTypeCompletionProposal(String replacementString, ICompilationUnit cu, int replacementOffset, int replacementLength, Image image, String displayString, int relevance) { super(replacementString, replacementOffset, replacementLength, image, displayString, relevance); fCompilationUnit= cu; } /** * To be o */ protected String updateReplacementString(IDocument document, char trigger, int offset, ImportsStructure impStructure) throws CoreException, BadLocationException { if (impStructure != null) { IType[] types= impStructure.getCompilationUnit().getTypes(); if (types.length > 0 && types[0].getSourceRange().getOffset() <= offset) { // ignore positions above type. return impStructure.addImport(getReplacementString()); } } return null; } /* (non-Javadoc) * @see ICompletionProposalExtension#apply(IDocument, char, int) */ public void apply(IDocument document, char trigger, int offset) { try { ImportsStructure impStructure= null; if (fCompilationUnit != null) { String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); impStructure= new ImportsStructure(fCompilationUnit, prefOrder, threshold, true); } String replacementString= updateReplacementString(document, trigger, offset, impStructure); if (replacementString != null) { setReplacementString(replacementString); setCursorPosition(replacementString.length()); } super.apply(document, trigger, offset); if (impStructure != null) { int oldLen= document.getLength(); impStructure.create(false, null); setReplacementOffset(getReplacementOffset() + document.getLength() - oldLen); } } catch (CoreException e) { JavaPlugin.log(e); } catch (BadLocationException e) { JavaPlugin.log(e); } } }
19,864
Bug 19864 Code completion does not filter fully qualified class names
Steps to reproduce: - Type: java.io. - Press CTRL+SPACE to make the Auto completion box appear. - Type: O The auto completion box then disapears. It should instead filter out those classes that do not begin with O. I'm using build 20020607.
resolved fixed
ff5b486
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-17T13:23:43Z
2002-06-11T01:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jdt.core.CompletionRequestorAdapter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; /** * Bin to collect the proposal of the infrastructure on code assist in a java text. */ public class ResultCollector extends CompletionRequestorAdapter { private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' }; private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' }; private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' }; private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';' }; protected IJavaProject fJavaProject; protected ICompilationUnit fCompilationUnit; // set when imports can be added protected int fCodeAssistOffset; protected int fContextOffset; private ArrayList fFields= new ArrayList(), fKeywords= new ArrayList(10), fLabels= new ArrayList(10), fMethods= new ArrayList(), fModifiers= new ArrayList(10), fPackages= new ArrayList(), fTypes= new ArrayList(), fVariables= new ArrayList(); private IProblem fLastProblem; private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry(); private ArrayList[] fResults = new ArrayList[] { fPackages, fLabels, fModifiers, fKeywords, fTypes, fMethods, fFields, fVariables }; private int fUserReplacementLength; /* * Is eating code assist enabled or disabled? PR #3666 * When eating is enabled, JavaCompletionProposal must be revisited: PR #5533 */ private boolean fPreventEating= true; /* * @see ICompletionRequestor#acceptClass */ public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, false, modifiers); if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance)); } /* * @see ICompletionRequestor#acceptError */ public void acceptError(IProblem error) { fLastProblem= error; } /* * @see ICompletionRequestor#acceptField */ public void acceptField( char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= getFieldDescriptor(modifiers); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(name); if (typeName.length > 0) { nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(typeName); } if (declaringTypeName != null && declaringTypeName.length > 0) { nameBuffer.append(" - "); //$NON-NLS-1$ nameBuffer.append(declaringTypeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance); proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name)); proposal.setTriggerCharacters(VAR_TRIGGER); fFields.add(proposal); } /* * @see ICompletionRequestor#acceptInterface */ public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(true, false, modifiers); if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance)); } /* * @see ICompletionRequestor#acceptAnonymousType */ public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd, relevance); proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName)); fTypes.add(proposal); } /* * @see ICompletionRequestor#acceptKeyword */ public void acceptKeyword(char[] keyword, int start, int end, int relevance) { String kw= new String(keyword); fKeywords.add(createCompletion(start, end, kw, null, kw, relevance)); } /* * @see ICompletionRequestor#acceptLabel */ public void acceptLabel(char[] labelName, int start, int end, int relevance) { String ln= new String(labelName); fLabels.add(createCompletion(start, end, ln, null, ln, relevance)); } /* * @see ICompletionRequestor#acceptLocalVariable */ public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end, int relevance) { StringBuffer buf= new StringBuffer(); buf.append(name); if (typeName != null) { buf.append(" "); //$NON-NLS-1$ buf.append(typeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(name), JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE, buf.toString(), relevance); proposal.setTriggerCharacters(VAR_TRIGGER); fVariables.add(proposal); } protected String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) { StringBuffer buf = new StringBuffer(); if (parameterTypeNames != null) { for (int i = 0; i < parameterTypeNames.length; i++) { if (i > 0) { buf.append(','); buf.append(' '); } buf.append(parameterTypeNames[i]); if (parameterNames != null && parameterNames[i] != null) { buf.append(' '); buf.append(parameterNames[i]); } } } return buf.toString(); } /* * @see ICompletionRequestor#acceptMethod */ public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) { if (completionName == null) return; JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterPackageNames, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, relevance); boolean isConstructor= returnTypeName == null ? true : returnTypeName.length == 0; proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, isConstructor)); boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')'); ProposalContextInformation contextInformation= null; if (hasOpeningBracket && parameterTypeNames.length > 0) { contextInformation= new ProposalContextInformation(); contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames)); contextInformation.setContextDisplayString(proposal.getDisplayString()); contextInformation.setImage(proposal.getImage()); int position= (completionName.length == 0) ? fContextOffset : -1; contextInformation.setContextInformationPosition(position); proposal.setContextInformation(contextInformation); } boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0); char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS; proposal.setTriggerCharacters(triggers); if (userMustCompleteParameters) { // set the cursor before the closing bracket proposal.setCursorPosition(completionName.length - 1); } fMethods.add(proposal); } /* * @see ICompletionRequestor#acceptModifier */ public void acceptModifier(char[] modifier, int start, int end, int relevance) { String mod= new String(modifier); fModifiers.add(createCompletion(start, end, mod, null, mod, relevance)); } /* * @see ICompletionRequestor#acceptPackage */ public void acceptPackage(char[] packageName, char[] completionName, int start, int end, int relevance) { fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName), relevance)); } /* * @see ICompletionRequestor#acceptType */ public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int relevance) { ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info, relevance)); } /* * @see ICodeCompletionRequestor#acceptMethodDeclaration */ public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) { StringBuffer displayString= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName); StringBuffer typeName= new StringBuffer(); if (declaringTypePackageName.length > 0) { typeName.append(declaringTypePackageName); typeName.append('.'); } typeName.append(declaringTypeName); String[] paramTypes= new String[parameterTypeNames.length]; for (int i= 0; i < parameterTypeNames.length; i++) { paramTypes[i]= Signature.createTypeSignature(parameterTypeNames[i], true); } JavaCompletionProposal proposal= new MethodStubCompletionProposal(fJavaProject, fCompilationUnit, typeName.toString(), new String(name), paramTypes, start, getLength(start, end), displayString.toString(), new String(completionName)); proposal.setImage(getImage(getMemberDescriptor(modifiers))); proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0)); proposal.setRelevance(relevance); fMethods.add(proposal); } /* * @see ICodeCompletionRequestor#acceptVariableName */ public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end, int relevance) { // XXX: To be revised StringBuffer buf= new StringBuffer(); buf.append(name); if (typeName != null && typeName.length > 0) { buf.append(" - "); //$NON-NLS-1$ buf.append(typeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString(), relevance); proposal.setTriggerCharacters(VAR_TRIGGER); fVariables.add(proposal); } public String getErrorMessage() { if (fLastProblem != null) return fLastProblem.getMessage(); return ""; //$NON-NLS-1$ } public JavaCompletionProposal[] getResults() { // return unsorted int totLen= 0; for (int i= 0; i < fResults.length; i++) { totLen += fResults[i].size(); } JavaCompletionProposal[] result= new JavaCompletionProposal[totLen]; int k= 0; for (int i= 0; i < fResults.length; i++) { ArrayList curr= fResults[i]; int currLen= curr.size(); for (int j= 0; j < currLen; j++) { JavaCompletionProposal proposal= (JavaCompletionProposal) curr.get(j); // for equal relevance, take categories proposal.setRelevance(proposal.getRelevance() * 16 + i); result[k++]= proposal; } } return result; } private StringBuffer getMethodDisplayString(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName) { StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(name); nameBuffer.append('('); if (parameterTypeNames != null && parameterTypeNames.length > 0) { nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames)); } nameBuffer.append(')'); if (returnTypeName != null && returnTypeName.length > 0) { nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(returnTypeName); } if (declaringTypeName != null && declaringTypeName.length > 0) { nameBuffer.append(" - "); //$NON-NLS-1$ nameBuffer.append(declaringTypeName); } return nameBuffer; } protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypePackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= getMemberDescriptor(modifiers); StringBuffer nameBuffer= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName); return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance); } protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end, int relevance) { StringBuffer declTypeBuf= new StringBuffer(); if (declaringTypePackageName.length > 0) { declTypeBuf.append(declaringTypePackageName); declTypeBuf.append('.'); } declTypeBuf.append(declaringTypeName); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(declaringTypeName); nameBuffer.append('('); if (parameterTypeNames.length > 0) { nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames)); } nameBuffer.append(')'); nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$ int length= end - start; return new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString(), relevance); } protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo, int relevance) { StringBuffer buf= new StringBuffer(typeName); if (containerName != null) { buf.append(" - "); //$NON-NLS-1$ if (containerName.length() > 0) { buf.append(containerName); } else { buf.append(JavaTextMessages.getString("ResultCollector.default_package")); //$NON-NLS-1$ } } String name= buf.toString(); ICompilationUnit cu= null; if (containerName != null && fCompilationUnit != null) { if (completion.equals(JavaModelUtil.concatenateName(containerName, typeName))) { cu= fCompilationUnit; } } JavaCompletionProposal proposal= new JavaTypeCompletionProposal(completion, cu, start, getLength(start, end), getImage(descriptor), name, relevance); proposal.setProposalInfo(proposalInfo); proposal.setTriggerCharacters(TYPE_TRIGGERS); return proposal; } protected ImageDescriptor getMemberDescriptor(int modifiers) { ImageDescriptor desc= JavaElementImageProvider.getMethodImageDescriptor(false, modifiers); if (Flags.isDeprecated(modifiers)) return getDeprecatedDescriptor(desc); return desc; } protected ImageDescriptor getFieldDescriptor(int modifiers) { ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, modifiers); if (Flags.isDeprecated(modifiers)) return getDeprecatedDescriptor(desc); return desc; } protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) { Point size= new Point(16, 16); return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.WARNING, size); } protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name, int relevance) { return new JavaCompletionProposal(completion, start, getLength(start, end), getImage(descriptor), name, relevance); } private int getLength(int start, int end) { int length; if (fUserReplacementLength == -1) { length= fPreventEating ? fCodeAssistOffset - start : end - start; } else { length= fUserReplacementLength; // extend length to begin at start if (start < fCodeAssistOffset) { length+= fCodeAssistOffset - start; } } return length; } private Image getImage(ImageDescriptor descriptor) { return (descriptor == null) ? null : fRegistry.get(descriptor); } /** * Specifies the context of the code assist operation. * @param codeAssistOffset The Offset at which the code assist will be called. * Used to modify the offsets of the created proposals. ('Non Eating') * @param contextOffset The offset at which the context presumable start or -1. * @param jproject The Java project to which the underlying source belongs. * Needed to find types referred. * @param cu The compilation unit that is edited. Used to add import statements. * Can be <code>null</code> if no import statements should be added. */ public void reset(int codeAssistOffset, int contextOffset, IJavaProject jproject, ICompilationUnit cu) { fJavaProject= jproject; fCompilationUnit= cu; fCodeAssistOffset= codeAssistOffset; fContextOffset= contextOffset; fUserReplacementLength= -1; fLastProblem= null; for (int i= 0; i < fResults.length; i++) fResults[i].clear(); } /** * Specifies the context of the code assist operation. * @param codeAssistOffset The Offset on which the code assist will be called. * Used to modify the offsets of the created proposals. ('Non Eating') * @param jproject The Java project to which the underlying source belongs. * Needed to find types referred. * @param cu The compilation unit that is edited. Used to add import statements. * Can be <code>null</code> if no import statements should be added. */ public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) { reset(codeAssistOffset, -1, jproject, cu); } /** * If the replacement length is set, it overrides the length returned from * the content assist infrastructure. * Use this setting if code assist is called with a none empty selection. */ public void setReplacementLength(int length) { fUserReplacementLength= length; } /** * If set, proposals created will not remove characters after the code assist position * @param preventEating The preventEating to set */ public void setPreventEating(boolean preventEating) { fPreventEating= preventEating; } }
23,685
Bug 23685 nls wizards: unconventional name for Messages should not be an error
null
resolved fixed
2cfef85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-18T15:12:27Z
2002-09-18T09:06:40Z
org.eclipse.jdt.ui/ui
23,685
Bug 23685 nls wizards: unconventional name for Messages should not be an error
null
resolved fixed
2cfef85
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-18T15:12:27Z
2002-09-18T09:06:40Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/nls/ExternalizeWizardPage2.java
23,838
Bug 23838 Error ticks don't show up in Types view
20020917 The error icons don't show up in types view if they are inside a class. They only appear if they are above the first type.
resolved fixed
ecaa749
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-19T14:25:11Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/TopLevelTypeProblemsLabelDecorator.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.browsing; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.ISourceReference; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.ui.ProblemsLabelDecorator; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; /** * Decorates top-level types with problem markers that * are above the first type. */ class TopLevelTypeProblemsLabelDecorator extends ProblemsLabelDecorator { public TopLevelTypeProblemsLabelDecorator(ImageDescriptorRegistry registry) { super(registry); } /* (non-Javadoc) * @see org.eclipse.jdt.ui.ProblemsLabelDecorator#isInside(int, ISourceReference) */ protected boolean isInside(int pos, ISourceReference sourceElement) throws CoreException { if (!(sourceElement instanceof IType) || ((IType)sourceElement).getDeclaringType() != null) return false; ICompilationUnit cu= ((IType)sourceElement).getCompilationUnit(); if (cu == null) return false; IType[] types= cu.getAllTypes(); if (types.length < 1) return false; ISourceRange range= types[0].getSourceRange(); return pos < range.getOffset(); } }
20,213
Bug 20213 Code assist could show static methods|fields with different icons
It would be good if one could distinguish between static methods and normal methods within the code assist. Eg. Thread.sleep(xxx) is static, but if you use Thread t=Thread.current(); t.sleep(xxx); you could think is local method.
resolved fixed
7eefb0c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T10:44:04Z
2002-06-13T14:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/java/ResultCollector.java
package org.eclipse.jdt.internal.ui.text.java; /* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ import java.util.ArrayList; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jdt.core.CompletionRequestorAdapter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.ui.JavaElementImageDescriptor; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.viewsupport.ImageDescriptorRegistry; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; /** * Bin to collect the proposal of the infrastructure on code assist in a java text. */ public class ResultCollector extends CompletionRequestorAdapter { private final static char[] METHOD_WITH_ARGUMENTS_TRIGGERS= new char[] { '(', '-', ' ' }; private final static char[] METHOD_TRIGGERS= new char[] { ';', ',', '.', '\t', '[', ' ' }; private final static char[] TYPE_TRIGGERS= new char[] { '.', '\t', '[', '(', ' ' }; private final static char[] VAR_TRIGGER= new char[] { '\t', ' ', '=', ';' }; protected IJavaProject fJavaProject; protected ICompilationUnit fCompilationUnit; // set when imports can be added protected int fCodeAssistOffset; protected int fContextOffset; private ArrayList fFields= new ArrayList(), fKeywords= new ArrayList(10), fLabels= new ArrayList(10), fMethods= new ArrayList(), fModifiers= new ArrayList(10), fPackages= new ArrayList(), fTypes= new ArrayList(), fVariables= new ArrayList(); private IProblem fLastProblem; private ImageDescriptorRegistry fRegistry= JavaPlugin.getImageDescriptorRegistry(); private ArrayList[] fResults = new ArrayList[] { fPackages, fLabels, fModifiers, fKeywords, fTypes, fMethods, fFields, fVariables }; private int fUserReplacementLength; /* * Is eating code assist enabled or disabled? PR #3666 * When eating is enabled, JavaCompletionProposal must be revisited: PR #5533 */ private boolean fPreventEating= true; /* * @see ICompletionRequestor#acceptClass */ public void acceptClass(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(false, false, modifiers); if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance)); } /* * @see ICompletionRequestor#acceptError */ public void acceptError(IProblem error) { fLastProblem= error; } /* * @see ICompletionRequestor#acceptField */ public void acceptField( char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[] typePackageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= getFieldDescriptor(modifiers); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(name); if (typeName.length > 0) { nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(typeName); } if (declaringTypeName != null && declaringTypeName.length > 0) { nameBuffer.append(" - "); //$NON-NLS-1$ nameBuffer.append(declaringTypeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance); proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name)); proposal.setTriggerCharacters(VAR_TRIGGER); fFields.add(proposal); } /* * @see ICompletionRequestor#acceptInterface */ public void acceptInterface(char[] packageName, char[] typeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= JavaElementImageProvider.getTypeImageDescriptor(true, false, modifiers); if (Flags.isDeprecated(modifiers)) descriptor= getDeprecatedDescriptor(descriptor); ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), descriptor, new String(typeName), new String(packageName), info, relevance)); } /* * @see ICompletionRequestor#acceptAnonymousType */ public void acceptAnonymousType(char[] superTypePackageName, char[] superTypeName, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int modifiers, int completionStart, int completionEnd, int relevance) { JavaCompletionProposal proposal= createAnonymousTypeCompletion(superTypePackageName, superTypeName, parameterTypeNames, parameterNames, completionName, completionStart, completionEnd, relevance); proposal.setProposalInfo(new ProposalInfo(fJavaProject, superTypePackageName, superTypeName)); fTypes.add(proposal); } /* * @see ICompletionRequestor#acceptKeyword */ public void acceptKeyword(char[] keyword, int start, int end, int relevance) { String kw= new String(keyword); fKeywords.add(createCompletion(start, end, kw, null, kw, relevance)); } /* * @see ICompletionRequestor#acceptLabel */ public void acceptLabel(char[] labelName, int start, int end, int relevance) { String ln= new String(labelName); fLabels.add(createCompletion(start, end, ln, null, ln, relevance)); } /* * @see ICompletionRequestor#acceptLocalVariable */ public void acceptLocalVariable(char[] name, char[] typePackageName, char[] typeName, int modifiers, int start, int end, int relevance) { StringBuffer buf= new StringBuffer(); buf.append(name); if (typeName != null) { buf.append(" "); //$NON-NLS-1$ buf.append(typeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(name), JavaPluginImages.DESC_OBJS_LOCAL_VARIABLE, buf.toString(), relevance); proposal.setTriggerCharacters(VAR_TRIGGER); fVariables.add(proposal); } protected String getParameterSignature(char[][] parameterTypeNames, char[][] parameterNames) { StringBuffer buf = new StringBuffer(); if (parameterTypeNames != null) { for (int i = 0; i < parameterTypeNames.length; i++) { if (i > 0) { buf.append(','); buf.append(' '); } buf.append(parameterTypeNames[i]); if (parameterNames != null && parameterNames[i] != null) { buf.append(' '); buf.append(parameterNames[i]); } } } return buf.toString(); } /* * @see ICompletionRequestor#acceptMethod */ public void acceptMethod(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) { if (completionName == null) return; JavaCompletionProposal proposal= createMethodCallCompletion(declaringTypeName, name, parameterPackageNames, parameterTypeNames, parameterNames, returnTypeName, completionName, modifiers, start, end, relevance); boolean isConstructor= returnTypeName == null ? true : returnTypeName.length == 0; proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, isConstructor)); boolean hasOpeningBracket= completionName.length == 0 || (completionName.length > 0 && completionName[completionName.length - 1] == ')'); ProposalContextInformation contextInformation= null; if (hasOpeningBracket && parameterTypeNames.length > 0) { contextInformation= new ProposalContextInformation(); contextInformation.setInformationDisplayString(getParameterSignature(parameterTypeNames, parameterNames)); contextInformation.setContextDisplayString(proposal.getDisplayString()); contextInformation.setImage(proposal.getImage()); int position= (completionName.length == 0) ? fContextOffset : -1; contextInformation.setContextInformationPosition(position); proposal.setContextInformation(contextInformation); } boolean userMustCompleteParameters= (contextInformation != null && completionName.length > 0); char[] triggers= userMustCompleteParameters ? METHOD_WITH_ARGUMENTS_TRIGGERS : METHOD_TRIGGERS; proposal.setTriggerCharacters(triggers); if (userMustCompleteParameters) { // set the cursor before the closing bracket proposal.setCursorPosition(completionName.length - 1); } fMethods.add(proposal); } /* * @see ICompletionRequestor#acceptModifier */ public void acceptModifier(char[] modifier, int start, int end, int relevance) { String mod= new String(modifier); fModifiers.add(createCompletion(start, end, mod, null, mod, relevance)); } /* * @see ICompletionRequestor#acceptPackage */ public void acceptPackage(char[] packageName, char[] completionName, int start, int end, int relevance) { fPackages.add(createCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_PACKAGE, new String(packageName), relevance)); } /* * @see ICompletionRequestor#acceptType */ public void acceptType(char[] packageName, char[] typeName, char[] completionName, int start, int end, int relevance) { ProposalInfo info= new ProposalInfo(fJavaProject, packageName, typeName); fTypes.add(createTypeCompletion(start, end, new String(completionName), JavaPluginImages.DESC_OBJS_CLASS, new String(typeName), new String(packageName), info, relevance)); } /* * @see ICodeCompletionRequestor#acceptMethodDeclaration */ public void acceptMethodDeclaration(char[] declaringTypePackageName, char[] declaringTypeName, char[] name, char[][] parameterPackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypePackageName, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) { StringBuffer displayString= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName); StringBuffer typeName= new StringBuffer(); if (declaringTypePackageName.length > 0) { typeName.append(declaringTypePackageName); typeName.append('.'); } typeName.append(declaringTypeName); String[] paramTypes= new String[parameterTypeNames.length]; for (int i= 0; i < parameterTypeNames.length; i++) { paramTypes[i]= Signature.createTypeSignature(parameterTypeNames[i], true); } JavaCompletionProposal proposal= new MethodStubCompletionProposal(fJavaProject, fCompilationUnit, typeName.toString(), new String(name), paramTypes, start, getLength(start, end), displayString.toString(), new String(completionName)); proposal.setImage(getImage(getMemberDescriptor(modifiers))); proposal.setProposalInfo(new ProposalInfo(fJavaProject, declaringTypePackageName, declaringTypeName, name, parameterPackageNames, parameterTypeNames, returnTypeName.length == 0)); proposal.setRelevance(relevance); fMethods.add(proposal); } /* * @see ICodeCompletionRequestor#acceptVariableName */ public void acceptVariableName(char[] typePackageName, char[] typeName, char[] name, char[] completionName, int start, int end, int relevance) { // XXX: To be revised StringBuffer buf= new StringBuffer(); buf.append(name); if (typeName != null && typeName.length > 0) { buf.append(" - "); //$NON-NLS-1$ buf.append(typeName); } JavaCompletionProposal proposal= createCompletion(start, end, new String(completionName), null, buf.toString(), relevance); proposal.setTriggerCharacters(VAR_TRIGGER); fVariables.add(proposal); } public String getErrorMessage() { if (fLastProblem != null) return fLastProblem.getMessage(); return ""; //$NON-NLS-1$ } public JavaCompletionProposal[] getResults() { // return unsorted int totLen= 0; for (int i= 0; i < fResults.length; i++) { totLen += fResults[i].size(); } JavaCompletionProposal[] result= new JavaCompletionProposal[totLen]; int k= 0; for (int i= 0; i < fResults.length; i++) { ArrayList curr= fResults[i]; int currLen= curr.size(); for (int j= 0; j < currLen; j++) { JavaCompletionProposal proposal= (JavaCompletionProposal) curr.get(j); // for equal relevance, take categories proposal.setRelevance(proposal.getRelevance() * 16 + i); result[k++]= proposal; } } return result; } private StringBuffer getMethodDisplayString(char[] declaringTypeName, char[] name, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName) { StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(name); nameBuffer.append('('); if (parameterTypeNames != null && parameterTypeNames.length > 0) { nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames)); } nameBuffer.append(')'); if (returnTypeName != null && returnTypeName.length > 0) { nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(returnTypeName); } if (declaringTypeName != null && declaringTypeName.length > 0) { nameBuffer.append(" - "); //$NON-NLS-1$ nameBuffer.append(declaringTypeName); } return nameBuffer; } protected JavaCompletionProposal createMethodCallCompletion(char[] declaringTypeName, char[] name, char[][] parameterTypePackageNames, char[][] parameterTypeNames, char[][] parameterNames, char[] returnTypeName, char[] completionName, int modifiers, int start, int end, int relevance) { ImageDescriptor descriptor= getMemberDescriptor(modifiers); StringBuffer nameBuffer= getMethodDisplayString(declaringTypeName, name, parameterTypeNames, parameterNames, returnTypeName); return createCompletion(start, end, new String(completionName), descriptor, nameBuffer.toString(), relevance); } protected JavaCompletionProposal createAnonymousTypeCompletion(char[] declaringTypePackageName, char[] declaringTypeName, char[][] parameterTypeNames, char[][] parameterNames, char[] completionName, int start, int end, int relevance) { StringBuffer declTypeBuf= new StringBuffer(); if (declaringTypePackageName.length > 0) { declTypeBuf.append(declaringTypePackageName); declTypeBuf.append('.'); } declTypeBuf.append(declaringTypeName); StringBuffer nameBuffer= new StringBuffer(); nameBuffer.append(declaringTypeName); nameBuffer.append('('); if (parameterTypeNames.length > 0) { nameBuffer.append(getParameterSignature(parameterTypeNames, parameterNames)); } nameBuffer.append(')'); nameBuffer.append(" "); //$NON-NLS-1$ nameBuffer.append(JavaTextMessages.getString("ResultCollector.anonymous_type")); //$NON-NLS-1$ int length= end - start; return new AnonymousTypeCompletionProposal(fJavaProject, fCompilationUnit, start, length, new String(completionName), nameBuffer.toString(), declTypeBuf.toString(), relevance); } protected JavaCompletionProposal createTypeCompletion(int start, int end, String completion, ImageDescriptor descriptor, String typeName, String containerName, ProposalInfo proposalInfo, int relevance) { StringBuffer buf= new StringBuffer(typeName); if (containerName != null) { buf.append(" - "); //$NON-NLS-1$ if (containerName.length() > 0) { buf.append(containerName); } else { buf.append(JavaTextMessages.getString("ResultCollector.default_package")); //$NON-NLS-1$ } } String name= buf.toString(); ICompilationUnit cu= null; if (containerName != null && fCompilationUnit != null) { if (completion.equals(JavaModelUtil.concatenateName(containerName, typeName))) { cu= fCompilationUnit; } } JavaCompletionProposal proposal= new JavaTypeCompletionProposal(completion, cu, start, getLength(start, end), getImage(descriptor), name, relevance, typeName, containerName); proposal.setProposalInfo(proposalInfo); proposal.setTriggerCharacters(TYPE_TRIGGERS); return proposal; } protected ImageDescriptor getMemberDescriptor(int modifiers) { ImageDescriptor desc= JavaElementImageProvider.getMethodImageDescriptor(false, modifiers); if (Flags.isDeprecated(modifiers)) return getDeprecatedDescriptor(desc); return desc; } protected ImageDescriptor getFieldDescriptor(int modifiers) { ImageDescriptor desc= JavaElementImageProvider.getFieldImageDescriptor(false, modifiers); if (Flags.isDeprecated(modifiers)) return getDeprecatedDescriptor(desc); return desc; } protected ImageDescriptor getDeprecatedDescriptor(ImageDescriptor descriptor) { Point size= new Point(16, 16); return new JavaElementImageDescriptor(descriptor, JavaElementImageDescriptor.WARNING, size); } protected JavaCompletionProposal createCompletion(int start, int end, String completion, ImageDescriptor descriptor, String name, int relevance) { return new JavaCompletionProposal(completion, start, getLength(start, end), getImage(descriptor), name, relevance); } private int getLength(int start, int end) { int length; if (fUserReplacementLength == -1) { length= fPreventEating ? fCodeAssistOffset - start : end - start; } else { length= fUserReplacementLength; // extend length to begin at start if (start < fCodeAssistOffset) { length+= fCodeAssistOffset - start; } } return length; } private Image getImage(ImageDescriptor descriptor) { return (descriptor == null) ? null : fRegistry.get(descriptor); } /** * Specifies the context of the code assist operation. * @param codeAssistOffset The Offset at which the code assist will be called. * Used to modify the offsets of the created proposals. ('Non Eating') * @param contextOffset The offset at which the context presumable start or -1. * @param jproject The Java project to which the underlying source belongs. * Needed to find types referred. * @param cu The compilation unit that is edited. Used to add import statements. * Can be <code>null</code> if no import statements should be added. */ public void reset(int codeAssistOffset, int contextOffset, IJavaProject jproject, ICompilationUnit cu) { fJavaProject= jproject; fCompilationUnit= cu; fCodeAssistOffset= codeAssistOffset; fContextOffset= contextOffset; fUserReplacementLength= -1; fLastProblem= null; for (int i= 0; i < fResults.length; i++) fResults[i].clear(); } /** * Specifies the context of the code assist operation. * @param codeAssistOffset The Offset on which the code assist will be called. * Used to modify the offsets of the created proposals. ('Non Eating') * @param jproject The Java project to which the underlying source belongs. * Needed to find types referred. * @param cu The compilation unit that is edited. Used to add import statements. * Can be <code>null</code> if no import statements should be added. */ public void reset(int codeAssistOffset, IJavaProject jproject, ICompilationUnit cu) { reset(codeAssistOffset, -1, jproject, cu); } /** * If the replacement length is set, it overrides the length returned from * the content assist infrastructure. * Use this setting if code assist is called with a none empty selection. */ public void setReplacementLength(int length) { fUserReplacementLength= length; } /** * If set, proposals created will not remove characters after the code assist position * @param preventEating The preventEating to set */ public void setPreventEating(boolean preventEating) { fPreventEating= preventEating; } }
20,474
Bug 20474 [Dialogs] SelectionDialog should not return an initial selection of null
F3 The JavaDoc for SelectionDialog.getInitialSelection does not state that null is a valid return value. If we think that clients are acutally using the null case to avoid performing some real work then we should fix the javadoc. Otherwise we should an empty list.
closed fixed
448a64f
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T12:07:58Z
2002-06-17T16:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/dialogs/MultiElementListSelectionDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.dialogs; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog; import org.eclipse.jdt.internal.ui.JavaUIMessages; /** * A class to select elements out of a list of elements, organized on multiple * pages. */ public class MultiElementListSelectionDialog extends AbstractElementListSelectionDialog { private static class Page { public Object[] elements; public String filter; public boolean okState= false; public Page(Object[] elements) { this.elements= elements; } }; private Page[] fPages; private int fCurrentPage; private int fNumberOfPages; private Button fFinishButton; private Button fBackButton; private Button fNextButton; private Label fPageInfoLabel; private String fPageInfoMessage= JavaUIMessages.getString("MultiElementListSelectionDialog.pageInfoMessage"); //$NON-NLS-1$; /** * Constructs a multi-page list selection dialog. * @param renderer the label renderer. * @param ignoreCase specifies if sorting and filtering ignores cases. * @param multipleSelection specifies if multiple selection is allowed. */ public MultiElementListSelectionDialog(Shell parent, ILabelProvider renderer) { super(parent, renderer); } /** * Sets message shown in the right top corner. Use {0} and {1} as placeholders * for the current and the total number of pages. * @param message the message. */ public void setPageInfoMessage(String message) { fPageInfoMessage= message; } /** * Sets the elements to be displayed in the dialog. * @param elements an array of pages holding arrays of elements */ public void setElements(Object[][] elements) { fNumberOfPages= elements.length; fPages= new Page[fNumberOfPages]; for (int i= 0; i != fNumberOfPages; i++) fPages[i]= new Page(elements[i]); initializeResult(fNumberOfPages); } /* * @see Window#open() */ public int open() { List selection= getInitialSelections(); if (selection == null) { setInitialSelections(new Object[fNumberOfPages]); selection= getInitialSelections(); } Assert.isTrue(selection.size() == fNumberOfPages); return super.open(); } /** * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { Composite contents= (Composite) super.createDialogArea(parent); createMessageArea(contents); createFilterText(contents); createFilteredList(contents); fCurrentPage= 0; setPageData(); return contents; } /** * @see Dialog#createButtonsForButtonBar(Composite) */ protected void createButtonsForButtonBar(Composite parent) { fBackButton= createButton(parent, IDialogConstants.BACK_ID, IDialogConstants.BACK_LABEL, false); fNextButton= createButton(parent, IDialogConstants.NEXT_ID, IDialogConstants.NEXT_LABEL, true); fFinishButton= createButton(parent, IDialogConstants.OK_ID, IDialogConstants.FINISH_LABEL, false); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } /** * @see SelectionDialog#createMessageArea(Composite) */ protected Label createMessageArea(Composite parent) { Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.horizontalSpacing= 5; layout.numColumns= 2; composite.setLayout(layout); GridData data= new GridData(GridData.HORIZONTAL_ALIGN_FILL); composite.setLayoutData(data); Label messageLabel= super.createMessageArea(composite); fPageInfoLabel= new Label(composite, SWT.NULL); fPageInfoLabel.setText(getPageInfoMessage()); data= new GridData(GridData.HORIZONTAL_ALIGN_FILL); data.horizontalAlignment= data.END; fPageInfoLabel.setLayoutData(data); return messageLabel; } /** * @see SelectionStatusDialog#computeResult() */ protected void computeResult() { setResult(fCurrentPage, getSelectedElements()); } /** * @see Dialog#buttonPressed(int) */ protected void buttonPressed(int buttonId) { if (buttonId == IDialogConstants.BACK_ID) { turnPage(false); } else if (buttonId == IDialogConstants.NEXT_ID) { turnPage(true); } else { super.buttonPressed(buttonId); } } /** * @see AbstractElementListSelectionDialog#handleDefaultSelected() */ protected void handleDefaultSelected() { if (validateCurrentSelection()) { if (fCurrentPage == fNumberOfPages - 1) { buttonPressed(IDialogConstants.OK_ID); } else { buttonPressed(IDialogConstants.NEXT_ID); } } } /** * @see AbstractElementListSelectionDialog#updateButtonsEnableState(IStatus) */ protected void updateButtonsEnableState(IStatus status) { boolean isOK= !status.matches(IStatus.ERROR); fPages[fCurrentPage].okState= isOK; boolean isAllOK= isOK; for (int i= 0; i != fNumberOfPages; i++) isAllOK = isAllOK && fPages[i].okState; fFinishButton.setEnabled(isAllOK); boolean nextButtonEnabled= isOK && (fCurrentPage < fNumberOfPages - 1); fNextButton.setEnabled(nextButtonEnabled); fBackButton.setEnabled(fCurrentPage != 0); if (nextButtonEnabled) { getShell().setDefaultButton(fNextButton); } else if (isAllOK) { getShell().setDefaultButton(fFinishButton); } } private void turnPage(boolean toNextPage) { Page page= fPages[fCurrentPage]; // store filter String filter= getFilter(); if (filter == null) filter= ""; //$NON-NLS-1$ page.filter= filter; // store selection Object[] selectedElements= getSelectedElements(); List list= getInitialSelections(); list.set(fCurrentPage, selectedElements); // store result setResult(fCurrentPage, getSelectedElements()); if (toNextPage) { if (fCurrentPage + 1 >= fNumberOfPages) return; fCurrentPage++; } else { if (fCurrentPage - 1 < 0) return; fCurrentPage--; } if (fPageInfoLabel != null && !fPageInfoLabel.isDisposed()) fPageInfoLabel.setText(getPageInfoMessage()); setPageData(); validateCurrentSelection(); } private void setPageData() { Page page= fPages[fCurrentPage]; // 1. set elements setListElements(page.elements); // 2. apply filter String filter= page.filter; if (filter == null) filter= ""; //$NON-NLS-1$ setFilter(filter); // 3. select elements Object[] selectedElements= (Object[]) getInitialSelections().get(fCurrentPage); setSelection(selectedElements); fFilteredList.setFocus(); } private String getPageInfoMessage() { if (fPageInfoMessage == null) return ""; //$NON-NLS-1$ String[] args= new String[] { Integer.toString(fCurrentPage + 1), Integer.toString(fNumberOfPages) }; return MessageFormat.format(fPageInfoMessage, args); } private void initializeResult(int length) { List result= new ArrayList(length); for (int i= 0; i != length; i++) result.add(null); setResult(result); } /** * Gets the current Page. * @return Returns a int */ public int getCurrentPage() { return fCurrentPage; } }
23,860
Bug 23860 bogus char left in refactoring input page - preview
select an expression, extract as temp enter 'xxx' as name, hit backspace 3 times - it stays 'x'
resolved fixed
d1df19a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T13:01:39Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,860
Bug 23860 bogus char left in refactoring input page - preview
select an expression, extract as temp enter 'xxx' as name, hit backspace 3 times - it stays 'x'
resolved fixed
d1df19a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T13:01:39Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractTempInputPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractInterfaceInputPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractTempInputPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/MoveInnerToToplnputPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameFieldInputWizardPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameFieldWizard.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameInputWizardPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/RenameRefactoringWizard.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/TextInputWizardPage.java
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
org.eclipse.jdt.ui/ui
23,861
Bug 23861 Extract Local Variable Input Page - does not show warning message for atypical but valid variable names (e.g. begins with uppercase letter)
The input page should show warning message (in the bar containing the refactoring name near the top of the page) for atypical but valid variable names (e.g. begins with uppercase letter). Code is already present for doing this, but it does not acheive its desired effect.
resolved fixed
a6929fb
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:41:38Z
2002-09-19T15:40:00Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/code/ExtractMethodInputPage.java
23,725
Bug 23725 Move To Top Level: compilation error when moving an inner class extending another #2[refactoring]
Consider the following case: public class Outer { public static class A {} public class B extends A {} } If I move Outer.B to top level, I end up with a compilation error. This can be fixed by qualifying the base class (Outer.A).
resolved wontfix
83c609a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:55:56Z
2002-09-18T14:40:00Z
org.eclipse.jdt.ui.tests.refactoring/test
23,725
Bug 23725 Move To Top Level: compilation error when moving an inner class extending another #2[refactoring]
Consider the following case: public class Outer { public static class A {} public class B extends A {} } If I move Outer.B to top level, I end up with a compilation error. This can be fixed by qualifying the base class (Outer.A).
resolved wontfix
83c609a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-20T15:55:56Z
2002-09-18T14:40:00Z
cases/org/eclipse/jdt/ui/tests/refactoring/MoveInnerToTopLevelTests.java
23,783
Bug 23783 Quick fix internal errors when missing method return type
Build 20020917 (2.1 stream) 1) Create the following type: public class A { public static getFoo() { return foo; } } 2) After saving, there will be a red sqiggle under "foo". 3) Place cursor on "foo" and invoke Quick Fix (tm) An internal error is dumped to the console. A stack is logged. 4) Select the Quick Fix option "create field 'foo'" Another internal error is dumped to console and logged. Log file is attached.
resolved fixed
010e095
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T10:40:06Z
2002-09-18T20:13:20Z
org.eclipse.jdt.ui/core
23,783
Bug 23783 Quick fix internal errors when missing method return type
Build 20020917 (2.1 stream) 1) Create the following type: public class A { public static getFoo() { return foo; } } 2) After saving, there will be a red sqiggle under "foo". 3) Place cursor on "foo" and invoke Quick Fix (tm) An internal error is dumped to the console. A stack is logged. 4) Select the Quick Fix option "create field 'foo'" Another internal error is dumped to console and logged. Log file is attached.
resolved fixed
010e095
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T10:40:06Z
2002-09-18T20:13:20Z
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteAnalyzer.java
15,370
Bug 15370 [misc] Files with non-platform line termination must be flagged
Eclipse interactive editors (like the Java source code editor) appear to write files using the platform's line termination character(s). This is '\n' on Unix and '\r\n' on Windows. Some other non-interactive "editors" (called "process" editors in the validateEdit document) do not consistently follow this rule. For instance, the '.classpath' process editor writes '\n' even on Windows. This inconsistency can cause ugly problems with CM systems that expect all text files to use the same line termination style. These problems can be very confusing to the users (which is why I marked the Severity as "major"). They can be avoided if the CM systems knows to treat the file as something other than a text file. Thus, Eclipse needs a mechanism whereby Team providers can ask if the file/resource should be treated as something other than a text file (even though it only contains text). Any creator of a file that creates a file that will not conform to the line termination style of the platform when written must mark the resource utilizing this mechanism. -------------------------------------------------------------------------------- Historical note: When this issue was first discussed, the following solution was proposed but rejected: 1) When a file already exists, the editor must write changes out using the line termination style of the pre-existing file (i.e. that it read in when it started the edit session). 2) If the editor is writing a new file or a file that was empty, there should be a new Eclipse-wide preference that will determine the line termination style used. The preference values would be: - Platform default - Windows style ("\r\n") - Unix style ("\n") 3) If a file already exists but has a mixture of line termination styles, the editor should either ask the user for the style to use or use the style indicated by the new Eclipse-wide preference. --------------------------------------------------------------------------------
verified fixed
c3fd82c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T10:44:41Z
2002-05-06T21:20:00Z
org.eclipse.jdt.ui/core
15,370
Bug 15370 [misc] Files with non-platform line termination must be flagged
Eclipse interactive editors (like the Java source code editor) appear to write files using the platform's line termination character(s). This is '\n' on Unix and '\r\n' on Windows. Some other non-interactive "editors" (called "process" editors in the validateEdit document) do not consistently follow this rule. For instance, the '.classpath' process editor writes '\n' even on Windows. This inconsistency can cause ugly problems with CM systems that expect all text files to use the same line termination style. These problems can be very confusing to the users (which is why I marked the Severity as "major"). They can be avoided if the CM systems knows to treat the file as something other than a text file. Thus, Eclipse needs a mechanism whereby Team providers can ask if the file/resource should be treated as something other than a text file (even though it only contains text). Any creator of a file that creates a file that will not conform to the line termination style of the platform when written must mark the resource utilizing this mechanism. -------------------------------------------------------------------------------- Historical note: When this issue was first discussed, the following solution was proposed but rejected: 1) When a file already exists, the editor must write changes out using the line termination style of the pre-existing file (i.e. that it read in when it started the edit session). 2) If the editor is writing a new file or a file that was empty, there should be a new Eclipse-wide preference that will determine the line termination style used. The preference values would be: - Platform default - Windows style ("\r\n") - Unix style ("\n") 3) If a file already exists but has a mixture of line termination styles, the editor should either ask the user for the style to use or use the style indicated by the new Eclipse-wide preference. --------------------------------------------------------------------------------
verified fixed
c3fd82c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T10:44:41Z
2002-05-06T21:20:00Z
extension/org/eclipse/jdt/internal/corext/template/java/JavaFormatter.java
23,968
Bug 23968 Abusive check on task tags
2.1M1 Java UI ensures that task tags are valid Java identifiers. Why is it so ? JDT/Core supports any type of tags. In particular, "TODO:" should work fine, and was one of the mentionned tags on the original feature request.
resolved fixed
2671b49
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:23:43Z
2002-09-23T11:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.StringTokenizer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.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.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; /* * The page for setting the compiler options. */ public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { // Preference store keys, see JavaCore.getOptions private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR; private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR; private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR; private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL; private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE; private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT; private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD; private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME; private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION; private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK; private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL; private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER; private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION; private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL; private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER; private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT; private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT; private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER; private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE; private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE; private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER; private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH; private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH; private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH; private static final String PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE; private static final String PREF_COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$ // values private static final String GENERATE= JavaCore.GENERATE; private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE; private static final String PRESERVE= JavaCore.PRESERVE; private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT; private static final String VERSION_1_1= JavaCore.VERSION_1_1; private static final String VERSION_1_2= JavaCore.VERSION_1_2; private static final String VERSION_1_3= JavaCore.VERSION_1_3; private static final String VERSION_1_4= JavaCore.VERSION_1_4; private static final String ERROR= JavaCore.ERROR; private static final String WARNING= JavaCore.WARNING; private static final String IGNORE= JavaCore.IGNORE; private static final String ABORT= JavaCore.ABORT; private static final String ENABLED= JavaCore.ENABLED; private static final String DISABLED= JavaCore.DISABLED; private static final String DEFAULT= "default"; //$NON-NLS-1$ private static final String USER= "user"; //$NON-NLS-1$ private static String[] getAllKeys() { return new String[] { PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL, PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL, PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS, PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE, PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH, PREF_PB_CIRCULAR_BUILDPATH, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_COMPILER_TASK_TAGS }; } /** * Initializes the current options (read from preference store) */ public static void initDefaults(IPreferenceStore store) { } private static class ControlData { private String fKey; private String[] fValues; public ControlData(String key, String[] values) { fKey= key; fValues= values; } public String getKey() { return fKey; } public String getValue(boolean selection) { int index= selection ? 0 : 1; return fValues[index]; } public String getValue(int index) { return fValues[index]; } public int getSelection(String value) { for (int i= 0; i < fValues.length; i++) { if (value.equals(fValues[i])) { return i; } } throw new IllegalArgumentException(); } } private Hashtable fWorkingValues; private ArrayList fCheckBoxes; private ArrayList fComboBoxes; private ArrayList fTextBoxes; private SelectionListener fSelectionListener; private ModifyListener fTextModifyListener; private ArrayList fComplianceControls; IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus, fTaskTagsStatus; public CompilerPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(JavaUIMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$ fWorkingValues= JavaCore.getOptions(); fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance()); fCheckBoxes= new ArrayList(); fComboBoxes= new ArrayList(); fTextBoxes= new ArrayList(2); fComplianceControls= new ArrayList(); fSelectionListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) {} public void widgetSelected(SelectionEvent e) { controlChanged(e.widget); } }; fTextModifyListener= new ModifyListener() { public void modifyText(ModifyEvent e) { textChanged((Text) e.widget); } }; fComplianceStatus= new StatusInfo(); fMaxNumberProblemsStatus= new StatusInfo(); fResourceFilterStatus= new StatusInfo(); fTaskTagsStatus= new StatusInfo(); } /** * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } /** * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE); } /** * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDialogUnits(parent); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); Composite warningsComposite= createWarningsTabContent(folder); Composite markersComposite= createMarkersTabContent(folder); Composite codeGenComposite= createCodeGenTabContent(folder); Composite complianceComposite= createComplianceTabContent(folder); Composite othersComposite= createOthersTabContent(folder); TabItem item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.tabtitle")); //$NON-NLS-1$ item.setControl(warningsComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.tabtitle")); //$NON-NLS-1$ item.setControl(markersComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.generation.tabtitle")); //$NON-NLS-1$ item.setControl(codeGenComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.compliance.tabtitle")); //$NON-NLS-1$ item.setControl(complianceComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.others.tabtitle")); //$NON-NLS-1$ item.setControl(othersComposite); validateSettings(null, null); return folder; } private Composite createMarkersTabContent(TabFolder folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$ }; String[] enabledDisabled= new String[] { ENABLED, DISABLED }; Composite markersComposite= new Composite(folder, SWT.NULL); markersComposite.setLayout(new GridLayout()); GridLayout layout= new GridLayout(); layout.numColumns= 2; Group group= new Group(markersComposite, SWT.NONE); group.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.deprecated.label")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); int indent= convertWidthInCharsToPixels(2); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$ addCheckBox(group, label, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, indent); layout= new GridLayout(); layout.numColumns= 1; group= new Group(markersComposite, SWT.NONE); group.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.taskmarkers.label")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); label= JavaUIMessages.getString("CompilerPreferencePage.pb_todo_comments.label"); //$NON-NLS-1$ Text text= addTextField(group, label, PREF_COMPILER_TASK_TAGS); GridData gd= (GridData) text.getLayoutData(); gd.grabExcessHorizontalSpace= true; gd.widthHint= convertWidthInCharsToPixels(10); layout= new GridLayout(); layout.numColumns= 2; group= new Group(markersComposite, SWT.NONE); group.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.nls.label")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); label= JavaUIMessages.getString("CompilerPreferencePage.pb_non_externalized_strings.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0); return markersComposite; } private Composite createOthersTabContent(TabFolder folder) { String[] abortIgnoreValues= new String[] { ABORT, IGNORE }; String[] errorWarning= new String[] { ERROR, WARNING }; String[] errorWarningLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning") //$NON-NLS-1$ }; GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite othersComposite= new Composite(folder, SWT.NULL); othersComposite.setLayout(layout); Label description= new Label(othersComposite, SWT.WRAP); description.setText(JavaUIMessages.getString("CompilerPreferencePage.build_warnings.description")); //$NON-NLS-1$ GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; // gd.widthHint= convertWidthInCharsToPixels(50); description.setLayoutData(gd); Composite combos= new Composite(othersComposite, SWT.NULL); gd= new GridData(GridData.FILL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; combos.setLayoutData(gd); GridLayout cl= new GridLayout(); cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0; combos.setLayout(cl); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_incomplete_build_path.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_build_path_cycles.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.build_invalid_classpath.label"); //$NON-NLS-1$ addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0); description= new Label(othersComposite, SWT.WRAP); description.setText(JavaUIMessages.getString("CompilerPreferencePage.resource_filter.description")); //$NON-NLS-1$ gd= new GridData(GridData.FILL); gd.horizontalSpan= 2; gd.widthHint= convertWidthInCharsToPixels(60); description.setLayoutData(gd); label= JavaUIMessages.getString("CompilerPreferencePage.resource_filter.label"); //$NON-NLS-1$ Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER); gd= (GridData) text.getLayoutData(); gd.grabExcessHorizontalSpace= true; gd.widthHint= convertWidthInCharsToPixels(10); return othersComposite; } private Composite createWarningsTabContent(Composite folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$ }; GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.verticalSpacing= 2; Composite warningsComposite= new Composite(folder, SWT.NULL); warningsComposite.setLayout(layout); Label description= new Label(warningsComposite, SWT.WRAP); description.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.description")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 2; gd.widthHint= convertWidthInCharsToPixels(50); description.setLayoutData(gd); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_unreachable_code.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_invalid_import.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_local.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_method_naming.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_hidden_catchblock.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_imports.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_parameter.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_static_access_receiver.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_synth_access_emul.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_max_per_unit.label"); //$NON-NLS-1$ Text text= addTextField(warningsComposite, label, PREF_PB_MAX_PER_UNIT); text.setTextLimit(6); return warningsComposite; } private Composite createCodeGenTabContent(Composite folder) { String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE }; GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite codeGenComposite= new Composite(folder, SWT.NULL); codeGenComposite.setLayout(layout); String label= JavaUIMessages.getString("CompilerPreferencePage.variable_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0); label= JavaUIMessages.getString("CompilerPreferencePage.line_number_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues, 0); label= JavaUIMessages.getString("CompilerPreferencePage.source_file_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues, 0); label= JavaUIMessages.getString("CompilerPreferencePage.codegen_unused_local.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0); return codeGenComposite; } private Composite createComplianceTabContent(Composite folder) { GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite complianceComposite= new Composite(folder, SWT.NULL); complianceComposite.setLayout(layout); String[] values34= new String[] { VERSION_1_3, VERSION_1_4 }; String[] values34Labels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.version13"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version14") //$NON-NLS-1$ }; String label= JavaUIMessages.getString("CompilerPreferencePage.compiler_compliance.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_COMPLIANCE, values34, values34Labels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.default_settings.label"); //$NON-NLS-1$ addCheckBox(complianceComposite, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0); int indent= convertWidthInCharsToPixels(2); Control[] otherChildren= complianceComposite.getChildren(); String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 }; String[] values14Labels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.version11"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version12"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version13"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version14") //$NON-NLS-1$ }; label= JavaUIMessages.getString("CompilerPreferencePage.codegen_targetplatform.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent); label= JavaUIMessages.getString("CompilerPreferencePage.source_compatibility.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent); String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$ }; label= JavaUIMessages.getString("CompilerPreferencePage.pb_assert_as_identifier.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent); Control[] allChildren= complianceComposite.getChildren(); fComplianceControls.addAll(Arrays.asList(allChildren)); fComplianceControls.removeAll(Arrays.asList(otherChildren)); return complianceComposite; } private void addCheckBox(Composite parent, String label, String key, String[] values, int indent) { ControlData data= new ControlData(key, values); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.horizontalIndent= indent; Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); checkBox.setData(data); checkBox.setLayoutData(gd); checkBox.addSelectionListener(fSelectionListener); String currValue= (String)fWorkingValues.get(key); checkBox.setSelection(data.getSelection(currValue) == 0); fCheckBoxes.add(checkBox); } private void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) { ControlData data= new ControlData(key, values); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indent; Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP); labelControl.setText(label); labelControl.setLayoutData(gd); Combo comboBox= new Combo(parent, SWT.READ_ONLY); comboBox.setItems(valueLabels); comboBox.setData(data); comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); comboBox.addSelectionListener(fSelectionListener); String currValue= (String)fWorkingValues.get(key); comboBox.select(data.getSelection(currValue)); fComboBoxes.add(comboBox); } private Text addTextField(Composite parent, String label, String key) { Label labelControl= new Label(parent, SWT.NONE); labelControl.setText(label); labelControl.setLayoutData(new GridData()); Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE); textBox.setData(key); textBox.setLayoutData(new GridData()); String currValue= (String) fWorkingValues.get(key); textBox.setText(currValue); textBox.addModifyListener(fTextModifyListener); textBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); fTextBoxes.add(textBox); return textBox; } private void controlChanged(Widget widget) { ControlData data= (ControlData) widget.getData(); String newValue= null; if (widget instanceof Button) { newValue= data.getValue(((Button)widget).getSelection()); } else if (widget instanceof Combo) { newValue= data.getValue(((Combo)widget).getSelectionIndex()); } else { return; } fWorkingValues.put(data.getKey(), newValue); validateSettings(data.getKey(), newValue); } private void textChanged(Text textControl) { String key= (String) textControl.getData(); String number= textControl.getText(); fWorkingValues.put(key, number); validateSettings(key, number); } private boolean checkValue(String key, String value) { return value.equals(fWorkingValues.get(key)); } /* (non-javadoc) * Update fields and validate. * @param changedKey Key that changed, or null, if all changed. */ private void validateSettings(String changedKey, String newValue) { if (changedKey != null) { if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) { updateComplianceEnableState(); if (DEFAULT.equals(newValue)) { updateComplianceDefaultSettings(); } } else if (PREF_COMPLIANCE.equals(changedKey)) { if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) { updateComplianceDefaultSettings(); } } else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) || PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) || PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) { fComplianceStatus= validateCompliance(); } else if (!PREF_PB_MAX_PER_UNIT.equals(changedKey)) { fMaxNumberProblemsStatus= validateMaxNumberProblems(); } else if (!PREF_RESOURCE_FILTER.equals(changedKey)) { fResourceFilterStatus= validateResourceFilters(); } else if (!PREF_COMPILER_TASK_TAGS.equals(changedKey)) { fTaskTagsStatus= validateTaskTags(); } else { return; } } else { updateComplianceEnableState(); } IStatus fComplianceStatus= validateCompliance(); IStatus fMaxNumberProblemsStatus= validateMaxNumberProblems(); IStatus fResourceFilterStatus= validateResourceFilters(); IStatus fTaskTagsStatus= validateTaskTags(); IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, validateMaxNumberProblems(), validateResourceFilters(), validateTaskTags() }); updateStatus(status); } private IStatus validateCompliance() { StatusInfo status= new StatusInfo(); if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) { if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.cpl13src14.error")); //$NON-NLS-1$ return status; } else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.cpl13trg14.error")); //$NON-NLS-1$ return status; } } if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.src14asrterr.error")); //$NON-NLS-1$ return status; } } if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.src14tgt14.error")); //$NON-NLS-1$ return status; } } return status; } private IStatus validateMaxNumberProblems() { String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT); StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value <= 0) { status.setError(JavaUIMessages.getFormattedString("CompilerPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } catch (NumberFormatException e) { status.setError(JavaUIMessages.getFormattedString("CompilerPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } private IStatus validateResourceFilters() { String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER); IWorkspace workspace= ResourcesPlugin.getWorkspace(); String[] filters= getFilters(text); for (int i= 0; i < filters.length; i++) { String fileName= filters[i].replace('*', 'x'); int resourceType= IResource.FILE; int lastCharacter= fileName.length() - 1; if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') { fileName= fileName.substring(0, lastCharacter); resourceType= IResource.FOLDER; } IStatus status= workspace.validateName(fileName, resourceType); if (status.matches(IStatus.ERROR)) { String message= JavaUIMessages.getFormattedString("CompilerPreferencePage.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$ return new StatusInfo(IStatus.ERROR, message); } } return new StatusInfo(); } private IStatus validateTaskTags() { String text= (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS); IWorkspace workspace= ResourcesPlugin.getWorkspace(); String[] tags= getFilters(text); for (int i= 0; i < tags.length; i++) { IStatus status= JavaConventions.validateIdentifier(tags[i]); if (status.matches(IStatus.ERROR)) { String message= JavaUIMessages.getFormattedString("CompilerPreferencePage.task.invalidsegment.error", status.getMessage()); //$NON-NLS-1$ return new StatusInfo(IStatus.ERROR, message); } } return new StatusInfo(); } private String[] getFilters(String text) { StringTokenizer tok= new StringTokenizer(text, ","); //$NON-NLS-1$ int nTokens= tok.countTokens(); String[] res= new String[nTokens]; for (int i= 0; i < res.length; i++) { res[i]= tok.nextToken(); } return res; } /* * Update the compliance controls' enable state */ private void updateComplianceEnableState() { boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER); for (int i= fComplianceControls.size() - 1; i >= 0; i--) { Control curr= (Control) fComplianceControls.get(i); curr.setEnabled(enabled); } } /* * Set the default compliance values derived from the chosen level */ private void updateComplianceDefaultSettings() { Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE); if (VERSION_1_3.equals(complianceLevel)) { fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE); fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3); fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1); } else if (VERSION_1_4.equals(complianceLevel)) { fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR); fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_4); fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4); } updateControls(); } /* * Evaluate if the current compliance setting correspond to a default setting */ private String getCurrentCompliance() { Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE); if ((VERSION_1_3.equals(complianceLevel) && checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE) && checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3) && checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1)) || (VERSION_1_4.equals(complianceLevel) && checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR) && checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4) && checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4))) { return DEFAULT; } return USER; } /* * @see IPreferencePage#performOk() */ public boolean performOk() { String[] allKeys= getAllKeys(); // preserve other options // store in JCore and the preferences Hashtable actualOptions= JavaCore.getOptions(); boolean hasChanges= false; for (int i= 0; i < allKeys.length; i++) { String key= allKeys[i]; String val= (String) fWorkingValues.get(key); String oldVal= (String) actualOptions.get(key); hasChanges= hasChanges | !val.equals(oldVal); actualOptions.put(key, val); } if (hasChanges) { String title= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.message"); //$NON-NLS-1$ MessageDialog dialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); int res= dialog.open(); if (res != 0 && res != 1) { JavaPlugin.getDefault().savePluginPreferences(); return false; } JavaCore.setOptions(actualOptions); if (res == 0) { doFullBuild(); } } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } public static boolean openQuestion(Shell parent, String title, String message) { MessageDialog dialog= new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); return dialog.open() == 0; } private void doFullBuild() { ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (InterruptedException e) { // cancelled by user } catch (InvocationTargetException e) { String title= JavaUIMessages.getString("CompilerPreferencePage.builderror.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("CompilerPreferencePage.builderror.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fWorkingValues= JavaCore.getDefaultOptions(); fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance()); updateControls(); validateSettings(null, null); super.performDefaults(); } private void updateControls() { // update the UI for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { Button curr= (Button) fCheckBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.setSelection(data.getSelection(currValue) == 0); } for (int i= fComboBoxes.size() - 1; i >= 0; i--) { Combo curr= (Combo) fComboBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.select(data.getSelection(currValue)); } for (int i= fTextBoxes.size() - 1; i >= 0; i--) { Text curr= (Text) fTextBoxes.get(i); String key= (String) curr.getData(); String currValue= (String) fWorkingValues.get(key); curr.setText(currValue); } } private void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/core
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
extension/org/eclipse/jdt/internal/corext/util/JavaModelUtil.java
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewClassCreationWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.wizards.NewClassWizardPage; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class NewClassCreationWizard extends NewElementWizard { private NewClassWizardPage fPage; public NewClassCreationWizard() { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWCLASS); setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(NewWizardMessages.getString("NewClassCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#createPages */ public void addPages() { super.addPages(); fPage= new NewClassWizardPage(); addPage(fPage); fPage.init(getSelection()); } /* * @see Wizard#performFinish */ public boolean performFinish() { if (finishPage(fPage.getRunnable())) { ICompilationUnit cu= fPage.getCreatedType().getCompilationUnit(); if (cu.isWorkingCopy()) { cu= (ICompilationUnit)cu.getOriginalElement(); } try { IResource resource= cu.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, only reveal and open will fail } return true; } return false; } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewElementWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; public abstract class NewElementWizard extends BasicNewResourceWizard implements INewWizard { public NewElementWizard() { setNeedsProgressMonitor(true); } /* * @see BasicNewResourceWizard#initializeDefaultPageImageDescriptor */ protected void initializeDefaultPageImageDescriptor() { // no action, we do not need the desktop default } protected void openResource(final IResource resource) { if (resource.getType() == IResource.FILE) { final IWorkbenchPage activePage= JavaPlugin.getDefault().getActivePage(); if (activePage != null) { final Display display= getShell().getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { try { activePage.openEditor((IFile)resource); } catch (PartInitException e) { JavaPlugin.log(e); } } }); } } } } /** * Run a runnable */ protected boolean finishPage(IRunnableWithProgress runnable) { IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable); try { getContainer().run(false, true, op); } catch (InvocationTargetException e) { Shell shell= getShell(); String title= NewWizardMessages.getString("NewElementWizard.op_error.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("NewElementWizard.op_error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, shell, title, message); return false; } catch (InterruptedException e) { return false; } return true; } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewInterfaceCreationWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class NewInterfaceCreationWizard extends NewElementWizard { private NewInterfaceWizardPage fPage; public NewInterfaceCreationWizard() { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWINT); setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(NewWizardMessages.getString("NewInterfaceCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#addPages */ public void addPages() { super.addPages(); fPage= new NewInterfaceWizardPage(); addPage(fPage); fPage.init(getSelection()); } /* * @see Wizard#performFinish */ public boolean performFinish() { if (finishPage(fPage.getRunnable())) { ICompilationUnit cu= fPage.getCreatedType().getCompilationUnit(); if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } try { IResource resource= cu.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, only reveal and open will fail } return true; } return false; } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewPackageCreationWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.wizards.NewPackageWizardPage; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class NewPackageCreationWizard extends NewElementWizard { private NewPackageWizardPage fPage; public NewPackageCreationWizard() { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWPACK); setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(NewWizardMessages.getString("NewPackageCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#addPages */ public void addPages() { super.addPages(); fPage= new NewPackageWizardPage(); addPage(fPage); fPage.init(getSelection()); } /* * @see Wizard#performFinish */ public boolean performFinish() { if (finishPage(fPage.getRunnable())) { IPackageFragment pack= fPage.getNewPackageFragment(); try { IResource resource= pack.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); // let pass, only reveal and open will fail } return true; } return false; } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExecutableExtension; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.wizards.newresource.BasicNewProjectResourceWizard; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; public class NewProjectCreationWizard extends NewElementWizard implements IExecutableExtension { public static final String NEW_PROJECT_WIZARD_ID= "org.eclipse.jdt.ui.wizards.NewProjectCreationWizard"; //$NON-NLS-1$ private NewProjectCreationWizardPage fJavaPage; private WizardNewProjectCreationPage fMainPage; private IConfigurationElement fConfigElement; public NewProjectCreationWizard() { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWJPRJ); setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(NewWizardMessages.getString("NewProjectCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#addPages */ public void addPages() { super.addPages(); fMainPage= new WizardNewProjectCreationPage("NewProjectCreationWizard"); //$NON-NLS-1$ fMainPage.setTitle(NewWizardMessages.getString("NewProjectCreationWizard.MainPage.title")); //$NON-NLS-1$ fMainPage.setDescription(NewWizardMessages.getString("NewProjectCreationWizard.MainPage.description")); //$NON-NLS-1$ addPage(fMainPage); fJavaPage= new NewProjectCreationWizardPage(fMainPage); addPage(fJavaPage); } /* * @see Wizard#performFinish */ public boolean performFinish() { IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(fJavaPage.getRunnable()); try { getContainer().run(false, true, op); } catch (InvocationTargetException e) { String title= NewWizardMessages.getString("NewProjectCreationWizard.op_error.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("NewProjectCreationWizard.op_error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); return false; } catch (InterruptedException e) { return false; } BasicNewProjectResourceWizard.updatePerspective(fConfigElement); selectAndReveal(fJavaPage.getJavaProject().getProject()); return true; } /* * Stores the configuration element for the wizard. The config element will be used * in <code>performFinish</code> to set the result perspective. */ public void setInitializationData(IConfigurationElement cfig, String propertyName, Object data) { fConfigElement= cfig; } /* (non-Javadoc) * @see IWizard#performCancel() */ public boolean performCancel() { fJavaPage.performCancel(); return super.performCancel(); } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewProjectCreationWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.HashSet; import java.util.Iterator; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IResourceVisitor; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.wizard.IWizardPage; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.wizards.JavaCapabilityConfigurationPage; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * As addition to the JavaCapabilityConfigurationPage, the wizard checks if an existing external * location was specified and offers to do an early project creation so that classpath can be detected. */ public class NewProjectCreationWizardPage extends JavaCapabilityConfigurationPage { private WizardNewProjectCreationPage fMainPage; private IPath fCurrProjectLocation; private boolean fProjectCreated; /** * Constructor for ProjectWizardPage. */ public NewProjectCreationWizardPage(WizardNewProjectCreationPage mainPage) { super(); fMainPage= mainPage; fCurrProjectLocation= fMainPage.getLocationPath(); fProjectCreated= false; } private boolean canDetectExistingClassPath(IPath projLocation) { return projLocation.toFile().exists() && !Platform.getLocation().equals(projLocation); } private void update() { IPath projLocation= fMainPage.getLocationPath(); if (!projLocation.equals(fCurrProjectLocation) && canDetectExistingClassPath(projLocation)) { String title= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationDialog.title"); //$NON-NLS-1$ String description= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationDialog.description"); //$NON-NLS-1$ if (MessageDialog.openQuestion(getShell(), title, description)) { createAndDetect(); } } fCurrProjectLocation= projLocation; IJavaProject prevProject= getJavaProject(); IProject currProject= fMainPage.getProjectHandle(); if ((prevProject == null) || !currProject.equals(prevProject.getProject())) { init(JavaCore.create(currProject), null, null, false); } } private void createAndDetect() { IRunnableWithProgress op= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) monitor= new NullProgressMonitor(); monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.desc"), 3); //$NON-NLS-1$ try { createProject(new SubProgressMonitor(monitor, 1)); initFromExistingStructures(new SubProgressMonitor(monitor, 2)); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; try { getContainer().run(false, true, op); } catch (InvocationTargetException e) { String title= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("NewProjectCreationWizardPage.EarlyCreationOperation.error.desc"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } catch (InterruptedException e) { // cancel pressed } } /* (non-Javadoc) * @see IDialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { if (visible) { update(); } super.setVisible(visible); } /* (non-Javadoc) * @see IWizardPage#getPreviousPage() */ public IWizardPage getPreviousPage() { if (fProjectCreated) { return null; } return super.getPreviousPage(); } public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) monitor= new NullProgressMonitor(); monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.NormalCreationOperation.desc"), 4); //$NON-NLS-1$ try { createProject(new SubProgressMonitor(monitor, 1)); if (getJavaProject() == null) { initFromExistingStructures(new SubProgressMonitor(monitor, 1)); } else { monitor.worked(1); } configureJavaProject(new SubProgressMonitor(monitor, 2)); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } private void createProject(IProgressMonitor monitor) throws CoreException { IProject project= fMainPage.getProjectHandle(); IPath projectLocation= fMainPage.getLocationPath(); BuildPathsBlock.createProject(project, projectLocation, monitor); fProjectCreated= true; } private void initFromExistingStructures(IProgressMonitor monitor) throws CoreException { if (monitor == null) monitor= new NullProgressMonitor(); monitor.beginTask(NewWizardMessages.getString("NewProjectCreationWizardPage.DetectingClasspathOperation.desc"), 2); //$NON-NLS-1$ try { IProject project= fMainPage.getProjectHandle(); if (project.getFile(".classpath").exists()) { //$NON-NLS-1$ init(JavaCore.create(project), null, null, false); monitor.worked(2); } else{ final HashSet sourceFolders= new HashSet(); IResourceVisitor visitor= new IResourceVisitor() { public boolean visit(IResource resource) throws CoreException { return doVisit(resource, sourceFolders); } }; project.accept(visitor); monitor.worked(1); IClasspathEntry[] entries= null; IPath outputLocation= null; if (!sourceFolders.isEmpty()) { int nSourceFolders= sourceFolders.size(); IClasspathEntry[] jreEntries= NewJavaProjectPreferencePage.getDefaultJRELibrary(); entries= new IClasspathEntry[nSourceFolders + jreEntries.length]; Iterator iter = sourceFolders.iterator(); for (int i = 0; i < nSourceFolders; i++) { entries[i]= JavaCore.newSourceEntry((IPath) iter.next()); } System.arraycopy(jreEntries, 0, entries, nSourceFolders, jreEntries.length); IPath projPath= project.getFullPath(); if (nSourceFolders == 1 && entries[0].getPath().equals(projPath)) { outputLocation= projPath; } else { outputLocation= projPath.append(NewJavaProjectPreferencePage.getOutputLocationName()); } if (!JavaConventions.validateClasspath(JavaCore.create(project), entries, outputLocation).isOK()) { outputLocation= null; entries= null; } } init(JavaCore.create(project), outputLocation, entries, false); monitor.worked(1); } } finally { monitor.done(); } } private boolean doVisit(IResource resource, HashSet sourceFolders) throws JavaModelException { if (!sourceFolders.isEmpty()) { IResource curr= resource; while (curr.getType() != IResource.ROOT) { if (sourceFolders.contains(curr.getFullPath())) { return false; } curr= curr.getParent(); } } if (resource.getType() == IResource.FILE) { if ("java".equals(resource.getFileExtension())) { //$NON-NLS-1$ ICompilationUnit cu= JavaCore.createCompilationUnitFrom((IFile) resource); if (cu != null) { IPath packPath= resource.getParent().getFullPath(); IPackageDeclaration[] decls= cu.getPackageDeclarations(); if (decls.length == 0) { sourceFolders.add(packPath); } else { IPath relpath= new Path(decls[0].getElementName().replace('.', '/')); int remainingSegments= packPath.segmentCount() - relpath.segmentCount(); if (remainingSegments >= 0) { IPath prefix= packPath.uptoSegment(remainingSegments); IPath common= packPath.removeFirstSegments(remainingSegments); if (common.equals(relpath)) { sourceFolders.add(prefix); } } } } } } return true; } /** * Called from the wizard on cancel. */ public void performCancel() { if (fProjectCreated) { try { fMainPage.getProjectHandle().delete(false, false, null); } catch (CoreException e) { JavaPlugin.log(e); } } } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewSourceFolderCreationWizard.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import org.eclipse.core.resources.IResource; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class NewSourceFolderCreationWizard extends NewElementWizard { private NewSourceFolderWizardPage fPage; public NewSourceFolderCreationWizard() { super(); setDefaultPageImageDescriptor(JavaPluginImages.DESC_WIZBAN_NEWSRCFOLDR); setDialogSettings(JavaPlugin.getDefault().getDialogSettings()); setWindowTitle(NewWizardMessages.getString("NewSourceFolderCreationWizard.title")); //$NON-NLS-1$ } /* * @see Wizard#addPages */ public void addPages() { super.addPages(); fPage= new NewSourceFolderWizardPage(); addPage(fPage); fPage.init(getSelection()); } /* * @see Wizard#performFinish */ public boolean performFinish() { if (finishPage(fPage.getRunnable())) { IPackageFragmentRoot root= fPage.getNewPackageFragmentRoot(); try { IResource resource= root.getUnderlyingResource(); selectAndReveal(resource); openResource(resource); } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, only reveal and open will fail } return true; } return false; } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/NewSourceFolderWizardPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; 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.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.wizards.NewElementWizardPage; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class NewSourceFolderWizardPage extends NewElementWizardPage { private static final String PAGE_NAME= "NewSourceFolderWizardPage"; //$NON-NLS-1$ private StringButtonDialogField fProjectField; private StatusInfo fProjectStatus; private StringButtonDialogField fRootDialogField; private StatusInfo fRootStatus; private IWorkspaceRoot fWorkspaceRoot; private IJavaProject fCurrJProject; private IClasspathEntry[] fEntries; private IPath fOutputLocation; private boolean fIsProjectAsSourceFolder; private IPackageFragmentRoot fCreatedRoot; public NewSourceFolderWizardPage() { super(PAGE_NAME); setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewSourceFolderWizardPage.description")); //$NON-NLS-1$ fWorkspaceRoot= ResourcesPlugin.getWorkspace().getRoot(); RootFieldAdapter adapter= new RootFieldAdapter(); fProjectField= new StringButtonDialogField(adapter); fProjectField.setDialogFieldListener(adapter); fProjectField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.project.label")); //$NON-NLS-1$ fProjectField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderWizardPage.project.button")); //$NON-NLS-1$ fRootDialogField= new StringButtonDialogField(adapter); fRootDialogField.setDialogFieldListener(adapter); fRootDialogField.setLabelText(NewWizardMessages.getString("NewSourceFolderWizardPage.root.label")); //$NON-NLS-1$ fRootDialogField.setButtonLabel(NewWizardMessages.getString("NewSourceFolderWizardPage.root.button")); //$NON-NLS-1$ fRootStatus= new StatusInfo(); fProjectStatus= new StatusInfo(); } // -------- Initialization --------- public void init(IStructuredSelection selection) { if (selection == null || selection.isEmpty()) { setDefaultAttributes(); return; } Object selectedElement= selection.getFirstElement(); if (selectedElement == null) { selectedElement= EditorUtility.getActiveEditorJavaInput(); } String projPath= null; if (selectedElement instanceof IResource) { IProject proj= ((IResource)selectedElement).getProject(); if (proj != null) { projPath= proj.getFullPath().makeRelative().toString(); } } else if (selectedElement instanceof IJavaElement) { IJavaProject jproject= ((IJavaElement)selectedElement).getJavaProject(); if (jproject != null) { projPath= jproject.getProject().getFullPath().makeRelative().toString(); } } if (projPath != null) { fProjectField.setText(projPath); fRootDialogField.setText(""); //$NON-NLS-1$ } else { setDefaultAttributes(); } } private void setDefaultAttributes() { String projPath= ""; //$NON-NLS-1$ try { // find the first java project IProject[] projects= fWorkspaceRoot.getProjects(); for (int i= 0; i < projects.length; i++) { IProject proj= projects[i]; if (proj.hasNature(JavaCore.NATURE_ID)) { projPath= proj.getFullPath().makeRelative().toString(); break; } } } catch (CoreException e) { // ignore here } fProjectField.setText(projPath); fRootDialogField.setText(""); //$NON-NLS-1$ } // -------- UI Creation --------- /* * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite) */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; layout.numColumns= 3; composite.setLayout(layout); fProjectField.doFillIntoGrid(composite, 3); fRootDialogField.doFillIntoGrid(composite, 3); int maxFieldWidth= convertWidthInCharsToPixels(40); LayoutUtil.setWidthHint(fProjectField.getTextControl(null), maxFieldWidth); LayoutUtil.setHorizontalGrabbing(fProjectField.getTextControl(null)); LayoutUtil.setWidthHint(fRootDialogField.getTextControl(null), maxFieldWidth); setControl(composite); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.NEW_PACKAGEROOT_WIZARD_PAGE); } /* * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { if (visible) { fRootDialogField.setFocus(); } super.setVisible(visible); } // -------- ContainerFieldAdapter -------- private class RootFieldAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { packRootChangeControlPressed(field); } // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { packRootDialogFieldChanged(field); } } private void packRootChangeControlPressed(DialogField field) { if (field == fRootDialogField) { IPath initialPath= new Path(fRootDialogField.getText()); String title= NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseExistingRootDialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseExistingRootDialog.description"); //$NON-NLS-1$ IFolder folder= chooseFolder(title, message, initialPath); if (folder != null) { IPath path= folder.getFullPath().removeFirstSegments(1); fRootDialogField.setText(path.toString()); } } else if (field == fProjectField) { IJavaProject jproject= chooseProject(); if (jproject != null) { IPath path= jproject.getProject().getFullPath().makeRelative(); fProjectField.setText(path.toString()); } } } private void packRootDialogFieldChanged(DialogField field) { if (field == fRootDialogField) { updateRootStatus(); } else if (field == fProjectField) { updateProjectStatus(); updateRootStatus(); } updateStatus(new IStatus[] { fProjectStatus, fRootStatus }); } private void updateProjectStatus() { fCurrJProject= null; fIsProjectAsSourceFolder= false; String str= fProjectField.getText(); if (str.length() == 0) { fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.EnterProjectName")); //$NON-NLS-1$ return; } IPath path= new Path(str); if (path.segmentCount() != 1) { fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.InvalidProjectPath")); //$NON-NLS-1$ return; } IProject project= fWorkspaceRoot.getProject(path.toString()); if (!project.exists()) { fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.ProjectNotExists")); //$NON-NLS-1$ return; } try { if (project.hasNature(JavaCore.NATURE_ID)) { fCurrJProject= JavaCore.create(project); fEntries= fCurrJProject.getRawClasspath(); fOutputLocation= fCurrJProject.getOutputLocation(); fProjectStatus.setOK(); return; } } catch (CoreException e) { JavaPlugin.log(e); fCurrJProject= null; } fProjectStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.NotAJavaProject")); //$NON-NLS-1$ } private void updateRootStatus() { fRootDialogField.enableButton(fCurrJProject != null); fIsProjectAsSourceFolder= false; if (fCurrJProject == null) { return; } fRootStatus.setOK(); IPath projPath= fCurrJProject.getProject().getFullPath(); String str= fRootDialogField.getText(); if (str.length() == 0) { fRootStatus.setError(NewWizardMessages.getFormattedString("NewSourceFolderWizardPage.error.EnterRootName", fCurrJProject.getProject().getFullPath().toString())); //$NON-NLS-1$ } else { IPath path= projPath.append(str); IStatus validate= fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER); if (validate.matches(IStatus.ERROR)) { fRootStatus.setError(NewWizardMessages.getFormattedString("NewSourceFolderWizardPage.error.InvalidRootName", validate.getMessage())); //$NON-NLS-1$ } else { IResource res= fWorkspaceRoot.findMember(path); if (res != null) { if (res.getType() != IResource.FOLDER) { fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.NotAFolder")); //$NON-NLS-1$ return; } } ArrayList newEntries= new ArrayList(fEntries.length + 1); for (int i= 0; i < fEntries.length; i++) { IClasspathEntry curr= fEntries[i]; if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (path.equals(curr.getPath())) { fRootStatus.setError(NewWizardMessages.getString("NewSourceFolderWizardPage.error.AlreadyExisting")); //$NON-NLS-1$ return; } if (projPath.equals(curr.getPath())) { fIsProjectAsSourceFolder= true; curr= JavaCore.newSourceEntry(path); } } newEntries.add(curr); } if (!fIsProjectAsSourceFolder) { newEntries.add(JavaCore.newSourceEntry(path)); } IClasspathEntry[] newEntriesArray= (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]); IStatus status= JavaConventions.validateClasspath(fCurrJProject, newEntriesArray, fOutputLocation); if (!status.isOK()) { if (fIsProjectAsSourceFolder && fOutputLocation.equals(projPath)) { IPath newOutputLocation= projPath.append(NewJavaProjectPreferencePage.getOutputLocationName()); IStatus status2= JavaConventions.validateClasspath(fCurrJProject, newEntriesArray, newOutputLocation); if (status2.isOK()) { fRootStatus.setWarning(NewWizardMessages.getFormattedString("NewSourceFolderWizardPage.warning.ReplaceSFandOL", newOutputLocation.toString())); //$NON-NLS-1$ return; } } fRootStatus.setError(status.getMessage()); } else if (fIsProjectAsSourceFolder) { fRootStatus.setWarning(NewWizardMessages.getString("NewSourceFolderWizardPage.warning.ReplaceSF")); //$NON-NLS-1$ } } } } // ---- creation ---------------- public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { fCreatedRoot= createPackageFragmentRoot(monitor, getShell()); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } protected IPackageFragmentRoot getNewPackageFragmentRoot() { return fCreatedRoot; } protected IPackageFragmentRoot createPackageFragmentRoot(IProgressMonitor monitor, Shell shell) throws CoreException, InterruptedException { String relPath= fRootDialogField.getText(); IFolder folder= fCurrJProject.getProject().getFolder(relPath); IPath path= folder.getFullPath(); if (!folder.exists()) { CoreUtility.createFolder(folder, true, true, monitor); } IClasspathEntry[] entries= fCurrJProject.getRawClasspath(); IClasspathEntry[] newEntries; IPath outputLocation= fOutputLocation; if (fIsProjectAsSourceFolder) { IPath projPath= fCurrJProject.getProject().getFullPath(); newEntries= new IClasspathEntry[entries.length]; for (int i= 0; i < newEntries.length; i++) { IClasspathEntry curr= entries[i]; if (curr.getEntryKind() == IClasspathEntry.CPE_SOURCE && curr.getPath().equals(projPath)) { curr= JavaCore.newSourceEntry(path); } newEntries[i]= curr; } if (outputLocation.equals(projPath)) { outputLocation= projPath.append(NewJavaProjectPreferencePage.getOutputLocationName()); if (BuildPathsBlock.hasClassfiles(fCurrJProject.getProject())) { if (BuildPathsBlock.getRemoveOldBinariesQuery(shell).doQuery(projPath)) { BuildPathsBlock.removeOldClassfiles(fCurrJProject.getProject()); } } } } else { newEntries= new IClasspathEntry[entries.length + 1]; int k= entries.length; for (int i= k - 1; i >= 0; i--) { IClasspathEntry curr= entries[i]; if (k > i && curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { newEntries[k--]= JavaCore.newSourceEntry(path); } newEntries[k--]= curr; } if (k == 0) { newEntries[k--]= JavaCore.newSourceEntry(path); } } fCurrJProject.setRawClasspath(newEntries, outputLocation, monitor); return fCurrJProject.getPackageFragmentRoot(folder); } // ------------- choose dialogs private IFolder chooseFolder(String title, String message, IPath initialPath) { Class[] acceptedClasses= new Class[] { IFolder.class }; ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); Object[] notWanted= getFilteredExistingContainerEntries(); ViewerFilter filter= new TypedViewerFilter(acceptedClasses, notWanted); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IProject currProject= fCurrJProject.getProject(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(title); dialog.setMessage(message); dialog.addFilter(filter); dialog.setInput(currProject); IResource res= currProject.findMember(initialPath); if (res != null) { dialog.setInitialSelection(res); } if (dialog.open() == dialog.OK) { return (IFolder) dialog.getFirstResult(); } return null; } private IJavaProject chooseProject() { IJavaProject[] projects; try { projects= JavaCore.create(fWorkspaceRoot).getJavaProjects(); } catch (JavaModelException e) { JavaPlugin.log(e); projects= new IJavaProject[0]; } ILabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT); ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), labelProvider); dialog.setTitle(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseProjectDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewSourceFolderWizardPage.ChooseProjectDialog.description")); //$NON-NLS-1$ dialog.setElements(projects); dialog.setInitialSelections(new Object[] { fCurrJProject }); if (dialog.open() == dialog.OK) { return (IJavaProject) dialog.getFirstResult(); } return null; } private IContainer[] getFilteredExistingContainerEntries() { if (fCurrJProject == null) { return new IContainer[0]; } List res= new ArrayList(); try { IResource container= fWorkspaceRoot.findMember(fCurrJProject.getOutputLocation()); if (container != null) { res.add(container); } } catch (JavaModelException e) { JavaPlugin.log(e); } for (int i= 0; i < fEntries.length; i++) { IClasspathEntry elem= fEntries[i]; if (elem.getEntryKind() == IClasspathEntry.CPE_SOURCE) { IResource container= fWorkspaceRoot.findMember(elem.getPath()); if (container != null) { res.add(container); } } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewPackageWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import 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.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; 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.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /** * Wizard page to create a new package. * * <p> * Note: This class is not intended to be subclassed. To implement a different kind of * a new package wizard page, extend <code>NewContainerWizardPage</code>. * </p> * * @since 2.0 */ public class NewPackageWizardPage extends NewContainerWizardPage { private static final String PAGE_NAME= "NewPackageWizardPage"; //$NON-NLS-1$ private static final String PACKAGE= "NewPackageWizardPage.package"; //$NON-NLS-1$ private StringDialogField fPackageDialogField; /* * Status of last validation of the package field */ private IStatus fPackageStatus; private IPackageFragment fCreatedPackageFragment; /** * Creates a new <code>NewPackageWizardPage</code> */ public NewPackageWizardPage() { super(PAGE_NAME); setTitle(NewWizardMessages.getString("NewPackageWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewPackageWizardPage.description")); //$NON-NLS-1$ fCreatedPackageFragment= null; PackageFieldAdapter adapter= new PackageFieldAdapter(); fPackageDialogField= new StringDialogField(); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewPackageWizardPage.package.label")); //$NON-NLS-1$ fPackageStatus= new StatusInfo(); } // -------- Initialization --------- /** * The wizard owning this page is responsible for calling this method with the * current selection. The selection is used to initialize the fields of the wizard * page. * * @param selection used to initialize the fields */ public void init(IStructuredSelection selection) { IJavaElement jelem= getInitialJavaElement(selection); initContainerPage(jelem); setPackageText("", true); //$NON-NLS-1$ updateStatus(new IStatus[] { fContainerStatus, fPackageStatus }); } // -------- UI Creation --------- /* * @see WizardPage#createControl */ public void createControl(Composite parent) { initializeDialogUnits(parent); Composite composite= new Composite(parent, SWT.NONE); int nColumns= 3; GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; layout.numColumns= 3; composite.setLayout(layout); Label label= new Label(composite, SWT.WRAP); label.setText(NewWizardMessages.getString("NewPackageWizardPage.info")); //$NON-NLS-1$ GridData gd= new GridData(); gd.widthHint= convertWidthInCharsToPixels(80); gd.horizontalSpan= 3; label.setLayoutData(gd); createContainerControls(composite, nColumns); createPackageControls(composite, nColumns); setControl(composite); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.NEW_PACKAGE_WIZARD_PAGE); } /** * @see org.eclipse.jface.dialogs.IDialogPage#setVisible(boolean) */ public void setVisible(boolean visible) { if (visible) { setFocus(); } super.setVisible(visible); } /** * Sets the focus to the package name input field. */ protected void setFocus() { fPackageDialogField.setFocus(); } private void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns - 1); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); DialogField.createEmptySpace(composite); } // -------- PackageFieldAdapter -------- private class PackageFieldAdapter implements IDialogFieldListener { // --------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { fPackageStatus= packageChanged(); // tell all others handleFieldChanged(PACKAGE); } } // -------- update message ---------------- /* * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); } // do status line update updateStatus(new IStatus[] { fContainerStatus, fPackageStatus }); } // ----------- validation ---------- /** * Verifies the input for the package field. */ private IStatus packageChanged() { StatusInfo status= new StatusInfo(); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewPackageWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewPackageWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ } } else { status.setError(NewWizardMessages.getString("NewPackageWizardPage.error.EnterName")); //$NON-NLS-1$ return status; } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { IPackageFragment pack= root.getPackageFragment(packName); try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= pack.getPath(); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewPackageWizardPage.error.IsOutputFolder")); //$NON-NLS-1$ return status; } } if (pack.exists()) { if (pack.containsJavaResources() || !pack.hasSubpackages()) { status.setError(NewWizardMessages.getString("NewPackageWizardPage.error.PackageExists")); //$NON-NLS-1$ } else { status.setWarning(NewWizardMessages.getString("NewPackageWizardPage.warning.PackageNotShown")); //$NON-NLS-1$ } } } catch (JavaModelException e) { JavaPlugin.log(e); } } return status; } /** * Returns the content of the package input field. * * @return the content of the package input field */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Sets the content of the package input field to the given value. * * @param str the new package input field text * @param canBeModified if <code>true</code> the package input * field can be modified; otherwise it is read-only. */ public void setPackageText(String str, boolean canBeModified) { fPackageDialogField.setText(str); fPackageDialogField.setEnabled(canBeModified); } // ---- creation ---------------- /** * Returns a runnable that creates a package using the current settings. * * @return the runnable that creates the new package */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { createPackage(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } /** * Returns the created package fragment. This method only returns a valid value * after the runnable returned from <code>getRunnable</code> has been * executed. * * @return the create package fragment */ public IPackageFragment getNewPackageFragment() { return fCreatedPackageFragment; } private void createPackage(IProgressMonitor monitor) throws CoreException, InterruptedException { IPackageFragmentRoot root= getPackageFragmentRoot(); String packName= getPackageText(); fCreatedPackageFragment= root.createPackageFragment(packName, true, monitor); } }
11,546
Bug 11546 Progress bar gets cleared during project creation
IMPORTANT: Start a new empty workspace Start to create a Java project Enter "JUnit" as name Press "Finish" ==> Progress bar goes to right, then gets cleared and user has to wait without knowing what's going to happen.
resolved fixed
75ee5f2
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T15:50:11Z
2002-03-18T16:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewTypeWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.ui.dialogs.ElementListSelectionDialog; import org.eclipse.ui.dialogs.SelectionDialog; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.ISourceRange; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.ITypeHierarchy; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.search.IJavaSearchConstants; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.core.search.SearchEngine; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.IImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.ImportsStructure; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; import org.eclipse.jdt.internal.corext.template.Template; import org.eclipse.jdt.internal.corext.template.Templates; import org.eclipse.jdt.internal.corext.template.java.JavaContext; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.TypeSelectionDialog; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.CodeGenerationPreferencePage; import org.eclipse.jdt.internal.ui.preferences.ImportOrganizePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.SWTUtil; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.SuperInterfaceSelectionDialog; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogFieldGroup; import org.eclipse.jdt.internal.ui.wizards.dialogfields.Separator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringDialogField; /** * The class <code>NewTypeWizardPage</code> contains controls and validation routines * for a 'New Type WizardPage'. Implementors decide which components to add and to enable. * Implementors can also customize the validation code. <code>NewTypeWizardPage</code> * is intended to serve as base class of all wizards that create types like applets, servlets, classes, * interfaces, etc. * <p> * See <code>NewClassWizardPage</code> or <code>NewInterfaceWizardPage</code> for an * example usage of <code>NewTypeWizardPage</code>. * </p> * * @see org.eclipse.jdt.ui.wizards.NewClassWizardPage * @see org.eclipse.jdt.ui.wizards.NewInterfaceWizardPage * * @since 2.0 */ public abstract class NewTypeWizardPage extends NewContainerWizardPage { /** * Class used in stub creation routines to add needed imports to a * compilation unit. */ public static class ImportsManager { private IImportsStructure fImportsStructure; /* package */ ImportsManager(IImportsStructure structure) { fImportsStructure= structure; } /* package */ IImportsStructure getImportsStructure() { return fImportsStructure; } /** * Adds a new import declaration that is sorted in the existing imports. * If an import already exists or the import would conflict with another import * of an other type with the same simple name the import is not added. * * @param qualifiedTypeName The fully qualified name of the type to import * (dot separated) * @return Returns the simple type name that can be used in the code or the * fully qualified type name if an import conflict prevented the import */ public String addImport(String qualifiedTypeName) { return fImportsStructure.addImport(qualifiedTypeName); } } /** Public access flag. See The Java Virtual Machine Specification for more details. */ public int F_PUBLIC = Flags.AccPublic; /** Private access flag. See The Java Virtual Machine Specification for more details. */ public int F_PRIVATE = Flags.AccPrivate; /** Protected access flag. See The Java Virtual Machine Specification for more details. */ public int F_PROTECTED = Flags.AccProtected; /** Static access flag. See The Java Virtual Machine Specification for more details. */ public int F_STATIC = Flags.AccStatic; /** Final access flag. See The Java Virtual Machine Specification for more details. */ public int F_FINAL = Flags.AccFinal; /** Abstract property flag. See The Java Virtual Machine Specification for more details. */ public int F_ABSTRACT = Flags.AccAbstract; private final static String PAGE_NAME= "NewTypeWizardPage"; //$NON-NLS-1$ /** Field ID of the package input field */ protected final static String PACKAGE= PAGE_NAME + ".package"; //$NON-NLS-1$ /** Field ID of the eclosing type input field */ protected final static String ENCLOSING= PAGE_NAME + ".enclosing"; //$NON-NLS-1$ /** Field ID of the enclosing type checkbox */ protected final static String ENCLOSINGSELECTION= ENCLOSING + ".selection"; //$NON-NLS-1$ /** Field ID of the type name input field */ protected final static String TYPENAME= PAGE_NAME + ".typename"; //$NON-NLS-1$ /** Field ID of the super type input field */ protected final static String SUPER= PAGE_NAME + ".superclass"; //$NON-NLS-1$ /** Field ID of the super interfaces input field */ protected final static String INTERFACES= PAGE_NAME + ".interfaces"; //$NON-NLS-1$ /** Field ID of the modifier checkboxes */ protected final static String MODIFIERS= PAGE_NAME + ".modifiers"; //$NON-NLS-1$ /** Field ID of the method stubs checkboxes */ protected final static String METHODS= PAGE_NAME + ".methods"; //$NON-NLS-1$ private class InterfacesListLabelProvider extends LabelProvider { private Image fInterfaceImage; public InterfacesListLabelProvider() { super(); fInterfaceImage= JavaPluginImages.get(JavaPluginImages.IMG_OBJS_INTERFACE); } public Image getImage(Object element) { return fInterfaceImage; } } private StringButtonStatusDialogField fPackageDialogField; private SelectionButtonDialogField fEnclosingTypeSelection; private StringButtonDialogField fEnclosingTypeDialogField; private boolean fCanModifyPackage; private boolean fCanModifyEnclosingType; private IPackageFragment fCurrPackage; private IType fCurrEnclosingType; private StringDialogField fTypeNameDialogField; private StringButtonDialogField fSuperClassDialogField; private ListDialogField fSuperInterfacesDialogField; private IType fSuperClass; private SelectionButtonDialogFieldGroup fAccMdfButtons; private SelectionButtonDialogFieldGroup fOtherMdfButtons; private IType fCreatedType; protected IStatus fEnclosingTypeStatus; protected IStatus fPackageStatus; protected IStatus fTypeNameStatus; protected IStatus fSuperClassStatus; protected IStatus fModifierStatus; protected IStatus fSuperInterfacesStatus; private boolean fIsClass; private int fStaticMdfIndex; private final int PUBLIC_INDEX= 0, DEFAULT_INDEX= 1, PRIVATE_INDEX= 2, PROTECTED_INDEX= 3; private final int ABSTRACT_INDEX= 0, FINAL_INDEX= 1; /** * Creates a new <code>NewTypeWizardPage</code> * * @param isClass <code>true</code> if a new class is to be created; otherwise * an interface is to be created * @param pageName the wizard page's name */ public NewTypeWizardPage(boolean isClass, String pageName) { super(pageName); fCreatedType= null; fIsClass= isClass; TypeFieldsAdapter adapter= new TypeFieldsAdapter(); fPackageDialogField= new StringButtonStatusDialogField(adapter); fPackageDialogField.setDialogFieldListener(adapter); fPackageDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.package.label")); //$NON-NLS-1$ fPackageDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.package.button")); //$NON-NLS-1$ fPackageDialogField.setStatusWidthHint(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ fEnclosingTypeSelection= new SelectionButtonDialogField(SWT.CHECK); fEnclosingTypeSelection.setDialogFieldListener(adapter); fEnclosingTypeSelection.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.enclosing.selection.label")); //$NON-NLS-1$ fEnclosingTypeDialogField= new StringButtonDialogField(adapter); fEnclosingTypeDialogField.setDialogFieldListener(adapter); fEnclosingTypeDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.enclosing.button")); //$NON-NLS-1$ fTypeNameDialogField= new StringDialogField(); fTypeNameDialogField.setDialogFieldListener(adapter); fTypeNameDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.typename.label")); //$NON-NLS-1$ fSuperClassDialogField= new StringButtonDialogField(adapter); fSuperClassDialogField.setDialogFieldListener(adapter); fSuperClassDialogField.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.superclass.label")); //$NON-NLS-1$ fSuperClassDialogField.setButtonLabel(NewWizardMessages.getString("NewTypeWizardPage.superclass.button")); //$NON-NLS-1$ String[] addButtons= new String[] { /* 0 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.add"), //$NON-NLS-1$ /* 1 */ null, /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.interfaces.remove") //$NON-NLS-1$ }; fSuperInterfacesDialogField= new ListDialogField(adapter, addButtons, new InterfacesListLabelProvider()); fSuperInterfacesDialogField.setDialogFieldListener(adapter); String interfaceLabel= fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.interfaces.class.label") : NewWizardMessages.getString("NewTypeWizardPage.interfaces.ifc.label"); //$NON-NLS-1$ //$NON-NLS-2$ fSuperInterfacesDialogField.setLabelText(interfaceLabel); fSuperInterfacesDialogField.setRemoveButtonIndex(2); String[] buttonNames1= new String[] { /* 0 == PUBLIC_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.public"), //$NON-NLS-1$ /* 1 == DEFAULT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.default"), //$NON-NLS-1$ /* 2 == PRIVATE_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.private"), //$NON-NLS-1$ /* 3 == PROTECTED_INDEX*/ NewWizardMessages.getString("NewTypeWizardPage.modifiers.protected") //$NON-NLS-1$ }; fAccMdfButtons= new SelectionButtonDialogFieldGroup(SWT.RADIO, buttonNames1, 4); fAccMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.setLabelText(NewWizardMessages.getString("NewTypeWizardPage.modifiers.acc.label")); //$NON-NLS-1$ fAccMdfButtons.setSelection(0, true); String[] buttonNames2; if (fIsClass) { buttonNames2= new String[] { /* 0 == ABSTRACT_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.abstract"), //$NON-NLS-1$ /* 1 == FINAL_INDEX */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.final"), //$NON-NLS-1$ /* 2 */ NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 2; // index of the static checkbox is 2 } else { buttonNames2= new String[] { NewWizardMessages.getString("NewTypeWizardPage.modifiers.static") //$NON-NLS-1$ }; fStaticMdfIndex= 0; // index of the static checkbox is 0 } fOtherMdfButtons= new SelectionButtonDialogFieldGroup(SWT.CHECK, buttonNames2, 4); fOtherMdfButtons.setDialogFieldListener(adapter); fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, false); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, false); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, false); fPackageStatus= new StatusInfo(); fEnclosingTypeStatus= new StatusInfo(); fCanModifyPackage= true; fCanModifyEnclosingType= true; updateEnableState(); fTypeNameStatus= new StatusInfo(); fSuperClassStatus= new StatusInfo(); fSuperInterfacesStatus= new StatusInfo(); fModifierStatus= new StatusInfo(); } /** * Initializes all fields provided by the page with a given selection. * * @param elem the selection used to intialize this page or <code> * null</code> if no selection was available */ protected void initTypePage(IJavaElement elem) { String initSuperclass= "java.lang.Object"; //$NON-NLS-1$ ArrayList initSuperinterfaces= new ArrayList(5); IPackageFragment pack= null; IType enclosingType= null; if (elem != null) { // evaluate the enclosing type pack= (IPackageFragment) elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT); IType typeInCU= (IType) elem.getAncestor(IJavaElement.TYPE); if (typeInCU != null) { if (typeInCU.getCompilationUnit() != null) { enclosingType= typeInCU; } } else { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { enclosingType= cu.findPrimaryType(); } } try { IType type= null; if (elem.getElementType() == IJavaElement.TYPE) { type= (IType)elem; if (type.exists()) { String superName= JavaModelUtil.getFullyQualifiedName(type); if (type.isInterface()) { initSuperinterfaces.add(superName); } else { initSuperclass= superName; } } } } catch (JavaModelException e) { JavaPlugin.log(e); // ignore this exception now } } setPackageFragment(pack, true); setEnclosingType(enclosingType, true); setEnclosingTypeSelection(false, true); setTypeName("", true); //$NON-NLS-1$ setSuperClass(initSuperclass, true); setSuperInterfaces(initSuperinterfaces, true); } // -------- UI Creation --------- /** * Creates a separator line. Expects a <code>GridLayout</code> with at least 1 column. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSeparator(Composite composite, int nColumns) { (new Separator(SWT.SEPARATOR | SWT.HORIZONTAL)).doFillIntoGrid(composite, nColumns, convertHeightInCharsToPixels(1)); } /** * Creates the controls for the package name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createPackageControls(Composite composite, int nColumns) { fPackageDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fPackageDialogField.getTextControl(null), getMaxFieldWidth()); LayoutUtil.setHorizontalGrabbing(fPackageDialogField.getTextControl(null)); } /** * Creates the controls for the enclosing type name field. Expects a <code>GridLayout</code> with at * least 4 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createEnclosingTypeControls(Composite composite, int nColumns) { // #6891 Composite tabGroup= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.marginHeight= 0; tabGroup.setLayout(layout); fEnclosingTypeSelection.doFillIntoGrid(tabGroup, 1); Control c= fEnclosingTypeDialogField.getTextControl(composite); GridData gd= new GridData(GridData.FILL_HORIZONTAL); gd.widthHint= getMaxFieldWidth(); gd.horizontalSpan= 2; c.setLayoutData(gd); Button button= fEnclosingTypeDialogField.getChangeControl(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.heightHint = SWTUtil.getButtonHeigthHint(button); gd.widthHint = SWTUtil.getButtonWidthHint(button); button.setLayoutData(gd); } /** * Creates the controls for the type name field. Expects a <code>GridLayout</code> with at * least 2 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createTypeNameControls(Composite composite, int nColumns) { fTypeNameDialogField.doFillIntoGrid(composite, nColumns - 1); DialogField.createEmptySpace(composite); LayoutUtil.setWidthHint(fTypeNameDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the modifiers radio/ceckbox buttons. Expects a * <code>GridLayout</code> with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createModifierControls(Composite composite, int nColumns) { LayoutUtil.setHorizontalSpan(fAccMdfButtons.getLabelControl(composite), 1); Control control= fAccMdfButtons.getSelectionButtonsGroup(composite); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); DialogField.createEmptySpace(composite); control= fOtherMdfButtons.getSelectionButtonsGroup(composite); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= nColumns - 2; control.setLayoutData(gd); DialogField.createEmptySpace(composite); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> * with at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperClassControls(Composite composite, int nColumns) { fSuperClassDialogField.doFillIntoGrid(composite, nColumns); LayoutUtil.setWidthHint(fSuperClassDialogField.getTextControl(null), getMaxFieldWidth()); } /** * Creates the controls for the superclass name field. Expects a <code>GridLayout</code> with * at least 3 columns. * * @param composite the parent composite * @param nColumns number of columns to span */ protected void createSuperInterfacesControls(Composite composite, int nColumns) { fSuperInterfacesDialogField.doFillIntoGrid(composite, nColumns); GridData gd= (GridData)fSuperInterfacesDialogField.getListControl(null).getLayoutData(); if (fIsClass) { gd.heightHint= convertHeightInCharsToPixels(3); } else { gd.heightHint= convertHeightInCharsToPixels(6); } gd.grabExcessVerticalSpace= false; gd.widthHint= getMaxFieldWidth(); } /** * Sets the focus on the type name input field. */ protected void setFocus() { fTypeNameDialogField.setFocus(); } // -------- TypeFieldsAdapter -------- private class TypeFieldsAdapter implements IStringButtonAdapter, IDialogFieldListener, IListAdapter { // -------- IStringButtonAdapter public void changeControlPressed(DialogField field) { typePageChangeControlPressed(field); } // -------- IListAdapter public void customButtonPressed(DialogField field, int index) { typePageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) {} // -------- IDialogFieldListener public void dialogFieldChanged(DialogField field) { typePageDialogFieldChanged(field); } } private void typePageChangeControlPressed(DialogField field) { if (field == fPackageDialogField) { IPackageFragment pack= choosePackage(); if (pack != null) { fPackageDialogField.setText(pack.getElementName()); } } else if (field == fEnclosingTypeDialogField) { IType type= chooseEnclosingType(); if (type != null) { fEnclosingTypeDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } else if (field == fSuperClassDialogField) { IType type= chooseSuperType(); if (type != null) { fSuperClassDialogField.setText(JavaModelUtil.getFullyQualifiedName(type)); } } } private void typePageCustomButtonPressed(DialogField field, int index) { if (field == fSuperInterfacesDialogField) { chooseSuperInterfaces(); } } /* * A field on the type has changed. The fields' status and all dependend * status are updated. */ private void typePageDialogFieldChanged(DialogField field) { String fieldName= null; if (field == fPackageDialogField) { fPackageStatus= packageChanged(); updatePackageStatusLabel(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= PACKAGE; } else if (field == fEnclosingTypeDialogField) { fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSING; } else if (field == fEnclosingTypeSelection) { updateEnableState(); boolean isEnclosedType= isEnclosingTypeSelected(); if (!isEnclosedType) { if (fAccMdfButtons.isSelected(PRIVATE_INDEX) || fAccMdfButtons.isSelected(PROTECTED_INDEX)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, false); fAccMdfButtons.setSelection(PROTECTED_INDEX, false); fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, false); } } fAccMdfButtons.enableSelectionButton(PRIVATE_INDEX, isEnclosedType && fIsClass); fAccMdfButtons.enableSelectionButton(PROTECTED_INDEX, isEnclosedType && fIsClass); fOtherMdfButtons.enableSelectionButton(fStaticMdfIndex, isEnclosedType); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fieldName= ENCLOSINGSELECTION; } else if (field == fTypeNameDialogField) { fTypeNameStatus= typeNameChanged(); fieldName= TYPENAME; } else if (field == fSuperClassDialogField) { fSuperClassStatus= superClassChanged(); fieldName= SUPER; } else if (field == fSuperInterfacesDialogField) { fSuperInterfacesStatus= superInterfacesChanged(); fieldName= INTERFACES; } else if (field == fOtherMdfButtons) { fModifierStatus= modifiersChanged(); fieldName= MODIFIERS; } else { fieldName= METHODS; } // tell all others handleFieldChanged(fieldName); } // -------- update message ---------------- /* * @see org.eclipse.jdt.ui.wizards.NewContainerWizardPage#handleFieldChanged(String) */ protected void handleFieldChanged(String fieldName) { super.handleFieldChanged(fieldName); if (fieldName == CONTAINER) { fPackageStatus= packageChanged(); fEnclosingTypeStatus= enclosingTypeChanged(); fTypeNameStatus= typeNameChanged(); fSuperClassStatus= superClassChanged(); fSuperInterfacesStatus= superInterfacesChanged(); } } // ---- set / get ---------------- /** * Returns the text of the package input field. * * @return the text of the package input field */ public String getPackageText() { return fPackageDialogField.getText(); } /** * Returns the text of the enclosing type input field. * * @return the text of the enclosing type input field */ public String getEnclosingTypeText() { return fEnclosingTypeDialogField.getText(); } /** * Returns the package fragment corresponding to the current input. * * @return a package fragement or <code>null</code> if the input * could not be resolved. */ public IPackageFragment getPackageFragment() { if (!isEnclosingTypeSelected()) { return fCurrPackage; } else { if (fCurrEnclosingType != null) { return fCurrEnclosingType.getPackageFragment(); } } return null; } /** * Sets the package fragment to the given value. The method updates the model * and the text of the control. * * @param pack the package fragement to be set * @param canBeModified if <code>true</code> the package fragment is * editable; otherwise it is read-only. */ public void setPackageFragment(IPackageFragment pack, boolean canBeModified) { fCurrPackage= pack; fCanModifyPackage= canBeModified; String str= (pack == null) ? "" : pack.getElementName(); //$NON-NLS-1$ fPackageDialogField.setText(str); updateEnableState(); } /** * Returns the enclosing type corresponding to the current input. * * @return the enclosing type or <code>null</code> if the enclosing type is * not selected or the input could not be resolved */ public IType getEnclosingType() { if (isEnclosingTypeSelected()) { return fCurrEnclosingType; } return null; } /** * Sets the enclosing type. The method updates the underlying model * and the text of the control. * * @param type the enclosing type * @param canBeModified if <code>true</code> the enclosing type field is * editable; otherwise it is read-only. */ public void setEnclosingType(IType type, boolean canBeModified) { fCurrEnclosingType= type; fCanModifyEnclosingType= canBeModified; String str= (type == null) ? "" : JavaModelUtil.getFullyQualifiedName(type); //$NON-NLS-1$ fEnclosingTypeDialogField.setText(str); updateEnableState(); } /** * Returns the selection state of the enclosing type checkbox. * * @return the seleciton state of the enclosing type checkbox */ public boolean isEnclosingTypeSelected() { return fEnclosingTypeSelection.isSelected(); } /** * Sets the enclosing type checkbox's selection state. * * @param isSelected the checkbox's selection state * @param canBeModified if <code>true</code> the enclosing type checkbox is * modifiable; otherwise it is read-only. */ public void setEnclosingTypeSelection(boolean isSelected, boolean canBeModified) { fEnclosingTypeSelection.setSelection(isSelected); fEnclosingTypeSelection.setEnabled(canBeModified); updateEnableState(); } /** * Returns the type name entered into the type input field. * * @return the type name */ public String getTypeName() { return fTypeNameDialogField.getText(); } /** * Sets the type name input field's text to the given value. Method doesn't update * the model. * * @param name the new type name * @param canBeModified if <code>true</code> the enclosing type name field is * editable; otherwise it is read-only. */ public void setTypeName(String name, boolean canBeModified) { fTypeNameDialogField.setText(name); fTypeNameDialogField.setEnabled(canBeModified); } /** * Returns the selected modifiers. * * @return the selected modifiers * @see Flags */ public int getModifiers() { int mdf= 0; if (fAccMdfButtons.isSelected(PUBLIC_INDEX)) { mdf+= F_PUBLIC; } else if (fAccMdfButtons.isSelected(PRIVATE_INDEX)) { mdf+= F_PRIVATE; } else if (fAccMdfButtons.isSelected(PROTECTED_INDEX)) { mdf+= F_PROTECTED; } if (fOtherMdfButtons.isSelected(ABSTRACT_INDEX) && (fStaticMdfIndex != 0)) { mdf+= F_ABSTRACT; } if (fOtherMdfButtons.isSelected(FINAL_INDEX)) { mdf+= F_FINAL; } if (fOtherMdfButtons.isSelected(fStaticMdfIndex)) { mdf+= F_STATIC; } return mdf; } /** * Sets the modifiers. * * @param modifiers <code>F_PUBLIC</code>, <code>F_PRIVATE</code>, * <code>F_PROTECTED</code>, <code>F_ABSTRACT, F_FINAL</code> * or <code>F_STATIC</code> or, a valid combination. * @param canBeModified if <code>true</code> the modifier fields are * editable; otherwise they are read-only * @see Flags */ public void setModifiers(int modifiers, boolean canBeModified) { if (Flags.isPublic(modifiers)) { fAccMdfButtons.setSelection(PUBLIC_INDEX, true); } else if (Flags.isPrivate(modifiers)) { fAccMdfButtons.setSelection(PRIVATE_INDEX, true); } else if (Flags.isProtected(modifiers)) { fAccMdfButtons.setSelection(PROTECTED_INDEX, true); } else { fAccMdfButtons.setSelection(DEFAULT_INDEX, true); } if (Flags.isAbstract(modifiers)) { fOtherMdfButtons.setSelection(ABSTRACT_INDEX, true); } if (Flags.isFinal(modifiers)) { fOtherMdfButtons.setSelection(FINAL_INDEX, true); } if (Flags.isStatic(modifiers)) { fOtherMdfButtons.setSelection(fStaticMdfIndex, true); } fAccMdfButtons.setEnabled(canBeModified); fOtherMdfButtons.setEnabled(canBeModified); } /** * Returns the content of the superclass input field. * * @return the superclass name */ public String getSuperClass() { return fSuperClassDialogField.getText(); } /** * Sets the super class name. * * @param name the new superclass name * @param canBeModified if <code>true</code> the superclass name field is * editable; otherwise it is read-only. */ public void setSuperClass(String name, boolean canBeModified) { fSuperClassDialogField.setText(name); fSuperClassDialogField.setEnabled(canBeModified); } /** * Returns the chosen super interfaces. * * @return a list of chosen super interfaces. The list's elements * are of type <code>String</code> */ public List getSuperInterfaces() { return fSuperInterfacesDialogField.getElements(); } /** * Sets the super interfaces. * * @param interfacesNames a list of super interface. The method requires that * the list's elements are of type <code>String</code> * @param canBeModified if <code>true</code> the super interface field is * editable; otherwise it is read-only. */ public void setSuperInterfaces(List interfacesNames, boolean canBeModified) { fSuperInterfacesDialogField.setElements(interfacesNames); fSuperInterfacesDialogField.setEnabled(canBeModified); } // ----------- validation ---------- /** * A hook method that gets called when the package field has changed. The method * validates the package name and returns the status of the validation. The validation * also updates the package fragment model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus packageChanged() { StatusInfo status= new StatusInfo(); fPackageDialogField.enableButton(getPackageFragmentRoot() != null); String packName= getPackageText(); if (packName.length() > 0) { IStatus val= JavaConventions.validatePackageName(packName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidPackageName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.DiscouragedPackageName", val.getMessage())); //$NON-NLS-1$ // continue } } IPackageFragmentRoot root= getPackageFragmentRoot(); if (root != null) { if (root.getJavaProject().exists() && packName.length() > 0) { try { IPath rootPath= root.getPath(); IPath outputPath= root.getJavaProject().getOutputLocation(); if (rootPath.isPrefixOf(outputPath) && !rootPath.equals(outputPath)) { // if the bin folder is inside of our root, dont allow to name a package // like the bin folder IPath packagePath= rootPath.append(packName.replace('.', '/')); if (outputPath.isPrefixOf(packagePath)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ClashOutputLocation")); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass } } fCurrPackage= root.getPackageFragment(packName); } else { status.setError(""); //$NON-NLS-1$ } return status; } /* * Updates the 'default' label next to the package field. */ private void updatePackageStatusLabel() { String packName= getPackageText(); if (packName.length() == 0) { fPackageDialogField.setStatus(NewWizardMessages.getString("NewTypeWizardPage.default")); //$NON-NLS-1$ } else { fPackageDialogField.setStatus(""); //$NON-NLS-1$ } } /* * Updates the enable state of buttons related to the enclosing type selection checkbox. */ private void updateEnableState() { boolean enclosing= isEnclosingTypeSelected(); fPackageDialogField.setEnabled(fCanModifyPackage && !enclosing); fEnclosingTypeDialogField.setEnabled(fCanModifyEnclosingType && enclosing); } /** * Hook method that gets called when the enclosing type name has changed. The method * validates the enclosing type and returns the status of the validation. It also updates the * enclosing type model. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus enclosingTypeChanged() { StatusInfo status= new StatusInfo(); fCurrEnclosingType= null; IPackageFragmentRoot root= getPackageFragmentRoot(); fEnclosingTypeDialogField.enableButton(root != null); if (root == null) { status.setError(""); //$NON-NLS-1$ return status; } String enclName= getEnclosingTypeText(); if (enclName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeEnterName")); //$NON-NLS-1$ return status; } try { IType type= root.getJavaProject().findType(enclName); if (type == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ return status; } if (type.getCompilationUnit() == null) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotInCU")); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isEditable(type.getCompilationUnit())) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingNotEditable")); //$NON-NLS-1$ return status; } fCurrEnclosingType= type; IPackageFragmentRoot enclosingRoot= JavaModelUtil.getPackageFragmentRoot(type); if (!enclosingRoot.equals(root)) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.EnclosingNotInSourceFolder")); //$NON-NLS-1$ } return status; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnclosingTypeNotExists")); //$NON-NLS-1$ JavaPlugin.log(e); return status; } } /** * Hook method that gets called when the type name has changed. The method validates the * type name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus typeNameChanged() { StatusInfo status= new StatusInfo(); String typeName= getTypeName(); // must not be empty if (typeName.length() == 0) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.EnterTypeName")); //$NON-NLS-1$ return status; } if (typeName.indexOf('.') != -1) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.QualifiedName")); //$NON-NLS-1$ return status; } IStatus val= JavaConventions.validateJavaTypeName(typeName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getFormattedString("NewTypeWizardPage.error.InvalidTypeName", val.getMessage())); //$NON-NLS-1$ return status; } else if (val.getSeverity() == IStatus.WARNING) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.TypeNameDiscouraged", val.getMessage())); //$NON-NLS-1$ // continue checking } // must not exist if (!isEnclosingTypeSelected()) { IPackageFragment pack= getPackageFragment(); if (pack != null) { ICompilationUnit cu= pack.getCompilationUnit(typeName + ".java"); //$NON-NLS-1$ if (cu.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } else { IType type= getEnclosingType(); if (type != null) { IType member= type.getType(typeName); if (member.exists()) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.TypeNameExists")); //$NON-NLS-1$ return status; } } } return status; } /** * Hook method that gets called when the superclass name has changed. The method * validates the superclass name and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superClassChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperClassDialogField.enableButton(root != null); fSuperClass= null; String sclassName= getSuperClass(); if (sclassName.length() == 0) { // accept the empty field (stands for java.lang.Object) return status; } IStatus val= JavaConventions.validateJavaTypeName(sclassName); if (val.getSeverity() == IStatus.ERROR) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ return status; } if (root != null) { try { IType type= resolveSuperTypeName(root.getJavaProject(), sclassName); if (type == null) { status.setWarning(NewWizardMessages.getString("NewTypeWizardPage.warning.SuperClassNotExists")); //$NON-NLS-1$ return status; } else { if (type.isInterface()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotClass", sclassName)); //$NON-NLS-1$ return status; } int flags= type.getFlags(); if (Flags.isFinal(flags)) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsFinal", sclassName)); //$NON-NLS-1$ return status; } else if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.SuperClassIsNotVisible", sclassName)); //$NON-NLS-1$ return status; } } fSuperClass= type; } catch (JavaModelException e) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.InvalidSuperClassName")); //$NON-NLS-1$ JavaPlugin.log(e); } } else { status.setError(""); //$NON-NLS-1$ } return status; } private IType resolveSuperTypeName(IJavaProject jproject, String sclassName) throws JavaModelException { IType type= null; if (isEnclosingTypeSelected()) { // search in the context of the enclosing type IType enclosingType= getEnclosingType(); if (enclosingType != null) { String[][] res= enclosingType.resolveType(sclassName); if (res != null && res.length > 0) { type= jproject.findType(res[0][0], res[0][1]); } } } else { IPackageFragment currPack= getPackageFragment(); if (type == null && currPack != null) { String packName= currPack.getElementName(); // search in own package if (!currPack.isDefaultPackage()) { type= jproject.findType(packName, sclassName); } // search in java.lang if (type == null && !"java.lang".equals(packName)) { //$NON-NLS-1$ type= jproject.findType("java.lang", sclassName); //$NON-NLS-1$ } } // search fully qualified if (type == null) { type= jproject.findType(sclassName); } } return type; } /** * Hook method that gets called when the list of super interface has changed. The method * validates the superinterfaces and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus superInterfacesChanged() { StatusInfo status= new StatusInfo(); IPackageFragmentRoot root= getPackageFragmentRoot(); fSuperInterfacesDialogField.enableButton(0, root != null); if (root != null) { List elements= fSuperInterfacesDialogField.getElements(); int nElements= elements.size(); for (int i= 0; i < nElements; i++) { String intfname= (String)elements.get(i); try { IType type= root.getJavaProject().findType(intfname); if (type == null) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceNotExists", intfname)); //$NON-NLS-1$ return status; } else { if (type.isClass()) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotInterface", intfname)); //$NON-NLS-1$ return status; } if (!JavaModelUtil.isVisible(type, getPackageFragment())) { status.setWarning(NewWizardMessages.getFormattedString("NewTypeWizardPage.warning.InterfaceIsNotVisible", intfname)); //$NON-NLS-1$ return status; } } } catch (JavaModelException e) { JavaPlugin.log(e); // let pass, checking is an extra } } } return status; } /** * Hook method that gets called when the modifiers have changed. The method validates * the modifiers and returns the status of the validation. * <p> * Subclasses may extend this method to perform their own validation. * </p> * * @return the status of the validation */ protected IStatus modifiersChanged() { StatusInfo status= new StatusInfo(); int modifiers= getModifiers(); if (Flags.isFinal(modifiers) && Flags.isAbstract(modifiers)) { status.setError(NewWizardMessages.getString("NewTypeWizardPage.error.ModifiersFinalAndAbstract")); //$NON-NLS-1$ } return status; } // selection dialogs private IPackageFragment choosePackage() { IPackageFragmentRoot froot= getPackageFragmentRoot(); IJavaElement[] packages= null; try { if (froot != null && froot.exists()) { packages= froot.getChildren(); } } catch (JavaModelException e) { JavaPlugin.log(e); } if (packages == null) { packages= new IJavaElement[0]; } ElementListSelectionDialog dialog= new ElementListSelectionDialog(getShell(), new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT)); dialog.setIgnoreCase(false); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.description")); //$NON-NLS-1$ dialog.setEmptyListMessage(NewWizardMessages.getString("NewTypeWizardPage.ChoosePackageDialog.empty")); //$NON-NLS-1$ dialog.setElements(packages); IPackageFragment pack= getPackageFragment(); if (pack != null) { dialog.setInitialSelections(new Object[] { pack }); } if (dialog.open() == dialog.OK) { return (IPackageFragment) dialog.getFirstResult(); } return null; } private IType chooseEnclosingType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaSearchScope scope= SearchEngine.createJavaSearchScope(new IJavaElement[] { root }); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.TYPE, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.ChooseEnclosingTypeDialog.description")); //$NON-NLS-1$ dialog.setFilter(Signature.getSimpleName(getEnclosingTypeText())); if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private IType chooseSuperType() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return null; } IJavaElement[] elements= new IJavaElement[] { root.getJavaProject() }; IJavaSearchScope scope= SearchEngine.createJavaSearchScope(elements); TypeSelectionDialog dialog= new TypeSelectionDialog(getShell(), getWizard().getContainer(), IJavaSearchConstants.CLASS, scope); dialog.setTitle(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("NewTypeWizardPage.SuperClassDialog.message")); //$NON-NLS-1$ dialog.setFilter(getSuperClass()); if (dialog.open() == dialog.OK) { return (IType) dialog.getFirstResult(); } return null; } private void chooseSuperInterfaces() { IPackageFragmentRoot root= getPackageFragmentRoot(); if (root == null) { return; } IJavaProject project= root.getJavaProject(); SuperInterfaceSelectionDialog dialog= new SuperInterfaceSelectionDialog(getShell(), getWizard().getContainer(), fSuperInterfacesDialogField, project); dialog.setTitle(fIsClass ? NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.class.title") : NewWizardMessages.getString("NewTypeWizardPage.InterfacesDialog.interface.title")); //$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. The progress * monitor must not be <code>null</code> */ public void createType(IProgressMonitor monitor) throws CoreException, InterruptedException { monitor.beginTask(NewWizardMessages.getString("NewTypeWizardPage.operationdesc"), 10); //$NON-NLS-1$ IPackageFragmentRoot root= getPackageFragmentRoot(); IPackageFragment pack= getPackageFragment(); if (pack == null) { pack= root.getPackageFragment(""); //$NON-NLS-1$ } if (!pack.exists()) { String packName= pack.getElementName(); pack= root.createPackageFragment(packName, true, null); } monitor.worked(1); String clName= getTypeName(); boolean isInnerClass= isEnclosingTypeSelected(); IType createdType; ImportsStructure imports; int indent= 0; String[] prefOrder= ImportOrganizePreferencePage.getImportOrderPreference(); int threshold= ImportOrganizePreferencePage.getImportNumberThreshold(); String lineDelimiter= null; if (!isInnerClass) { lineDelimiter= System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ String packStatement= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ";" + lineDelimiter + lineDelimiter; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ ICompilationUnit parentCU= pack.createCompilationUnit(clName + ".java", packStatement, false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ imports= new ImportsStructure(parentCU, prefOrder, threshold, false); // add an import that will be removed again. Having this import solves 14661 imports.addImport(pack.getElementName(), getTypeName()); String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, parentCU); createdType= parentCU.createType(content, null, false, new SubProgressMonitor(monitor, 3)); } else { IType enclosingType= getEnclosingType(); // if we are working on a enclosed type that is open in an editor, // then replace the enclosing type with its working copy IType workingCopy= (IType) EditorUtility.getWorkingCopy(enclosingType); if (workingCopy != null) { enclosingType= workingCopy; } ICompilationUnit parentCU= enclosingType.getCompilationUnit(); imports= new ImportsStructure(parentCU, prefOrder, threshold, true); // 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); String content= constructTypeStub(new ImportsManager(imports), lineDelimiter, parentCU); IJavaElement[] elems= enclosingType.getChildren(); IJavaElement sibling= elems.length > 0 ? elems[0] : null; createdType= enclosingType.createType(content, sibling, false, new SubProgressMonitor(monitor, 1)); indent= StubUtility.getIndentUsed(enclosingType) + 1; } // add imports for superclass/interfaces, so types can be resolved correctly imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); createTypeMembers(createdType, new ImportsManager(imports), new SubProgressMonitor(monitor, 1)); // add imports imports.create(!isInnerClass, new SubProgressMonitor(monitor, 1)); ICompilationUnit cu= createdType.getCompilationUnit(); ISourceRange range; if (isInnerClass) { synchronized(cu) { cu.reconcile(); } range= createdType.getSourceRange(); } else { range= cu.getSourceRange(); } IBuffer buf= cu.getBuffer(); String originalContent= buf.getText(range.getOffset(), range.getLength()); String formattedContent= StubUtility.codeFormat(originalContent, indent, lineDelimiter); buf.replace(range.getOffset(), range.getLength(), formattedContent); if (!isInnerClass) { String fileComment= getFileComment(cu); if (fileComment != null && fileComment.length() > 0) { buf.replace(0, 0, fileComment + lineDelimiter); } buf.save(new SubProgressMonitor(monitor, 1), false); } else { monitor.worked(1); } fCreatedType= createdType; monitor.done(); } /** * Returns the created type. 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, ICompilationUnit parentCU) { StringBuffer buf= new StringBuffer(); String typeComment= getTypeComment(parentCU); if (typeComment != null && typeComment.length() > 0) { buf.append(typeComment); buf.append(lineDelimiter); } int modifiers= getModifiers(); buf.append(Flags.toString(modifiers)); if (modifiers != 0) { buf.append(' '); } buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ buf.append(getTypeName()); writeSuperClass(buf, imports); writeSuperInterfaces(buf, imports); buf.append('{'); buf.append(lineDelimiter); buf.append(lineDelimiter); buf.append('}'); buf.append(lineDelimiter); return buf.toString(); } /** * @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead */ protected void createTypeMembers(IType newType, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { //deprecated } /** * Hook method that gets called from <code>createType</code> to support adding of * unanticipated methods, fields, and inner types to the created type. * <p> * Implementers can use any methods defined on <code>IType</code> to manipulate the * new type. * </p> * <p> * The source code of the new type will be formtted using the platform's formatter. Needed * imports are added by the wizard at the end of the type creation process using the given * import manager. * </p> * * @param newType the new type created via <code>createType</code> * @param imports an import manager which can be used to add new imports * @param monitor a progress monitor to report progress. Must not be <code>null</code> * * @see #createType(IProgressMonitor) */ protected void createTypeMembers(IType newType, ImportsManager imports, IProgressMonitor monitor) throws CoreException { // call for compatibility createTypeMembers(newType, ((ImportsManager)imports).getImportsStructure(), monitor); // default implementation does nothing // example would be // String mainMathod= "public void foo(Vector vec) {}" // createdType.createMethod(main, null, false, null); // imports.addImport("java.lang.Vector"); } /** * Hook mathod that gets called from <code>createType</code> to retrieve * a file comment. This default implementation returns the content of the * 'filecomment' template. * * @return the file comment or <code>null</code> if a file comment * is not desired */ protected String getFileComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doFileComments()) { return getTemplate("filecomment", parentCU, 0); //$NON-NLS-1$ } return null; } /** * Hook method that gets called from <code>createType</code> to retrieve * a type comment. This default implementation returns the content of the * 'typecomment' template. * * @return the type comment or <code>null</code> if a type comment * is not desired */ protected String getTypeComment(ICompilationUnit parentCU) { if (CodeGenerationPreferencePage.doCreateComments()) { return getTemplate("typecomment", parentCU, 0); //$NON-NLS-1$ } 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. * * @param name the template to be evaluated * @param parentCU the templates evaluation context * @param pos a source offset into the parent compilation unit. The * template is evalutated at the given source offset */ protected String getTemplate(String name, ICompilationUnit parentCU, int pos) { try { Template[] templates= Templates.getInstance().getTemplates(name); if (templates.length > 0) { return JavaContext.evaluateTemplate(templates[0], parentCU, pos); } } catch (CoreException e) { JavaPlugin.log(e); } return null; } /** * @deprecated Use createInheritedMethods(IType,boolean,boolean,IImportsManager,IProgressMonitor) */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, IImportsStructure imports, IProgressMonitor monitor) throws CoreException { return createInheritedMethods(type, doConstructors, doUnimplementedMethods, new ImportsManager(imports), monitor); } /** * Creates the bodies of all unimplemented methods and constructors and adds them to the type. * Method is typically called by implementers of <code>NewTypeWizardPage</code> to add * needed method and constructors. * * @param type the type for which the new methods and constructor are to be created * @param doConstructors if <code>true</code> unimplemented constructors are created * @param doUnimplementedMethods if <code>true</code> unimplemented methods are created * @param imports an import manager to add all neded import statements * @param monitor a progress monitor to report progress */ protected IMethod[] createInheritedMethods(IType type, boolean doConstructors, boolean doUnimplementedMethods, ImportsManager imports, IProgressMonitor monitor) throws CoreException { ArrayList newMethods= new ArrayList(); ITypeHierarchy hierarchy= type.newSupertypeHierarchy(monitor); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (doConstructors) { IType superclass= hierarchy.getSuperclass(type); if (superclass != null) { String[] constructors= StubUtility.evalConstructors(type, superclass, settings, imports.getImportsStructure()); if (constructors != null) { for (int i= 0; i < constructors.length; i++) { newMethods.add(constructors[i]); } } } } if (doUnimplementedMethods) { String[] unimplemented= StubUtility.evalUnimplementedMethods(type, hierarchy, false, settings, null, imports.getImportsStructure()); if (unimplemented != null) { for (int i= 0; i < unimplemented.length; i++) { newMethods.add(unimplemented[i]); } } } IMethod[] createdMethods= new IMethod[newMethods.size()]; for (int i= 0; i < newMethods.size(); i++) { String content= (String) newMethods.get(i) + '\n'; // content will be formatted, ok to use \n createdMethods[i]= type.createMethod(content, null, false, null); } return createdMethods; } // ---- creation ---------------- /** * Returns the runnable that creates the type using the current settings. * The returned runnable must be executed in the UI thread. * * @return the runnable to create the new type */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { if (monitor == null) { monitor= new NullProgressMonitor(); } createType(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } }
14,386
Bug 14386 Wrong Javadoc insertion in Editor
Testet with: Eclipse 2.0 (pre-release) Build 20020416 I played with the "Add Javadoc comment" feature and found the following bug. Using this source as the correct starting point: ----------------- test code: package test; /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class HelloWorld { /** * Method main. * @param args */ public static void main(String[] args) { System.out.println("args = " + args); System.out.println("line 2 ..."); } } /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ class SecondClass { public SecondClass { }//constructor private void doIt() { //bla } }//SecondClass ----------------------------- i double click the method "doIt()" in the tree browser on the right hand site. the result is: --------------------------- package test; /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class HelloWorld { /** * Method main. * @param args */ public static void main(String[] args) { System.out.println("args = " + args); System.out.println("line 2 ..."); } } /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ class SecondClass { public SecondClass { /** * Method doIt. */ }//constructor private void doIt() { //bla } }//SecondClass ------------------------------- => the javadoc comment is inserted within the body of the constructor of the class "SecondClass" - one line above.
resolved fixed
bc1d067
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T16:08:37Z
2002-04-23T08:20:00Z
org.eclipse.jdt.ui/core
14,386
Bug 14386 Wrong Javadoc insertion in Editor
Testet with: Eclipse 2.0 (pre-release) Build 20020416 I played with the "Add Javadoc comment" feature and found the following bug. Using this source as the correct starting point: ----------------- test code: package test; /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class HelloWorld { /** * Method main. * @param args */ public static void main(String[] args) { System.out.println("args = " + args); System.out.println("line 2 ..."); } } /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ class SecondClass { public SecondClass { }//constructor private void doIt() { //bla } }//SecondClass ----------------------------- i double click the method "doIt()" in the tree browser on the right hand site. the result is: --------------------------- package test; /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class HelloWorld { /** * Method main. * @param args */ public static void main(String[] args) { System.out.println("args = " + args); System.out.println("line 2 ..."); } } /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ class SecondClass { public SecondClass { /** * Method doIt. */ }//constructor private void doIt() { //bla } }//SecondClass ------------------------------- => the javadoc comment is inserted within the body of the constructor of the class "SecondClass" - one line above.
resolved fixed
bc1d067
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T16:08:37Z
2002-04-23T08:20:00Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/AddJavaDocStubOperation.java
14,386
Bug 14386 Wrong Javadoc insertion in Editor
Testet with: Eclipse 2.0 (pre-release) Build 20020416 I played with the "Add Javadoc comment" feature and found the following bug. Using this source as the correct starting point: ----------------- test code: package test; /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class HelloWorld { /** * Method main. * @param args */ public static void main(String[] args) { System.out.println("args = " + args); System.out.println("line 2 ..."); } } /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ class SecondClass { public SecondClass { }//constructor private void doIt() { //bla } }//SecondClass ----------------------------- i double click the method "doIt()" in the tree browser on the right hand site. the result is: --------------------------- package test; /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ public class HelloWorld { /** * Method main. * @param args */ public static void main(String[] args) { System.out.println("args = " + args); System.out.println("line 2 ..."); } } /** * @author MH * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. */ class SecondClass { public SecondClass { /** * Method doIt. */ }//constructor private void doIt() { //bla } }//SecondClass ------------------------------- => the javadoc comment is inserted within the body of the constructor of the class "SecondClass" - one line above.
resolved fixed
bc1d067
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T16:08:37Z
2002-04-23T08:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/actions/AddJavaDocStubAction.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.actions; import java.lang.reflect.InvocationTargetException; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IMethod; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.internal.corext.codemanipulation.AddJavaDocStubOperation; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.actions.ActionMessages; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter; import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; /** * Creates a Java Doc Stubs for the selected members. * <p> * Will open the parent compilation unit in a Java editor. The result is * unsaved, so the user can decide if the changes are acceptable. * <p> * The action is applicable to structured selections containing elements * of type <code>IMember</code>. * * <p> * This class may be instantiated; it is not intended to be subclassed. * </p> * * @since 2.0 */ public class AddJavaDocStubAction extends SelectionDispatchAction { private CompilationUnitEditor fEditor; /** * Creates a new <code>AddJavaDocStubAction</code>. The action requires * that the selection provided by the site's selection provider is of type <code> * org.eclipse.jface.viewers.IStructuredSelection</code>. * * @param site the site providing context information for this action */ public AddJavaDocStubAction(IWorkbenchSite site) { super(site); setText(ActionMessages.getString("AddJavaDocStubAction.label")); //$NON-NLS-1$ setDescription(ActionMessages.getString("AddJavaDocStubAction.description")); //$NON-NLS-1$ setToolTipText(ActionMessages.getString("AddJavaDocStubAction.tooltip")); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.ADD_JAVADOC_STUB_ACTION); } /** * Note: This constructor is for internal use only. Clients should not call this constructor. */ public AddJavaDocStubAction(CompilationUnitEditor editor) { this(editor.getEditorSite()); fEditor= editor; setEnabled(checkEnabledEditor()); } //---- Structured Viewer ----------------------------------------------------------- /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void selectionChanged(IStructuredSelection selection) { IMember[] members= getSelectedMembers(selection); setEnabled(members != null && members.length > 0 && JavaModelUtil.isEditable(members[0].getCompilationUnit())); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(IStructuredSelection selection) { IMember[] members= getSelectedMembers(selection); if (members == null || members.length == 0) { return; } try { ICompilationUnit cu= members[0].getCompilationUnit(); // open the editor, forces the creation of a working copy IEditorPart editor= EditorUtility.openInEditor(cu); ICompilationUnit workingCopyCU; IMember[] workingCopyMembers; if (cu.isWorkingCopy()) { workingCopyCU= cu; workingCopyMembers= members; synchronized (workingCopyCU) { workingCopyCU.reconcile(); } } else { // get the corresponding elements from the working copy workingCopyCU= EditorUtility.getWorkingCopy(cu); if (workingCopyCU == null) { showError(ActionMessages.getString("AddJavaDocStubsAction.error.noWorkingCopy")); //$NON-NLS-1$ return; } workingCopyMembers= new IMember[members.length]; for (int i= 0; i < members.length; i++) { IMember member= members[i]; IMember workingCopyMember= (IMember) JavaModelUtil.findMemberInCompilationUnit(workingCopyCU, member); if (workingCopyMember == null) { showError(ActionMessages.getFormattedString("AddJavaDocStubsAction.error.memberNotExisting", member.getElementName())); //$NON-NLS-1$ return; } workingCopyMembers[i]= workingCopyMember; } } run(workingCopyMembers); synchronized (workingCopyCU) { workingCopyCU.reconcile(); } EditorUtility.revealInEditor(editor, members[0]); } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$ } } //---- Java Editior -------------------------------------------------------------- /* package */ void editorStateChanged() { setEnabled(checkEnabledEditor()); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void selectionChanged(ITextSelection selection) { } private boolean checkEnabledEditor() { return fEditor != null && !fEditor.isEditorInputReadOnly() && SelectionConverter.canOperateOn(fEditor); } /* (non-Javadoc) * Method declared on SelectionDispatchAction */ protected void run(ITextSelection selection) { try { IJavaElement element= SelectionConverter.getElementAtOffset(fEditor); int type= element != null ? element.getElementType() : -1; if (type != IJavaElement.METHOD && type != IJavaElement.TYPE) { element= SelectionConverter.getTypeAtOffset(fEditor); if (element == null) { MessageDialog.openInformation(getShell(), getDialogTitle(), ActionMessages.getString("AddJavaDocStubsAction.not_applicable")); //$NON-NLS-1$ return; } } run(new IMember[] { (IMember)element }); } catch (CoreException e) { ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$ } } //---- Helpers ------------------------------------------------------------------- private void run(IMember[] members) { try { CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); AddJavaDocStubOperation op= new AddJavaDocStubOperation(members, settings); ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); dialog.run(false, true, new WorkbenchRunnableAdapter(op)); } catch (InvocationTargetException e) { ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.getString("AddJavaDocStubsAction.error.actionFailed")); //$NON-NLS-1$ } catch (InterruptedException e) { // operation cancelled } } private void showError(String message) { MessageDialog.openError(getShell(), getDialogTitle(), message); } private IMember[] getSelectedMembers(IStructuredSelection selection) { List elements= selection.toList(); int nElements= elements.size(); if (nElements > 0) { IMember[] res= new IMember[nElements]; ICompilationUnit cu= null; for (int i= 0; i < nElements; i++) { Object curr= elements.get(i); if (curr instanceof IMethod || curr instanceof IType) { IMember member= (IMember)curr; // limit to methods & types if (i == 0) { cu= member.getCompilationUnit(); if (cu == null) { return null; } } else if (!cu.equals(member.getCompilationUnit())) { return null; } res[i]= member; } else { return null; } } return res; } return null; } private String getDialogTitle() { return ActionMessages.getString("AddJavaDocStubsAction.error.dialogTitle"); //$NON-NLS-1$ } }
15,726
Bug 15726 moves field comments from one field to another [quick fix]
20020508 public class A { int field; //field comment A(int fred){ _fred= fred; } } you are offered to create field _fred but then it steals the comment: int field; private int _fred; //field comment
resolved fixed
d8aa460
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T18:25:14Z
2002-05-10T14:13:20Z
org.eclipse.jdt.ui.tests/ui/org/eclipse/jdt/ui/tests/astrewrite/ASTRewritingStatementsTest.java
package org.eclipse.jdt.ui.tests.astrewrite; import java.util.Hashtable; import java.util.List; import junit.framework.Test; import junit.framework.TestSuite; 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.*; import org.eclipse.jdt.testplugin.JavaProjectHelper; import org.eclipse.jdt.testplugin.TestPluginLauncher; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.ui.text.correction.ASTResolving; import org.eclipse.jdt.internal.ui.text.correction.ASTRewriteCorrectionProposal; public class ASTRewritingStatementsTest extends ASTRewritingTest { private final boolean BUG_23259= false; private static final Class THIS= ASTRewritingStatementsTest.class; private IJavaProject fJProject1; private IPackageFragmentRoot fSourceFolder; public ASTRewritingStatementsTest(String name) { super(name); } public static void main(String[] args) { TestPluginLauncher.run(TestPluginLauncher.getLocationFromProperties(), THIS, args); } public static Test suite() { if (false) { return new TestSuite(THIS); } else { TestSuite suite= new TestSuite(); suite.addTest(new ASTRewritingStatementsTest("testRemove")); return suite; } } protected void setUp() throws Exception { Hashtable options= JavaCore.getOptions(); options.put(JavaCore.FORMATTER_TAB_CHAR, JavaCore.SPACE); options.put(JavaCore.FORMATTER_TAB_SIZE, "4"); JavaCore.setOptions(options); fJProject1= JavaProjectHelper.createJavaProject("TestProject1", "bin"); assertTrue("rt not found", JavaProjectHelper.addRTJar(fJProject1) != null); fSourceFolder= JavaProjectHelper.addSourceContainer(fJProject1, "src"); } protected void tearDown() throws Exception { JavaProjectHelper.delete(fJProject1); } public void testAdd() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); { /* foo(): append a return statement */ StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" public Object foo() {\n"); buf.append(" if (this.equals(new Object())) {\n"); buf.append(" toString();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "C"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= block.statements(); ReturnStatement returnStatement= block.getAST().newReturnStatement(); returnStatement.setExpression(ASTResolving.getInitExpression(methodDecl.getReturnType())); statements.add(returnStatement); rewrite.markAsInserted(returnStatement); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" public Object foo() {\n"); buf.append(" if (this.equals(new Object())) {\n"); buf.append(" toString();\n"); buf.append(" }\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } { /* hoo(): return; -> return false; */ StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class D {\n"); buf.append(" public Object goo() {\n"); buf.append(" return new Integer(3);\n"); buf.append(" }\n"); buf.append(" public void hoo(int p1, Object p2) {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("D.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "D"); MethodDeclaration methodDecl= findMethodDeclaration(type, "hoo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= block.statements(); assertTrue("No statements in block", !statements.isEmpty()); assertTrue("No ReturnStatement", statements.get(0) instanceof ReturnStatement); ReturnStatement returnStatement= (ReturnStatement) statements.get(0); Expression expr= block.getAST().newBooleanLiteral(false); returnStatement.setExpression(expr); rewrite.markAsInserted(expr); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class D {\n"); buf.append(" public Object goo() {\n"); buf.append(" return new Integer(3);\n"); buf.append(" }\n"); buf.append(" public void hoo(int p1, Object p2) {\n"); buf.append(" return false;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } } public void testRemove() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); { /* foo(): remove if... */ StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" public Object foo() {\n"); buf.append(" if (this.equals(new Object())) {\n"); buf.append(" toString();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "C"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= block.statements(); assertTrue("No statements in block", !statements.isEmpty()); rewrite.markAsRemoved((ASTNode) statements.get(0)); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" public Object foo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } { StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class D {\n"); buf.append(" public Object goo() {\n"); buf.append(" return new Integer(3);\n"); buf.append(" }\n"); buf.append(" public void hoo(int p1, Object p2) {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("D.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "D"); MethodDeclaration methodDecl= findMethodDeclaration(type, "goo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= block.statements(); assertTrue("No statements in block", !statements.isEmpty()); assertTrue("No ReturnStatement", statements.get(0) instanceof ReturnStatement); ReturnStatement returnStatement= (ReturnStatement) statements.get(0); Expression expr= returnStatement.getExpression(); rewrite.markAsRemoved(expr); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class D {\n"); buf.append(" public Object goo() {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" public void hoo(int p1, Object p2) {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } /* { // delete StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public Object goo() {\n"); buf.append(" i++; //comment\n"); buf.append(" i++; //comment\n"); buf.append(" return new Integer(3);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "goo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= methodDecl.getBody().statements(); rewrite.markAsRemoved((ASTNode) statements.get(0)); rewrite.markAsRemoved((ASTNode) statements.get(1)); rewrite.markAsRemoved((ASTNode) statements.get(2)); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public Object goo() {\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); }*/ } public void testReplace() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); { /* foo(): if.. -> return; */ StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" public Object foo() {\n"); buf.append(" if (this.equals(new Object())) {\n"); buf.append(" toString();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("C.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "C"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= block.statements(); assertTrue("No statements in block", !statements.isEmpty()); ReturnStatement returnStatement= block.getAST().newReturnStatement(); rewrite.markAsReplaced((ASTNode) statements.get(0), returnStatement); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class C {\n"); buf.append(" public Object foo() {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } { /* goo(): new Integer(3) -> 'null' */ StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class D {\n"); buf.append(" public Object goo() {\n"); buf.append(" return new Integer(3);\n"); buf.append(" }\n"); buf.append(" public void hoo(int p1, Object p2) {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("D.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); TypeDeclaration type= findTypeDeclaration(astRoot, "D"); MethodDeclaration methodDecl= findMethodDeclaration(type, "goo"); Block block= methodDecl.getBody(); assertTrue("No block" , block != null); List statements= block.statements(); assertTrue("No statements in block", !statements.isEmpty()); assertTrue("No ReturnStatement", statements.get(0) instanceof ReturnStatement); ReturnStatement returnStatement= (ReturnStatement) statements.get(0); Expression expr= returnStatement.getExpression(); Expression modified= ASTResolving.getInitExpression(methodDecl.getReturnType()); rewrite.markAsReplaced(expr, modified); ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class D {\n"); buf.append(" public Object goo() {\n"); buf.append(" return null;\n"); buf.append(" }\n"); buf.append(" public void hoo(int p1, Object p2) {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } } public void testBreakStatement() 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(" break;\n"); buf.append(" break label;\n"); buf.append(" break label;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 3", statements.size() == 3); { // insert label BreakStatement statement= (BreakStatement) statements.get(0); assertTrue("Has label", statement.getLabel() == null); SimpleName newLabel= ast.newSimpleName("label2"); statement.setLabel(newLabel); rewrite.markAsInserted(newLabel); } { // replace label BreakStatement statement= (BreakStatement) statements.get(1); SimpleName label= statement.getLabel(); assertTrue("Has no label", label != null); SimpleName newLabel= ast.newSimpleName("label2"); rewrite.markAsReplaced(label, newLabel); } { // remove label BreakStatement statement= (BreakStatement) statements.get(2); SimpleName label= statement.getLabel(); assertTrue("Has no label", label != null); rewrite.markAsRemoved(label); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" break label2;\n"); buf.append(" break label2;\n"); buf.append(" break;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testConstructorInvocation() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E(String e, String f) {\n"); buf.append(" this();\n"); buf.append(" }\n"); buf.append(" public E() {\n"); buf.append(" this(\"Hello\", true);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration[] declarations= type.getMethods(); assertTrue("Number of statements not 2", declarations.length == 2); { // add parameters Block block= declarations[0].getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); ConstructorInvocation invocation= (ConstructorInvocation) statements.get(0); List arguments= invocation.arguments(); StringLiteral stringLiteral1= ast.newStringLiteral(); stringLiteral1.setLiteralValue("Hello"); arguments.add(stringLiteral1); rewrite.markAsInserted(stringLiteral1); StringLiteral stringLiteral2= ast.newStringLiteral(); stringLiteral2.setLiteralValue("World"); arguments.add(stringLiteral2); rewrite.markAsInserted(stringLiteral2); } { //remove parameters Block block= declarations[1].getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); ConstructorInvocation invocation= (ConstructorInvocation) statements.get(0); List arguments= invocation.arguments(); rewrite.markAsRemoved((ASTNode) arguments.get(0)); rewrite.markAsRemoved((ASTNode) arguments.get(1)); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public E(String e, String f) {\n"); buf.append(" this(\"Hello\", \"World\");\n"); buf.append(" }\n"); buf.append(" public E() {\n"); buf.append(" this();\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testContinueStatement() 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(" continue;\n"); buf.append(" continue label;\n"); buf.append(" continue label;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 3", statements.size() == 3); { // insert label ContinueStatement statement= (ContinueStatement) statements.get(0); assertTrue("Has label", statement.getLabel() == null); SimpleName newLabel= ast.newSimpleName("label2"); statement.setLabel(newLabel); rewrite.markAsInserted(newLabel); } { // replace label ContinueStatement statement= (ContinueStatement) statements.get(1); SimpleName label= statement.getLabel(); assertTrue("Has no label", label != null); SimpleName newLabel= ast.newSimpleName("label2"); rewrite.markAsReplaced(label, newLabel); } { // remove label ContinueStatement statement= (ContinueStatement) statements.get(2); SimpleName label= statement.getLabel(); assertTrue("Has no label", label != null); rewrite.markAsRemoved(label); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" continue label2;\n"); buf.append(" continue label2;\n"); buf.append(" continue;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testDoStatement() 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(" do {\n"); buf.append(" System.beep();\n"); buf.append(" } while (i == j);\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace body and expression DoStatement doStatement= (DoStatement) statements.get(0); Block newBody= ast.newBlock(); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName("hoo")); invocation.arguments().add(ast.newNumberLiteral("11")); newBody.statements().add(ast.newExpressionStatement(invocation)); rewrite.markAsReplaced(doStatement.getBody(), newBody); BooleanLiteral literal= ast.newBooleanLiteral(true); rewrite.markAsReplaced(doStatement.getExpression(), literal); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" do {\n"); buf.append(" hoo(11);\n"); buf.append(" } while (true);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testExpressionStatement() 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(" i= 0;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("Parse errors", (block.getFlags() & ASTNode.MALFORMED) == 0); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace expression ExpressionStatement stmt= (ExpressionStatement) statements.get(0); Assignment assignment= (Assignment) stmt.getExpression(); Expression placeholder= (Expression) rewrite.createCopy(assignment); Assignment newExpression= ast.newAssignment(); newExpression.setLeftHandSide(ast.newSimpleName("x")); newExpression.setRightHandSide(placeholder); newExpression.setOperator(Assignment.Operator.ASSIGN); rewrite.markAsReplaced(stmt.getExpression(), newExpression); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" x = i= 0;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testForStatement() 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(" for (int i= 0; i < len; i++) {\n"); buf.append(" }\n"); buf.append(" for (i= 0, j= 0; i < len; i++, j++) {\n"); buf.append(" }\n"); buf.append(" for (;;) {\n"); buf.append(" }\n"); buf.append(" for (;;) {\n"); buf.append(" }\n"); buf.append(" for (i= 0; i < len; 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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("Parse errors", (block.getFlags() & ASTNode.MALFORMED) == 0); List statements= block.statements(); assertTrue("Number of statements not 5", statements.size() == 5); { // replace initializer, change expression, add updater, replace cody ForStatement forStatement= (ForStatement) statements.get(0); List initializers= forStatement.initializers(); assertTrue("Number of initializers not 1", initializers.size() == 1); Assignment assignment= ast.newAssignment(); assignment.setLeftHandSide(ast.newSimpleName("i")); assignment.setOperator(Assignment.Operator.ASSIGN); assignment.setRightHandSide(ast.newNumberLiteral("3")); rewrite.markAsReplaced((ASTNode) initializers.get(0), assignment); Assignment assignment2= ast.newAssignment(); assignment2.setLeftHandSide(ast.newSimpleName("j")); assignment2.setOperator(Assignment.Operator.ASSIGN); assignment2.setRightHandSide(ast.newNumberLiteral("4")); rewrite.markAsInserted(assignment2); initializers.add(assignment2); BooleanLiteral literal= ast.newBooleanLiteral(true); rewrite.markAsReplaced(forStatement.getExpression(), literal); // add updater PrefixExpression prefixExpression= ast.newPrefixExpression(); prefixExpression.setOperand(ast.newSimpleName("j")); prefixExpression.setOperator(PrefixExpression.Operator.INCREMENT); forStatement.updaters().add(prefixExpression); rewrite.markAsInserted(prefixExpression); // replace body Block newBody= ast.newBlock(); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName("hoo")); invocation.arguments().add(ast.newNumberLiteral("11")); newBody.statements().add(ast.newExpressionStatement(invocation)); rewrite.markAsReplaced(forStatement.getBody(), newBody); } { // remove initializers, expression and updaters ForStatement forStatement= (ForStatement) statements.get(1); List initializers= forStatement.initializers(); assertTrue("Number of initializers not 2", initializers.size() == 2); rewrite.markAsRemoved((ASTNode) initializers.get(0)); rewrite.markAsRemoved((ASTNode) initializers.get(1)); rewrite.markAsRemoved(forStatement.getExpression()); List updaters= forStatement.updaters(); assertTrue("Number of initializers not 2", updaters.size() == 2); rewrite.markAsRemoved((ASTNode) updaters.get(0)); rewrite.markAsRemoved((ASTNode) updaters.get(1)); } { // insert updater ForStatement forStatement= (ForStatement) statements.get(2); PrefixExpression prefixExpression= ast.newPrefixExpression(); prefixExpression.setOperand(ast.newSimpleName("j")); prefixExpression.setOperator(PrefixExpression.Operator.INCREMENT); forStatement.updaters().add(prefixExpression); rewrite.markAsInserted(prefixExpression); } { // insert updater & initializer ForStatement forStatement= (ForStatement) statements.get(3); Assignment assignment= ast.newAssignment(); assignment.setLeftHandSide(ast.newSimpleName("j")); assignment.setOperator(Assignment.Operator.ASSIGN); assignment.setRightHandSide(ast.newNumberLiteral("3")); forStatement.initializers().add(assignment); rewrite.markAsInserted(assignment); PrefixExpression prefixExpression= ast.newPrefixExpression(); prefixExpression.setOperand(ast.newSimpleName("j")); prefixExpression.setOperator(PrefixExpression.Operator.INCREMENT); forStatement.updaters().add(prefixExpression); rewrite.markAsInserted(prefixExpression); } { // replace initializer: turn assignement to var decl ForStatement forStatement= (ForStatement) statements.get(4); Assignment assignment= (Assignment) forStatement.initializers().get(0); SimpleName leftHandSide= (SimpleName) assignment.getLeftHandSide(); VariableDeclarationFragment varFragment= ast.newVariableDeclarationFragment(); VariableDeclarationExpression varDecl= ast.newVariableDeclarationExpression(varFragment); varFragment.setName(ast.newSimpleName(leftHandSide.getIdentifier())); Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); varFragment.setInitializer(placeholder); varDecl.setType(ast.newPrimitiveType(PrimitiveType.INT)); rewrite.markAsReplaced(assignment, varDecl); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" for (i = 3, j = 4; true; i++, ++j) {\n"); buf.append(" hoo(11);\n"); buf.append(" }\n"); buf.append(" for (;;) {\n"); buf.append(" }\n"); buf.append(" for (;;++j) {\n"); buf.append(" }\n"); buf.append(" for (j = 3;;++j) {\n"); buf.append(" }\n"); buf.append(" for (int i = 0; i < len; i++) {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testIfStatement() 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(" if (i == 0) {\n"); buf.append(" System.beep();\n"); buf.append(" } else {\n"); buf.append(" }\n"); buf.append(" if (i == 0) {\n"); buf.append(" System.beep();\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 2", statements.size() == 2); { // replace expression body and then body, remove else body IfStatement ifStatement= (IfStatement) statements.get(0); BooleanLiteral literal= ast.newBooleanLiteral(true); rewrite.markAsReplaced(ifStatement.getExpression(), literal); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName("hoo")); invocation.arguments().add(ast.newNumberLiteral("11")); Block newBody= ast.newBlock(); newBody.statements().add(ast.newExpressionStatement(invocation)); rewrite.markAsReplaced(ifStatement.getThenStatement(), newBody); rewrite.markAsRemoved(ifStatement.getElseStatement()); } { // add else body IfStatement ifStatement= (IfStatement) statements.get(1); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName("hoo")); invocation.arguments().add(ast.newNumberLiteral("11")); Block newBody= ast.newBlock(); newBody.statements().add(ast.newExpressionStatement(invocation)); rewrite.markAsInserted(newBody); ifStatement.setElseStatement(newBody); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" if (true) {\n"); buf.append(" hoo(11);\n"); buf.append(" }\n"); buf.append(" if (i == 0) {\n"); buf.append(" System.beep();\n"); buf.append(" } else {\n"); buf.append(" hoo(11);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testLabeledStatement() 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(" label: if (i == 0) {\n"); buf.append(" System.beep();\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace label and statement LabeledStatement labeledStatement= (LabeledStatement) statements.get(0); Name newLabel= ast.newSimpleName("newLabel"); rewrite.markAsReplaced(labeledStatement.getLabel(), newLabel); Assignment newExpression= ast.newAssignment(); newExpression.setLeftHandSide(ast.newSimpleName("x")); newExpression.setRightHandSide(ast.newNumberLiteral("1")); newExpression.setOperator(Assignment.Operator.ASSIGN); Statement newStatement= ast.newExpressionStatement(newExpression); rewrite.markAsReplaced(labeledStatement.getBody(), newStatement); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" newLabel: x = 1;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testReturnStatement() 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(" return;\n"); buf.append(" return 1;\n"); buf.append(" return 1;\n"); buf.append(" return 1 + 2;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 4", statements.size() == 4); { // insert expression ReturnStatement statement= (ReturnStatement) statements.get(0); assertTrue("Has expression", statement.getExpression() == null); SimpleName newExpression= ast.newSimpleName("x"); statement.setExpression(newExpression); rewrite.markAsInserted(newExpression); } { // replace expression ReturnStatement statement= (ReturnStatement) statements.get(1); Expression expression= statement.getExpression(); assertTrue("Has no label", expression != null); SimpleName newExpression= ast.newSimpleName("x"); rewrite.markAsReplaced(expression, newExpression); } { // remove expression ReturnStatement statement= (ReturnStatement) statements.get(2); Expression expression= statement.getExpression(); assertTrue("Has no label", expression != null); rewrite.markAsRemoved(expression); } { // modify in expression (no change) ReturnStatement statement= (ReturnStatement) statements.get(3); InfixExpression expression= (InfixExpression) statement.getExpression(); rewrite.markAsReplaced(expression.getLeftOperand(), ast.newNumberLiteral("9")); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" return x;\n"); buf.append(" return x;\n"); buf.append(" return;\n"); buf.append(" return 9 + 2;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testSwitchStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" switch (i) {\n"); buf.append(" }\n"); buf.append(" switch (i) {\n"); buf.append(" case 1:\n"); buf.append(" i= 1;\n"); buf.append(" break;\n"); buf.append(" case 2:\n"); buf.append(" i= 2;\n"); buf.append(" break;\n"); buf.append(" default:\n"); buf.append(" i= 3;\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List blockStatements= block.statements(); assertTrue("Number of statements not 2", blockStatements.size() == 2); { // insert statements, replace expression SwitchStatement switchStatement= (SwitchStatement) blockStatements.get(0); ASTNode expression= switchStatement.getExpression(); SimpleName newExpression= ast.newSimpleName("x"); rewrite.markAsReplaced(expression, newExpression); List statements= switchStatement.statements(); assertTrue("Number of statements not 0", statements.size() == 0); SwitchCase caseStatement1= ast.newSwitchCase(); caseStatement1.setExpression(ast.newNumberLiteral("1")); rewrite.markAsInserted(caseStatement1); statements.add(caseStatement1); Statement statement1= ast.newReturnStatement(); rewrite.markAsInserted(statement1); statements.add(statement1); SwitchCase caseStatement2= ast.newSwitchCase(); // default caseStatement2.setExpression(null); rewrite.markAsInserted(caseStatement2); statements.add(caseStatement2); } { // insert, remove, replace statements, change case statements SwitchStatement switchStatement= (SwitchStatement) blockStatements.get(1); List statements= switchStatement.statements(); assertTrue("Number of statements not 8", statements.size() == 8); // remove statements if (BUG_23259) { System.out.println(getClass().getName()+"::" + getName() +" limited (bug 23259)"); } else { rewrite.markAsRemoved((ASTNode) statements.get(0)); rewrite.markAsRemoved((ASTNode) statements.get(1)); rewrite.markAsRemoved((ASTNode) statements.get(2)); } // change case statement SwitchCase caseStatement= (SwitchCase) statements.get(3); Expression newCaseExpression= ast.newNumberLiteral("10"); rewrite.markAsReplaced(caseStatement.getExpression(), newCaseExpression); { // insert case statement SwitchCase caseStatement2= ast.newSwitchCase(); caseStatement2.setExpression(ast.newNumberLiteral("11")); rewrite.markAsInserted(caseStatement2); statements.add(0, caseStatement2); // insert statement Statement statement1= ast.newReturnStatement(); rewrite.markAsInserted(statement1); statements.add(1, statement1); } { // insert case statement SwitchCase caseStatement2= ast.newSwitchCase(); caseStatement2.setExpression(ast.newNumberLiteral("12")); rewrite.markAsInserted(caseStatement2); statements.add(caseStatement2); // insert statement Statement statement1= ast.newReturnStatement(); rewrite.markAsInserted(statement1); statements.add(statement1); } } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" switch (x) {\n"); buf.append(" case 1 :\n"); buf.append(" return;\n"); buf.append(" default :\n"); buf.append(" }\n"); buf.append(" switch (i) {\n"); buf.append(" case 11 :\n"); buf.append(" return;\n"); if (BUG_23259) { buf.append(" case 1:\n"); buf.append(" i= 1;\n"); buf.append(" break;\n"); } buf.append(" case 10:\n"); buf.append(" i= 2;\n"); buf.append(" break;\n"); buf.append(" default:\n"); buf.append(" i= 3;\n"); buf.append(" case 12 :\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testSynchronizedStatement() 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(" synchronized(this) {\n"); buf.append(" System.beep();\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace expression and body SynchronizedStatement statement= (SynchronizedStatement) statements.get(0); ASTNode newExpression= ast.newSimpleName("obj"); rewrite.markAsReplaced(statement.getExpression(), newExpression); Block newBody= ast.newBlock(); Assignment assign= ast.newAssignment(); assign.setLeftHandSide(ast.newSimpleName("x")); assign.setRightHandSide(ast.newNumberLiteral("1")); assign.setOperator(Assignment.Operator.ASSIGN); newBody.statements().add(ast.newExpressionStatement(assign)); rewrite.markAsReplaced(statement.getBody(), newBody); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" synchronized(obj) {\n"); buf.append(" x = 1;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testThrowStatement() 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(" throw new Exception();\n"); buf.append(" }\n"); buf.append(" public void goo() {\n"); buf.append(" throw new Exception('d');\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("E.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); { // replace expression MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); ThrowStatement statement= (ThrowStatement) statements.get(0); ClassInstanceCreation creation= ast.newClassInstanceCreation(); creation.setName(ast.newSimpleName("NullPointerException")); creation.arguments().add(ast.newSimpleName("x")); rewrite.markAsReplaced(statement.getExpression(), creation); } { // modify expression MethodDeclaration methodDecl= findMethodDeclaration(type, "goo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); ThrowStatement statement= (ThrowStatement) statements.get(0); ClassInstanceCreation creation= (ClassInstanceCreation) statement.getExpression(); ASTNode newArgument= ast.newSimpleName("x"); rewrite.markAsReplaced((ASTNode) creation.arguments().get(0), newArgument); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" throw new NullPointerException(x);\n"); buf.append(" }\n"); buf.append(" public void goo() {\n"); buf.append(" throw new Exception(x);\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testTryStatement() throws Exception { IPackageFragment pack1= fSourceFolder.createPackageFragment("test1", false, null); StringBuffer buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" try {\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" try {\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } finally {\n"); buf.append(" }\n"); buf.append(" try {\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List blockStatements= block.statements(); assertTrue("Number of statements not 3", blockStatements.size() == 3); { // add catch, replace finally TryStatement tryStatement= (TryStatement) blockStatements.get(0); CatchClause catchClause= ast.newCatchClause(); SingleVariableDeclaration decl= ast.newSingleVariableDeclaration(); decl.setType(ast.newSimpleType(ast.newSimpleName("IOException"))); decl.setName(ast.newSimpleName("e")); catchClause.setException(decl); rewrite.markAsInserted(catchClause); tryStatement.catchClauses().add(catchClause); Block body= ast.newBlock(); body.statements().add(ast.newReturnStatement()); rewrite.markAsReplaced(tryStatement.getFinally(), body); } { // replace catch, remove finally TryStatement tryStatement= (TryStatement) blockStatements.get(1); List catchClauses= tryStatement.catchClauses(); CatchClause catchClause= ast.newCatchClause(); SingleVariableDeclaration decl= ast.newSingleVariableDeclaration(); decl.setType(ast.newSimpleType(ast.newSimpleName("Exception"))); decl.setName(ast.newSimpleName("x")); catchClause.setException(decl); rewrite.markAsReplaced((ASTNode) catchClauses.get(0), catchClause); rewrite.markAsRemoved(tryStatement.getFinally()); } { // remove catch, add finally TryStatement tryStatement= (TryStatement) blockStatements.get(2); List catchClauses= tryStatement.catchClauses(); rewrite.markAsRemoved((ASTNode) catchClauses.get(0)); Block body= ast.newBlock(); body.statements().add(ast.newReturnStatement()); rewrite.markAsInserted(body); tryStatement.setFinally(body); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo(int i) {\n"); buf.append(" try {\n"); buf.append(" } catch (IOException e) {\n"); buf.append(" } finally {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" try {\n"); buf.append(" } catch (Exception x) {\n"); buf.append(" }\n"); buf.append(" try {\n"); buf.append(" } finally {\n"); buf.append(" return;\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testTypeDeclarationStatement() 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(" class A {\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("Parse errors", (block.getFlags() & ASTNode.MALFORMED) == 0); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace expression TypeDeclarationStatement stmt= (TypeDeclarationStatement) statements.get(0); TypeDeclaration newDeclaration= ast.newTypeDeclaration(); newDeclaration.setName(ast.newSimpleName("X")); newDeclaration.setInterface(true); rewrite.markAsReplaced(stmt.getTypeDeclaration(), newDeclaration); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" interface X {\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testVariableDeclarationStatement() 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 void foo() {\n"); buf.append(" int i1= 1;\n"); buf.append(" int i2= 1, k2= 2, n2= 3;\n"); buf.append(" final int i3= 1, k3= 2, n3= 3;\n"); buf.append(" }\n"); buf.append("}\n"); ICompilationUnit cu= pack1.createCompilationUnit("A.java", buf.toString(), false, null); CompilationUnit astRoot= AST.parseCompilationUnit(cu, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "A"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); assertTrue("Parse errors", (block.getFlags() & ASTNode.MALFORMED) == 0); List statements= block.statements(); assertTrue("Number of statements not 3", statements.size() == 3); { // add modifier, change type, add fragment VariableDeclarationStatement decl= (VariableDeclarationStatement) statements.get(0); // add modifier VariableDeclarationStatement modifiedNode= ast.newVariableDeclarationStatement(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(Modifier.FINAL); rewrite.markAsModified(decl, modifiedNode); PrimitiveType newType= ast.newPrimitiveType(PrimitiveType.BOOLEAN); rewrite.markAsReplaced(decl.getType(), newType); List fragments= decl.fragments(); VariableDeclarationFragment frag= ast.newVariableDeclarationFragment(); frag.setName(ast.newSimpleName("k1")); frag.setInitializer(null); rewrite.markAsInserted(frag); fragments.add(frag); } { // add modifiers, remove first two fragments, replace last VariableDeclarationStatement decl= (VariableDeclarationStatement) statements.get(1); // add modifier VariableDeclarationStatement modifiedNode= ast.newVariableDeclarationStatement(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(Modifier.FINAL); rewrite.markAsModified(decl, modifiedNode); List fragments= decl.fragments(); assertTrue("Number of fragments not 3", fragments.size() == 3); rewrite.markAsRemoved((ASTNode) fragments.get(0)); rewrite.markAsRemoved((ASTNode) fragments.get(1)); VariableDeclarationFragment frag= ast.newVariableDeclarationFragment(); frag.setName(ast.newSimpleName("k2")); frag.setInitializer(null); rewrite.markAsReplaced((ASTNode) fragments.get(2), frag); } { // remove modifiers VariableDeclarationStatement decl= (VariableDeclarationStatement) statements.get(2); // add modifier VariableDeclarationStatement modifiedNode= ast.newVariableDeclarationStatement(ast.newVariableDeclarationFragment()); modifiedNode.setModifiers(0); rewrite.markAsModified(decl, modifiedNode); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class A {\n"); buf.append(" public void foo() {\n"); buf.append(" final boolean i1= 1, k1;\n"); buf.append(" final int k2;\n"); buf.append(" int i3= 1, k3= 2, n3= 3;\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testWhileStatement() 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(" while (i == j) {\n"); buf.append(" System.beep();\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace expression and body WhileStatement whileStatement= (WhileStatement) statements.get(0); BooleanLiteral literal= ast.newBooleanLiteral(true); rewrite.markAsReplaced(whileStatement.getExpression(), literal); Block newBody= ast.newBlock(); MethodInvocation invocation= ast.newMethodInvocation(); invocation.setName(ast.newSimpleName("hoo")); invocation.arguments().add(ast.newNumberLiteral("11")); newBody.statements().add(ast.newExpressionStatement(invocation)); rewrite.markAsReplaced(whileStatement.getBody(), newBody); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" while (true) {\n"); buf.append(" hoo(11);\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } public void testInsertCode() 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(" while (i == j) {\n"); buf.append(" System.beep();\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, false); ASTRewrite rewrite= new ASTRewrite(astRoot); AST ast= astRoot.getAST(); assertTrue("Parse errors", (astRoot.getFlags() & ASTNode.MALFORMED) == 0); TypeDeclaration type= findTypeDeclaration(astRoot, "E"); MethodDeclaration methodDecl= findMethodDeclaration(type, "foo"); Block block= methodDecl.getBody(); List statements= block.statements(); assertTrue("Number of statements not 1", statements.size() == 1); { // replace while statement with comment, insert new statement WhileStatement whileStatement= (WhileStatement) statements.get(0); String comment= "//hello"; ASTNode placeHolder= rewrite.createPlaceholder(comment, ASTRewrite.STATEMENT); rewrite.markAsReplaced(whileStatement, placeHolder); StringBuffer buf1= new StringBuffer(); buf1.append("if (i == 3) {\n"); buf1.append(" System.beep();\n"); buf1.append("}"); ASTNode placeHolder2= rewrite.createPlaceholder(buf1.toString(), ASTRewrite.STATEMENT); rewrite.markAsInserted(placeHolder2); statements.add(placeHolder2); } ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal("", cu, rewrite, 10, null); proposal.getCompilationUnitChange().setSave(true); proposal.apply(null); buf= new StringBuffer(); buf.append("package test1;\n"); buf.append("public class E {\n"); buf.append(" public void foo() {\n"); buf.append(" //hello\n"); buf.append(" if (i == 3) {\n"); buf.append(" System.beep();\n"); buf.append(" }\n"); buf.append(" }\n"); buf.append("}\n"); assertEqualString(cu.getSource(), buf.toString()); clearRewrite(rewrite); } }
15,726
Bug 15726 moves field comments from one field to another [quick fix]
20020508 public class A { int field; //field comment A(int fred){ _fred= fred; } } you are offered to create field _fred but then it steals the comment: int field; private int _fred; //field comment
resolved fixed
d8aa460
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T18:25:14Z
2002-05-10T14:13:20Z
org.eclipse.jdt.ui/core
15,726
Bug 15726 moves field comments from one field to another [quick fix]
20020508 public class A { int field; //field comment A(int fred){ _fred= fred; } } you are offered to create field _fred but then it steals the comment: int field; private int _fred; //field comment
resolved fixed
d8aa460
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-23T18:25:14Z
2002-05-10T14:13:20Z
extension/org/eclipse/jdt/internal/corext/dom/ASTRewriteAnalyzer.java
23,698
Bug 23698 Extract Interface: Interface name clash checking done on Next
As like the new class wizard does, Extract Interface should check the existence of an interface as you type and not wait until the user hits Next.
verified fixed
7bd9f07
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T09:06:13Z
2002-09-18T11:53:20Z
org.eclipse.jdt.ui/core
23,698
Bug 23698 Extract Interface: Interface name clash checking done on Next
As like the new class wizard does, Extract Interface should check the existence of an interface as you type and not wait until the user hits Next.
verified fixed
7bd9f07
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T09:06:13Z
2002-09-18T11:53:20Z
refactoring/org/eclipse/jdt/internal/corext/refactoring/structure/ExtractInterfaceRefactoring.java
23,699
Bug 23699 Extract Interface: Should work on member and local classes as well [refactoring]
Summary says it all :)
resolved fixed
302c3ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T09:50:36Z
2002-09-18T11:53:20Z
org.eclipse.jdt.ui.tests.refactoring/test
23,699
Bug 23699 Extract Interface: Should work on member and local classes as well [refactoring]
Summary says it all :)
resolved fixed
302c3ff
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T09:50:36Z
2002-09-18T11:53:20Z
cases/org/eclipse/jdt/ui/tests/refactoring/ExtractInterfaceTests.java
23,696
Bug 23696 Extract Interface: Distinction between overridden/implemented and new methods
If I have a toString() method in a class, I rarely want it to be part of the extracted interface. There should be some visual indication or the possibility to select only the newly declared methods in the class.
verified fixed
23d9457
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T10:22:20Z
2002-09-18T11:53:20Z
org.eclipse.jdt.ui/ui
23,696
Bug 23696 Extract Interface: Distinction between overridden/implemented and new methods
If I have a toString() method in a class, I rarely want it to be part of the extracted interface. There should be some visual indication or the possibility to select only the newly declared methods in the class.
verified fixed
23d9457
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T10:22:20Z
2002-09-18T11:53:20Z
refactoring/org/eclipse/jdt/internal/ui/refactoring/ExtractInterfaceInputPage.java
22,573
Bug 22573 Can't make OK to appear in type hierarchy history dialog [type hierarchy]
Build 20020813 1. Open Type Hierarchy (1st time). 2. Click on the history toolbar button 3. Press "Remove" on the dialog ==> no way to enable "OK" It would be better not to allow to remove the actual type hierarchy.
resolved fixed
ae47959
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T10:45:57Z
2002-08-20T13:26:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/HistoryListAction.java
package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.Arrays; import java.util.List; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.Action; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IListAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ListDialogField; public class HistoryListAction extends Action { private class HistoryListDialog extends StatusDialog { private ListDialogField fHistoryList; private IStatus fHistoryStatus; private IJavaElement fResult; private HistoryListDialog(Shell shell, IJavaElement[] elements) { super(shell); setTitle(TypeHierarchyMessages.getString("HistoryListDialog.title")); //$NON-NLS-1$ String[] buttonLabels= new String[] { /* 0 */ TypeHierarchyMessages.getString("HistoryListDialog.remove.button") //$NON-NLS-1$ }; IListAdapter adapter= new IListAdapter() { public void customButtonPressed(DialogField field, int index) { } public void selectionChanged(DialogField field) { doSelectionChanged(); } }; JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_QUALIFIED | JavaElementLabelProvider.SHOW_ROOT); fHistoryList= new ListDialogField(adapter, buttonLabels, labelProvider); fHistoryList.setLabelText(TypeHierarchyMessages.getString("HistoryListDialog.label")); //$NON-NLS-1$ fHistoryList.setRemoveButtonIndex(0); fHistoryList.setElements(Arrays.asList(elements)); ISelection sel; if (elements.length > 0) { sel= new StructuredSelection(elements[0]); } else { sel= new StructuredSelection(); } fHistoryList.selectElements(sel); } /* * @see Dialog#createDialogArea(Composite) */ protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); inner.setLayoutData(new GridData(GridData.FILL)); LayoutUtil.doDefaultLayout(inner, new DialogField[] { fHistoryList }, true, 0, 0); LayoutUtil.setHeigthHint(fHistoryList.getListControl(null), convertHeightInCharsToPixels(12)); LayoutUtil.setHorizontalGrabbing(fHistoryList.getListControl(null)); fHistoryList.getTableViewer().addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { if (fHistoryStatus.isOK()) { okPressed(); } } }); return composite; } private void doSelectionChanged() { StatusInfo status= new StatusInfo(); List selected= fHistoryList.getSelectedElements(); if (selected.size() != 1) { status.setError(""); //$NON-NLS-1$ fResult= null; } else { fResult= (IJavaElement) selected.get(0); } fHistoryStatus= status; updateStatus(status); } public IJavaElement getResult() { return fResult; } public IJavaElement[] getRemaining() { List elems= fHistoryList.getElements(); return (IJavaElement[]) elems.toArray(new IJavaElement[elems.size()]); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.HISTORY_LIST_DIALOG); } } private TypeHierarchyViewPart fView; public HistoryListAction(TypeHierarchyViewPart view) { fView= view; setText(TypeHierarchyMessages.getString("HistoryListAction.label")); //$NON-NLS-1$ JavaPluginImages.setLocalImageDescriptors(this, "history_list.gif"); //$NON-NLS-1$ WorkbenchHelp.setHelp(this, IJavaHelpContextIds.HISTORY_LIST_ACTION); } /* * @see IAction#run() */ public void run() { IJavaElement[] historyEntries= fView.getHistoryEntries(); HistoryListDialog dialog= new HistoryListDialog(JavaPlugin.getActiveWorkbenchShell(), historyEntries); if (dialog.open() == dialog.OK) { fView.setHistoryEntries(dialog.getRemaining()); fView.setInputElement(dialog.getResult()); } } }
22,551
Bug 22551 Hierarchy pane missing "New..." menu item in context menu [type hierarchy]
(R2.0) I can almost use Eclipse like a Smalltalk Class Hierarchy browser. This is one of two problems. My custom perspective has a Packages pane, a Hierarchy pane (which includes methods of course) and a code editor pane. I cannot create a new class that is a subclass of the selected class in the Hierarchy pane. Note that I can do this in the "Types" pane from the context menu. The workaround is to use the Packages context menu, but this does NOT pick up the superclass that I have selected in the Hierarchy pane.
resolved fixed
f7476cf
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T12:32:31Z
2002-08-19T23:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/actions/NewWizardsActionGroup.java
22,551
Bug 22551 Hierarchy pane missing "New..." menu item in context menu [type hierarchy]
(R2.0) I can almost use Eclipse like a Smalltalk Class Hierarchy browser. This is one of two problems. My custom perspective has a Packages pane, a Hierarchy pane (which includes methods of course) and a code editor pane. I cannot create a new class that is a subclass of the selected class in the Hierarchy pane. Note that I can do this in the "Types" pane from the context menu. The workaround is to use the Packages context menu, but this does NOT pick up the superclass that I have selected in the Hierarchy pane.
resolved fixed
f7476cf
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T12:32:31Z
2002-08-19T23:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPartListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetManager; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.NewWizardMenu; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.search.ui.ISearchResultView; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.ui.actions.BuildActionGroup; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.ImportActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.packageview.PackagesMessages; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.search.SearchUtil; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup; abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener, IViewPartInputProvider { private static final String TAG_SELECTED_ELEMENTS= "selectedElements"; //$NON-NLS-1$ private static final String TAG_SELECTED_ELEMENT= "selectedElement"; //$NON-NLS-1$ private static final String TAG_SELECTED_ELEMENT_PATH= "selectedElementPath"; //$NON-NLS-1$ private ILabelProvider fLabelProvider; private ILabelProvider fTitleProvider; private StructuredViewer fViewer; private IMemento fMemento; private JavaElementTypeComparator fTypeComparator; // Actions private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup; private boolean fHasWorkingSetFilter= true; private boolean fHasCustomFilter= true; private OpenEditorActionGroup fOpenEditorGroup; private CCPActionGroup fCCPActionGroup; private BuildActionGroup fBuildActionGroup; protected CompositeActionGroup fActionGroups; // Filters private CustomFiltersActionGroup fCustomFiltersActionGroup; private Menu fContextMenu; private IWorkbenchPart fPreviousSelectionProvider; private Object fPreviousSelectedElement; /* * Ensure selection changed events being processed only if * initiated by user interaction with this part. */ private boolean fProcessSelectionEvents= true; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partBroughtToTop(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; /* * Implements method from IViewPart. */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup.saveState(memento); if (fHasCustomFilter) fCustomFiltersActionGroup.saveState(memento); saveSelectionState(memento); } private void saveSelectionState(IMemento memento) { Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); if (elements.length > 0) { IMemento selectionMem= memento.createChild(TAG_SELECTED_ELEMENTS); for (int i= 0; i < elements.length; i++) { IMemento elementMem= selectionMem.createChild(TAG_SELECTED_ELEMENT); // we can only persist JavaElements for now Object o= elements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_SELECTED_ELEMENT_PATH, ((IJavaElement) elements[i]).getHandleIdentifier()); } } } protected void restoreState(IMemento memento) { if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup.restoreState(memento); if (fHasCustomFilter) fCustomFiltersActionGroup.restoreState(memento); if (fHasCustomFilter || fHasWorkingSetFilter) { fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } // restoreSelectionState(memento); } private ISelection restoreSelectionState(IMemento memento) { if (memento == null) return null; IMemento childMem; childMem= memento.getChild(TAG_SELECTED_ELEMENTS); if (childMem != null) { ArrayList list= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_SELECTED_ELEMENT); for (int i= 0; i < elementMem.length; i++) { IJavaElement element= JavaCore.create(elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH)); if (element != null && element.exists()) list.add(element); } return new StructuredSelection(list); } return null; } /** * Creates the search list inner viewer. */ public void createPartControl(Composite parent) { Assert.isTrue(fViewer == null); fTypeComparator= new JavaElementTypeComparator(); // Setup viewer fViewer= createViewer(parent); fLabelProvider= createLabelProvider(); ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(); fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr)); fViewer.setSorter(new JavaElementSorter()); fViewer.setUseHashlookup(true); fTitleProvider= createTitleProvider(); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getControl()); fViewer.getControl().setMenu(fContextMenu); getSite().registerContextMenu(menuMgr, fViewer); getSite().setSelectionProvider(fViewer); createActions(); // call before registering for selection changes addKeyListener(); // Custom filter group if (fHasCustomFilter) fCustomFiltersActionGroup= new CustomFiltersActionGroup(this, fViewer); if (fMemento != null) restoreState(fMemento); getSite().setSelectionProvider(fViewer); // Status line IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); hookViewerListeners(); // Filters addFilters(); // Initialize viewer input fViewer.setContentProvider(createContentProvider()); setInitialInput(); initDragAndDrop(); // Initialize selecton setInitialSelection(); fMemento= null; // Listen to workbench window changes getViewSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(this); getViewSite().getPage().addPartListener(fPartListener); fillActionBars(getViewSite().getActionBars()); setHelp(); } private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance()}; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fViewer), new ResourceTransferDragAdapter(fViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners) { public void dragStart(DragSourceEvent event) { IStructuredSelection selection= (IStructuredSelection)getSelectionProvider().getSelection(); for (Iterator iter= selection.iterator(); iter.hasNext(); ) { if (iter.next() instanceof IMember) { setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)}); break; } } super.dragStart(event); } }); } protected void fillActionBars(IActionBars actionBars) { IToolBarManager toolBar= actionBars.getToolBarManager(); fillToolBar(toolBar); if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars()); actionBars.updateActionBars(); fActionGroups.fillActionBars(actionBars); if (fHasCustomFilter) fCustomFiltersActionGroup.fillActionBars(actionBars); } //---- IWorkbenchPart ------------------------------------------------------ public void setFocus() { fViewer.getControl().setFocus(); } public void dispose() { if (fViewer != null) { getViewSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this); getViewSite().getPage().removePartListener(fPartListener); fViewer= null; } if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } /** * Adds the KeyListener */ protected void addKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { handleKeyReleased(event); } }); } protected void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; int key= event.keyCode; IAction action; if (key == SWT.F5) { action= fBuildActionGroup.getRefreshAction(); if (action.isEnabled()) action.run(); } if (event.character == SWT.DEL) { action= fCCPActionGroup.getDeleteAction(); if (action.isEnabled()) action.run(); } } //---- Adding Action to Toolbar ------------------------------------------- protected void fillToolBar(IToolBarManager tbm) { } /** * Called when the context menu is about to open. * Override to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); int size= selection.size(); Object element= selection.getFirstElement(); IJavaElement jElement= element instanceof IJavaElement ? (IJavaElement)element : null; if (size == 0 || (size == 1 && (isNewTarget(jElement) || element instanceof IContainer))) { MenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu); new NewWizardMenu(newMenu, getSite().getWorkbenchWindow(), false); } if (size == 1) addOpenNewWindowAction(menu, element); fActionGroups.setContext(new ActionContext(selection)); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } private boolean isNewTarget(IJavaElement element) { if (element == null) return false; int type= element.getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.COMPILATION_UNIT || type == IJavaElement.TYPE; } private void addOpenNewWindowAction(IMenuManager menu, Object element) { if (element instanceof IJavaElement) { try { element= ((IJavaElement)element).getCorrespondingResource(); } catch(JavaModelException e) { } } if (!(element instanceof IContainer)) return; menu.appendToGroup( IContextMenuConstants.GROUP_OPEN, new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element)); } protected void createActions() { fActionGroups= new CompositeActionGroup(new ActionGroup[] { fOpenEditorGroup= new OpenEditorActionGroup(this), new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new ImportActionGroup(this), new GenerateActionGroup(this), fBuildActionGroup= new BuildActionGroup(this), new JavaSearchActionGroup(this)}); String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$ Assert.isNotNull(viewId); IPropertyChangeListener titleUpdater= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) updateTitle(); } }; if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(fViewer, viewId, getShell(), titleUpdater); } /** * Returns the shell to use for opening dialogs. * Used in this class, and in the actions. */ private Shell getShell() { return fViewer.getControl().getShell(); } protected final Display getDisplay() { return fViewer.getControl().getDisplay(); } /** * Returns the selection provider. */ ISelectionProvider getSelectionProvider() { return fViewer; } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ abstract protected boolean isValidInput(Object element); /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element == null) return false; element= getSuitableJavaElement(element); if (element == null) return false; Object input= getViewer().getInput(); if (input == null) return false; if (input instanceof Collection) return ((Collection)input).contains(element); else return input.equals(element); } private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) { if (newInput == null) return part == fPreviousSelectionProvider; if (input instanceof IJavaElement && newInput instanceof IJavaElement) return getTypeComparator().compare(newInput, input) > 0; else return false; } private boolean isInputResetBy(IWorkbenchPart part) { if (!(part instanceof JavaBrowsingPart)) return true; Object thisInput= getViewer().getInput(); Object partInput= ((JavaBrowsingPart)part).getViewer().getInput(); if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement) return getTypeComparator().compare(partInput, thisInput) > 0; else return true; } protected boolean isAncestorOf(Object ancestor, Object element) { if (element instanceof IJavaElement && ancestor instanceof IJavaElement) return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element); return false; } private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) { if (element != null) return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent()); else return false; } public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!fProcessSelectionEvents || part == this || (part instanceof ISearchResultView) || !(selection instanceof IStructuredSelection)) return; // Set selection Object selectedElement= getSingleElementFromSelection(selection); if (selectedElement != null && part.equals(fPreviousSelectionProvider) && selectedElement.equals(fPreviousSelectedElement)) return; fPreviousSelectedElement= selectedElement; Object currentInput= (IJavaElement)getViewer().getInput(); if (selectedElement != null && selectedElement.equals(currentInput)) { IJavaElement elementToSelect= findElementToSelect(selectedElement); if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0) setSelection(new StructuredSelection(elementToSelect), true); else if (elementToSelect == null && (this instanceof MembersView)) { setSelection(StructuredSelection.EMPTY, true); fPreviousSelectedElement= StructuredSelection.EMPTY; } fPreviousSelectionProvider= part; return; } // Clear input if needed if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) { if (!isAncestorOf(selectedElement, currentInput)) setInput(null); fPreviousSelectionProvider= part; return; } else if (selection.isEmpty() && !isInputResetBy(part)) { fPreviousSelectionProvider= part; return; } else if (selectedElement == null && part == fPreviousSelectionProvider) { setInput(null); fPreviousSelectionProvider= part; return; } fPreviousSelectionProvider= part; // Adjust input and set selection and if (selectedElement instanceof IJavaElement) adjustInputAndSetSelection((IJavaElement)selectedElement); else setSelection(StructuredSelection.EMPTY, true); } void setHasWorkingSetFilter(boolean state) { fHasWorkingSetFilter= state; } void setHasCustomSetFilter(boolean state) { fHasCustomFilter= state; } protected void setInput(Object input) { setViewerInput(input); updateTitle(); } private void setViewerInput(Object input) { fProcessSelectionEvents= false; fViewer.setInput(input); fProcessSelectionEvents= true; } void updateTitle() { setTitleToolTip(getToolTipText(fViewer.getInput())); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null) return result; IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet(); String wsstr= JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$ if (result.length() == 0) return wsstr; return JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$ } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } protected final StructuredViewer getViewer() { return fViewer; } protected ILabelProvider createLabelProvider() { return new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, AppearanceAwareLabelProvider.getDecorators(true, null) ); } protected ILabelProvider createTitleProvider() { return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS); } protected final ILabelProvider getLabelProvider() { return fLabelProvider; } protected final ILabelProvider getTitleProvider() { return fTitleProvider; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI); } protected int getLabelProviderFlags() { return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS; } /** * Adds filters the viewer of this part. */ protected void addFilters() { // default is to have no filters } /** * Creates the the content provider of this part. */ protected IContentProvider createContentProvider() { return new JavaBrowsingContentProvider(true, this); } protected void setInitialInput() { // Use the selection, if any ISelection selection= getSite().getPage().getSelection(); Object input= getSingleElementFromSelection(selection); if (!(input instanceof IJavaElement)) { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); } setInput(findInputForJavaElement((IJavaElement)input)); } protected void setInitialSelection() { // Use the selection, if any Object input; IWorkbenchPage page= getSite().getPage(); ISelection selection= null; if (page != null) selection= page.getSelection(); if (selection instanceof ITextSelection) { Object part= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); if (part instanceof IEditorPart) { setSelectionFromEditor((IEditorPart)part); if (fViewer.getSelection() != null) return; } } // Use saved selection from memento if (selection == null || selection.isEmpty()) selection= restoreSelectionState(fMemento); if (selection != null && !selection.isEmpty()) input= getSingleElementFromSelection(selection); else { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement)) { if (input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); else return; } } if (findElementToSelect((IJavaElement)input) != null) adjustInputAndSetSelection((IJavaElement)input); } final protected void setHelp() { JavaUIHelp.setHelp(fViewer, getHelpContextId()); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ abstract protected String getHelpContextId(); /** * Adds additional listeners to this view. * This method can be overridden but should * call super. */ protected void hookViewerListeners() { fViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!fProcessSelectionEvents) return; fPreviousSelectedElement= getSingleElementFromSelection(event.getSelection()); IWorkbenchPage page= getSite().getPage(); if (page == null) return; if (page.equals(JavaPlugin.getActivePage()) && JavaBrowsingPart.this.equals(page.getActivePart())) { linkToEditor((IStructuredSelection)event.getSelection()); } } }); fViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { IAction open= fOpenEditorGroup.getOpenAction(); if (open.isEnabled()) { open.run(); restoreSelection(); } } }); } void restoreSelection() { // Default is to do nothing } void adjustInputAndSetSelection(IJavaElement je) { IJavaElement elementToSelect= getSuitableJavaElement(findElementToSelect(je)); IJavaElement newInput= findInputForJavaElement(je); if (elementToSelect == null && !isValidInput(newInput)) // Clear input setInput(null); else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) { // Adjust input to selection setInput(newInput); // Recompute suitable element since it depends on the viewer's input elementToSelect= getSuitableJavaElement(elementToSelect); } if (elementToSelect != null && elementToSelect.exists()) setSelection(new StructuredSelection(elementToSelect), true); else setSelection(StructuredSelection.EMPTY, true); } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; if (isValidInput(je)) return je; return findInputForJavaElement(je.getParent()); } final protected IJavaElement findElementToSelect(Object obj) { if (obj instanceof IJavaElement) return findElementToSelect((IJavaElement)obj); return null; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ abstract protected IJavaElement findElementToSelect(IJavaElement je); protected final Object getSingleElementFromSelection(ISelection selection) { if (!(selection instanceof StructuredSelection) || selection.isEmpty()) return null; Iterator iter= ((StructuredSelection)selection).iterator(); Object firstElement= iter.next(); if (!(firstElement instanceof IJavaElement)) { if (firstElement instanceof ISearchResultViewEntry) { IJavaElement je= SearchUtil.getJavaElement((ISearchResultViewEntry)firstElement); if (je != null) return je; firstElement= ((ISearchResultViewEntry)firstElement).getResource(); } if (firstElement instanceof IAdaptable) { IJavaElement je= (IJavaElement)((IAdaptable)firstElement).getAdapter(IJavaElement.class); if (je == null && firstElement instanceof IFile) { IContainer parent= ((IFile)firstElement).getParent(); if (parent != null) return (IJavaElement)parent.getAdapter(IJavaElement.class); else return null; } else return je; } else return firstElement; } Object currentInput= (IJavaElement)getViewer().getInput(); if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement))) if (iter.hasNext()) // multi selection and view is empty return null; else // ok: single selection and view is empty return firstElement; // be nice to multi selection while (iter.hasNext()) { Object element= iter.next(); if (!(element instanceof IJavaElement)) return null; if (!currentInput.equals(findInputForJavaElement((IJavaElement)element))) return null; } return firstElement; } /** * Gets the typeComparator. * @return Returns a JavaElementTypeComparator */ protected Comparator getTypeComparator() { return fTypeComparator; } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { Object obj= selection.getFirstElement(); if (selection.size() == 1) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) obj); } } } void setSelectionFromEditor(IWorkbenchPart part) { if (!JavaBasePreferencePage.linkBrowsingViewSelectionToEditor()) return; if (part == null) return; IWorkbenchPartSite site= part.getSite(); if (site == null) return; ISelectionProvider provider= site.getSelectionProvider(); if (provider != null) setSelectionFromEditor(part, provider.getSelection()); } private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) { if (part instanceof IEditorPart) { IEditorInput ei= ((IEditorPart)part).getEditorInput(); if (selection instanceof ITextSelection) { int offset= ((ITextSelection)selection).getOffset(); IJavaElement element= getElementForInputAt(ei, offset); if (element != null) { adjustInputAndSetSelection(element); return; } } if (ei instanceof IFileEditorInput) { IFile file= ((IFileEditorInput)ei).getFile(); IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class); if (je == null) { IContainer container= ((IFileEditorInput)ei).getFile().getParent(); if (container != null) je= (IJavaElement)container.getAdapter(IJavaElement.class); } if (je == null) { setSelection(null, false); return; } adjustInputAndSetSelection(je); } else if (ei instanceof IClassFileEditorInput) { IClassFile cf= ((IClassFileEditorInput)ei).getClassFile(); adjustInputAndSetSelection(cf); } } } /** * Returns the element contained in the EditorInput */ Object getElementOfInput(IEditorInput input) { if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); else if (input instanceof IFileEditorInput) return ((IFileEditorInput)input).getFile(); else if (input instanceof JarEntryEditorInput) return ((JarEntryEditorInput)input).getStorage(); return null; } private IResource getResourceFor(Object element) { if (element instanceof IJavaElement) { if (element instanceof IWorkingCopy) { IWorkingCopy wc= (IWorkingCopy)element; IJavaElement original= wc.getOriginalElement(); if (original != null) element= original; } try { element= ((IJavaElement)element).getUnderlyingResource(); } catch (JavaModelException e) { return null; } } if (!(element instanceof IResource) || ((IResource)element).isPhantom()) { return null; } return (IResource)element; } private void setSelection(ISelection selection, boolean reveal) { if (selection != null && selection.equals(fViewer.getSelection())) return; fProcessSelectionEvents= false; fViewer.setSelection(selection, reveal); fProcessSelectionEvents= true; } /** * Tries to find the given element in a workingcopy. */ protected static IJavaElement getWorkingCopy(IJavaElement input) { try { if (input instanceof ICompilationUnit) return ((ICompilationUnit)input).findSharedWorkingCopy(JavaUI.getBufferFactory()); else return EditorUtility.getWorkingCopy(input, false); } catch (JavaModelException ex) { } return null; } /** * Returns the original element from which the specified working copy * element was created from. This is a handle only method, the * returned element may or may not exist. * * @param workingCopy the element for which to get the original * @return the original Java element or <code>null</code> if this is not a working copy element */ protected static IJavaElement getOriginal(IJavaElement workingCopy) { ICompilationUnit cu= getCompilationUnit(workingCopy); if (cu != null) return ((IWorkingCopy)cu).getOriginal(workingCopy); return null; } /** * Returns the compilation unit for the given java element. * * @param element the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ protected static ICompilationUnit getCompilationUnit(IJavaElement element) { if (element == null) return null; if (element instanceof IMember) return ((IMember) element).getCompilationUnit(); int type= element.getElementType(); if (IJavaElement.COMPILATION_UNIT == type) return (ICompilationUnit) element; if (IJavaElement.CLASS_FILE == type) return null; return getCompilationUnit(element.getParent()); } /** * Converts the given Java element to one which is suitable for this * view. It takes into account wether the view shows working copies or not. * * @param element the Java element to be converted * @return an element suitable for this view */ IJavaElement getSuitableJavaElement(Object obj) { if (!(obj instanceof IJavaElement)) return null; IJavaElement element= (IJavaElement)obj; if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0) return element; if (element.getElementType() == IJavaElement.CLASS_FILE) return element; if (isInputAWorkingCopy()) { IJavaElement wc= getWorkingCopy(element); if (wc != null) element= wc; return element; } else { ICompilationUnit cu= getCompilationUnit(element); if (cu != null && ((IWorkingCopy)cu).isWorkingCopy()) return ((IWorkingCopy)cu).getOriginal(element); else return element; } } boolean isInputAWorkingCopy() { return ((StandardJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy(); } /** * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementForInputAt(IEditorInput input, int offset) { if (input instanceof IClassFileEditorInput) { try { return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset); } catch (JavaModelException ex) { return null; } } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(input); if (unit != null) try { unit.reconcile(); return unit.getElementAt(offset); } catch (JavaModelException ex) { } return null; } protected IType getTypeForCU(ICompilationUnit cu) { cu= (ICompilationUnit)getSuitableJavaElement(cu); // Use primary type if possible IType primaryType= cu.findPrimaryType(); if (primaryType != null) return primaryType; // Use first top-level type try { IType[] types= cu.getTypes(); if (types.length > 0) return types[0]; else return null; } catch (JavaModelException ex) { return null; } } void setProcessSelectionEvents(boolean state) { fProcessSelectionEvents= state; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } }
22,551
Bug 22551 Hierarchy pane missing "New..." menu item in context menu [type hierarchy]
(R2.0) I can almost use Eclipse like a Smalltalk Class Hierarchy browser. This is one of two problems. My custom perspective has a Packages pane, a Hierarchy pane (which includes methods of course) and a code editor pane. I cannot create a new class that is a subclass of the selected class in the Hierarchy pane. Note that I can do this in the "Types" pane from the context menu. The workaround is to use the Packages context menu, but this does NOT pick up the superclass that I have selected in the Hierarchy pane.
resolved fixed
f7476cf
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T12:32:31Z
2002-08-19T23:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/packageview/PackageExplorerActionGroup.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.packageview; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IResource; import org.eclipse.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.MenuManager; 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.ActionGroup; import org.eclipse.ui.actions.MoveResourceAction; import org.eclipse.ui.actions.NewWizardMenu; import org.eclipse.ui.actions.OpenInNewWindowAction; import org.eclipse.ui.actions.RenameResourceAction; import org.eclipse.ui.views.framelist.BackAction; import org.eclipse.ui.views.framelist.ForwardAction; import org.eclipse.ui.views.framelist.FrameList; import org.eclipse.ui.views.framelist.GoIntoAction; import org.eclipse.ui.views.framelist.UpAction; 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.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.actions.BuildActionGroup; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.ImportActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.JdtActionConstants; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.ui.actions.NavigateActionGroup; import org.eclipse.jdt.ui.actions.ProjectActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.preferences.AppearancePreferencePage; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; 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 RenameResourceAction fRenameResourceAction; private MoveResourceAction fMoveResourceAction; private NavigateActionGroup fNavigateActionGroup; private BuildActionGroup fBuildActionGroup; private CCPActionGroup fCCPActionGroup; private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup; private MemberFilterActionGroup fMemberFilterActionGroup; private CustomFiltersActionGroup fCustomFiltersActionGroup; public PackageExplorerActionGroup(PackageExplorerPart part) { super(); fPart= part; IWorkbenchPartSite site = fPart.getSite(); Shell shell= site.getShell(); ISelectionProvider provider= site.getSelectionProvider(); IStructuredSelection selection= (IStructuredSelection) provider.getSelection(); setGroups(new ActionGroup[] { fNavigateActionGroup= new NavigateActionGroup(fPart), new ShowActionGroup(fPart), fCCPActionGroup= new CCPActionGroup(fPart), new RefactorActionGroup(fPart), new ImportActionGroup(fPart), new GenerateActionGroup(fPart), fBuildActionGroup= new BuildActionGroup(fPart), new JavaSearchActionGroup(fPart), new ProjectActionGroup(fPart), fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(part.getViewer(), JavaUI.ID_PACKAGES, shell, createTitleUpdater())}); 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); fMemberFilterActionGroup= new MemberFilterActionGroup(fPart.getViewer(), "PackageView"); //$NON-NLS-1$ fCustomFiltersActionGroup= new CustomFiltersActionGroup(fPart, fPart.getViewer()); provider.addSelectionChangedListener(this); update(selection); } 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) { actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, fRenameResourceAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, fMoveResourceAction); } else { actionBars.setGlobalActionHandler(IWorkbenchActionConstants.RENAME, null); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.MOVE, null); } actionBars.updateActionBars(); } //---- Persistent state ----------------------------------------------------------------------- /* package */ void restoreState(IMemento memento) { fMemberFilterActionGroup.restoreState(memento); fWorkingSetFilterActionGroup.restoreState(memento); fCustomFiltersActionGroup.restoreState(memento); fPart.getViewer().getControl().setRedraw(false); fPart.getViewer().refresh(); fPart.getViewer().getControl().setRedraw(true); } /* package */ void saveState(IMemento memento) { fMemberFilterActionGroup.saveState(memento); fWorkingSetFilterActionGroup.saveState(memento); fCustomFiltersActionGroup.saveState(memento); } //---- Action Bars ---------------------------------------------------------------------------- public void fillActionBars(IActionBars actionBars) { super.fillActionBars(actionBars); setGlobalActionHandlers(actionBars); fillToolBar(actionBars.getToolBarManager()); fillViewMenu(actionBars.getMenuManager()); fCustomFiltersActionGroup.fillActionBars(actionBars); } private void setGlobalActionHandlers(IActionBars actionBars) { // Navigate Go Into and Go To actions. actionBars.setGlobalActionHandler(IWorkbenchActionConstants.GO_INTO, fZoomInAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.BACK, fBackAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.FORWARD, fForwardAction); actionBars.setGlobalActionHandler(IWorkbenchActionConstants.UP, fUpAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_TYPE, fGotoTypeAction); actionBars.setGlobalActionHandler(JdtActionConstants.GOTO_PACKAGE, fGotoPackageAction); } /* package */ void fillToolBar(IToolBarManager toolBar) { toolBar.removeAll(); toolBar.add(fBackAction); toolBar.add(fForwardAction); toolBar.add(fUpAction); if (AppearancePreferencePage.showCompilationUnitChildren()) { toolBar.add(new Separator()); fMemberFilterActionGroup.contributeToToolBar(toolBar); } } /* package */ void fillViewMenu(IMenuManager menu) { menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); menu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS+"-end"));//$NON-NLS-1$ } /* package */ void handleSelectionChanged(SelectionChangedEvent event) { fZoomInAction.update(); } //---- Context menu ------------------------------------------------------------------------- public void fillContextMenu(IMenuManager menu) { IStructuredSelection selection= (IStructuredSelection)getContext().getSelection(); int size= selection.size(); Object element= selection.getFirstElement(); IJavaElement jElement= element instanceof IJavaElement ? (IJavaElement)element : null; if (size == 0 || (size == 1 && (isNewTarget(jElement) || element instanceof IContainer))) { IMenuManager newMenu= new MenuManager(PackagesMessages.getString("PackageExplorer.new")); //$NON-NLS-1$ menu.appendToGroup(IContextMenuConstants.GROUP_NEW, newMenu); new NewWizardMenu(newMenu, fPart.getSite().getWorkbenchWindow(), false); } addGotoMenu(menu, element, size); addOpenNewWindowAction(menu, element); super.fillContextMenu(menu); } private void addGotoMenu(IMenuManager menu, Object element, int size) { if (size == 1 && fPart.getViewer().isExpandable(element) && (isGoIntoTarget(element) || element instanceof IContainer)) menu.appendToGroup(IContextMenuConstants.GROUP_GOTO, fZoomInAction); } private boolean isNewTarget(IJavaElement element) { if (element == null) return false; int type= element.getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.COMPILATION_UNIT || type == IJavaElement.TYPE; } 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) { try { element= ((IJavaElement)element).getCorrespondingResource(); } catch(JavaModelException e) { } } 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 (JavaBasePreferencePage.doubleClickGoesInto()) { // don't zoom into compilation units and class files if (element instanceof IOpenable && !(element instanceof ICompilationUnit) && !(element instanceof IClassFile)) { fZoomInAction.run(); } } else { if (element instanceof ICompilationUnit && OpenStrategy.getOpenMethod() == OpenStrategy.DOUBLE_CLICK) return; viewer.setExpandedState(element, !viewer.getExpandedState(element)); } } } /* package */ void handleOpen(OpenEvent event) { IAction openAction= fNavigateActionGroup.getOpenAction(); if (openAction != null && openAction.isEnabled()) { openAction.run(); return; } } /* package */ void handleKeyEvent(KeyEvent event) { if (event.stateMask != 0) return; if (event.keyCode == SWT.F5) { IAction refreshAction= fBuildActionGroup.getRefreshAction(); if (refreshAction != null && refreshAction.isEnabled()) refreshAction.run(); } else if (event.character == SWT.DEL) { IAction delete= fCCPActionGroup.getDeleteAction(); if (delete != null && delete.isEnabled()) delete.run(); } } private IPropertyChangeListener createTitleUpdater() { return new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) { IWorkingSet workingSet= (IWorkingSet)event.getNewValue(); String workingSetName= null; if (workingSet != null) workingSetName= workingSet.getName(); fPart.setWorkingSetName(workingSetName); fPart.updateTitle(); } } }; } }
22,551
Bug 22551 Hierarchy pane missing "New..." menu item in context menu [type hierarchy]
(R2.0) I can almost use Eclipse like a Smalltalk Class Hierarchy browser. This is one of two problems. My custom perspective has a Packages pane, a Hierarchy pane (which includes methods of course) and a code editor pane. I cannot create a new class that is a subclass of the selected class in the Hierarchy pane. Note that I can do this in the "Types" pane from the context menu. The workaround is to use the Packages context menu, but this does NOT pick up the superclass that I have selected in the Hierarchy pane.
resolved fixed
f7476cf
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T12:32:31Z
2002-08-19T23:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/typehierarchy/TypeHierarchyViewPart.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.typehierarchy; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; 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.DragSource; 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.IPartListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchActionConstants; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.PartInitException; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.actions.OpenWithMenu; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.part.PageBook; 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.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.ui.actions.ShowActionGroup; 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.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.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.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.preferences.MembersOrderPreferencePage; import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.JavaUILabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; /** * view showing the supertypes/subtypes of its input. */ public class TypeHierarchyViewPart extends ViewPart implements ITypeHierarchyViewPart, IViewPartInputProvider { public static final int VIEW_ID_TYPE= 2; public static final int VIEW_ID_SUPER= 0; public static final int VIEW_ID_SUB= 1; public static final int VIEW_ORIENTATION_VERTICAL= 0; public static final int VIEW_ORIENTATION_HORIZONTAL= 1; public static final int VIEW_ORIENTATION_SINGLE= 2; private static final String DIALOGSTORE_HIERARCHYVIEW= "TypeHierarchyViewPart.hierarchyview"; //$NON-NLS-1$ private static final String DIALOGSTORE_VIEWORIENTATION= "TypeHierarchyViewPart.orientation"; //$NON-NLS-1$ private static final String TAG_INPUT= "input"; //$NON-NLS-1$ private static final String TAG_VIEW= "view"; //$NON-NLS-1$ private static final String TAG_ORIENTATION= "orientation"; //$NON-NLS-1$ private static final String TAG_RATIO= "ratio"; //$NON-NLS-1$ private static final String TAG_SELECTION= "selection"; //$NON-NLS-1$ private static final String TAG_VERTICAL_SCROLL= "vertical_scroll"; //$NON-NLS-1$ private static final String GROUP_FOCUS= "group.focus"; //$NON-NLS-1$ // the selected type in the hierarchy view private IType fSelectedType; // input element or null private IJavaElement fInputElement; // history of inut elements. No duplicates private ArrayList fInputHistory; private IMemento fMemento; private TypeHierarchyLifeCycle fHierarchyLifeCycle; private ITypeHierarchyLifeCycleListener fTypeHierarchyLifeCycleListener; private IPropertyChangeListener fPropertyChangeListener; private MethodsViewer fMethodsViewer; private int fCurrentViewerIndex; private TypeHierarchyViewer[] fAllViewers; private SelectionProviderMediator fSelectionProviderMediator; private ISelectionChangedListener fSelectionChangedListener; private boolean fIsEnableMemberFilter; 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 IDialogSettings fDialogSettings; private ToggleViewAction[] fViewActions; private HistoryDropDownAction fHistoryDropDownAction; private ToggleOrientationAction[] fToggleOrientationActions; private int fCurrentOrientation; private EnableMemberFilterAction fEnableMemberFilterAction; private AddMethodStubAction fAddStubAction; private FocusOnTypeAction fFocusOnTypeAction; private FocusOnSelectionAction fFocusOnSelectionAction; private IPartListener fPartListener; private CompositeActionGroup fActionGroups; private CCPActionGroup fCCPActionGroup; public TypeHierarchyViewPart() { fSelectedType= null; fInputElement= null; fHierarchyLifeCycle= new TypeHierarchyLifeCycle(); fHierarchyLifeCycle.setReconciled(JavaBasePreferencePage.reconcileJavaViews()); 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); } }; JavaPlugin.getDefault().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); fFocusOnTypeAction= new FocusOnTypeAction(this); fPaneLabelProvider= new JavaUILabelProvider(); fAddStubAction= new AddMethodStubAction(); fFocusOnSelectionAction= new FocusOnSelectionAction(this); fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { if (part instanceof IEditorPart) editorActivated((IEditorPart) part); } public void partBroughtToTop(IWorkbenchPart part) {} public void partClosed(IWorkbenchPart part) {} public void partDeactivated(IWorkbenchPart part) {} public void partOpened(IWorkbenchPart part) {} }; fSelectionChangedListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(event); } }; } /** * Method doPropertyChange. * @param event */ private void doPropertyChange(PropertyChangeEvent event) { if (fMethodsViewer != null) { if (MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION.equals(event.getProperty())) { fMethodsViewer.refresh(); } } } /** * Adds the entry if new. Inserted at the beginning of the history entries list. */ private void addHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { fInputHistory.remove(entry); } fInputHistory.add(0, entry); fHistoryDropDownAction.setEnabled(true); } private void updateHistoryEntries() { for (int i= fInputHistory.size() - 1; i >= 0; i--) { IJavaElement type= (IJavaElement) fInputHistory.get(i); if (!type.exists()) { fInputHistory.remove(i); } } fHistoryDropDownAction.setEnabled(!fInputHistory.isEmpty()); } /** * Goes to the selected entry, without updating the order of history entries. */ public void gotoHistoryEntry(IJavaElement entry) { if (fInputHistory.contains(entry)) { updateInput(entry); } } /** * Gets all history entries. */ public IJavaElement[] getHistoryEntries() { if (fInputHistory.size() > 0) { updateHistoryEntries(); } return (IJavaElement[]) fInputHistory.toArray(new IJavaElement[fInputHistory.size()]); } /** * Sets the history entries */ public void setHistoryEntries(IJavaElement[] elems) { fInputHistory.clear(); for (int i= 0; i < elems.length; i++) { fInputHistory.add(elems[i]); } updateHistoryEntries(); } /** * Selects an member in the methods list or in the current hierarchy. */ public void selectMember(IMember member) { ICompilationUnit cu= member.getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { member= (IMember) cu.getOriginal(member); if (member == null) { return; } } if (member.getElementType() != IJavaElement.TYPE) { if (fHierarchyLifeCycle.isReconciled() && cu != null) { try { member= (IMember) EditorUtility.getWorkingCopy(member); if (member == null) { return; } } catch (JavaModelException e) { JavaPlugin.log(e); return; } } 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(); } 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(); } ICompilationUnit cu= ((IMember) element).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { element= cu.getOriginal(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; fInputElement= inputElement; if (fInputElement == null) { clearInput(); } else { try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e); clearInput(); return; } fPagebook.showPage(fTypeMethodsSplitter); if (inputElement.getElementType() != IJavaElement.TYPE) { setView(VIEW_ID_TYPE); } // turn off member filtering setMemberFilter(null); fIsEnableMemberFilter= false; if (!fInputElement.equals(prevInput)) { updateHierarchyViewer(); } IType root= getSelectableType(fInputElement); internalSelectType(root, true); updateMethodViewer(root); updateToolbarButtons(); updateTitle(); enableMemberFilter(false); } } private void clearInput() { fInputElement= null; fHierarchyLifeCycle.freeHierarchy(); updateHierarchyViewer(); updateToolbarButtons(); } /* * @see IWorbenchPart#setFocus */ public void setFocus() { fPagebook.setFocus(); } /* * @see IWorkbenchPart#dispose */ public void dispose() { fHierarchyLifeCycle.freeHierarchy(); fHierarchyLifeCycle.removeChangedListener(fTypeHierarchyLifeCycleListener); fPaneLabelProvider.dispose(); if (fPropertyChangeListener != null) { JavaPlugin.getDefault().getPreferenceStore().removePropertyChangeListener(fPropertyChangeListener); fPropertyChangeListener= null; } getSite().getPage().removePartListener(fPartListener); if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } private Control createTypeViewerControl(Composite parent) { fViewerbook= new PageBook(parent, SWT.NULL); KeyListener keyListener= createKeyListener(); // Create the viewers TypeHierarchyViewer superTypesViewer= new SuperTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(superTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUPERTYPES_VIEW); TypeHierarchyViewer subTypesViewer= new SubTypeHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(subTypesViewer, keyListener, IContextMenuConstants.TARGET_ID_SUBTYPES_VIEW); TypeHierarchyViewer vajViewer= new TraditionalHierarchyViewer(fViewerbook, fHierarchyLifeCycle, this); initializeTypesViewer(vajViewer, keyListener, IContextMenuConstants.TARGET_ID_HIERARCHY_VIEW); fAllViewers= new TypeHierarchyViewer[3]; fAllViewers[VIEW_ID_SUPER]= superTypesViewer; fAllViewers[VIEW_ID_SUB]= subTypesViewer; fAllViewers[VIEW_ID_TYPE]= vajViewer; int currViewerIndex; try { currViewerIndex= fDialogSettings.getInt(DIALOGSTORE_HIERARCHYVIEW); if (currViewerIndex < 0 || currViewerIndex > 2) { currViewerIndex= VIEW_ID_TYPE; } } catch (NumberFormatException e) { currViewerIndex= VIEW_ID_TYPE; } fEmptyTypesViewer= new Label(fViewerbook, SWT.LEFT); for (int i= 0; i < fAllViewers.length; i++) { fAllViewers[i].setInput(fAllViewers[i]); } // force the update fCurrentViewerIndex= -1; setView(currViewerIndex); return fViewerbook; } private KeyListener createKeyListener() { return new KeyAdapter() { public void keyReleased(KeyEvent event) { if (event.stateMask == 0) { if (event.keyCode == SWT.F5) { updateHierarchyViewer(); return; } else if (event.character == SWT.DEL){ if (fCCPActionGroup.getDeleteAction().isEnabled()) fCCPActionGroup.getDeleteAction().run(); return; } } viewPartKeyShortcuts(event); } }; } 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.addSelectionChangedListener(fSelectionChangedListener); } 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.addSelectionChangedListener(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){ Control control= viewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(viewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners)); } private void viewPartKeyShortcuts(KeyEvent event) { if (event.stateMask == SWT.CTRL) { if (event.character == '1') { setView(VIEW_ID_TYPE); } else if (event.character == '2') { setView(VIEW_ID_SUPER); } else if (event.character == '3') { setView(VIEW_ID_SUB); } } } /** * Returns the inner component in a workbench part. * @see IWorkbenchPart#createPartControl */ public void createPartControl(Composite container) { fPagebook= new PageBook(container, SWT.NONE); // page 1 of pagebook (viewers) fTypeMethodsSplitter= new SashForm(fPagebook, SWT.VERTICAL); fTypeMethodsSplitter.setVisible(false); fTypeViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); Control typeViewerControl= createTypeViewerControl(fTypeViewerViewForm); fTypeViewerViewForm.setContent(typeViewerControl); fMethodViewerViewForm= new ViewForm(fTypeMethodsSplitter, SWT.NONE); fTypeMethodsSplitter.setWeights(new int[] {35, 65}); Control methodViewerPart= createMethodViewerControl(fMethodViewerViewForm); fMethodViewerViewForm.setContent(methodViewerPart); fMethodViewerPaneLabel= new CLabel(fMethodViewerViewForm, SWT.NONE); fMethodViewerViewForm.setTopLeft(fMethodViewerPaneLabel); ToolBar methodViewerToolBar= new ToolBar(fMethodViewerViewForm, SWT.FLAT | SWT.WRAP); fMethodViewerViewForm.setTopCenter(methodViewerToolBar); // page 2 of pagebook (no hierarchy label) fNoHierarchyShownLabel= new Label(fPagebook, SWT.TOP + SWT.LEFT + SWT.WRAP); fNoHierarchyShownLabel.setText(TypeHierarchyMessages.getString("TypeHierarchyViewPart.empty")); //$NON-NLS-1$ 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); // set the filter menu items IActionBars actionBars= getViewSite().getActionBars(); IMenuManager viewMenu= actionBars.getMenuManager(); for (int i= 0; i < fToggleOrientationActions.length; i++) { viewMenu.add(fToggleOrientationActions[i]); } viewMenu.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS)); // 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); IJavaElement input= 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 OpenEditorActionGroup(this), new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new GenerateActionGroup(this), new JavaSearchActionGroup(this)}); fActionGroups.fillActionBars(getViewSite().getActionBars()); initDragAndDrop(); } /** * 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); // IStructuredSelection selection= (IStructuredSelection)viewer.getSelection(); // if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { // addOpenPerspectiveItem(menu, selection); // } // addOpenWithMenu(menu, selection); 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); // // ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, viewer); // // // XXX workaround until we have fully converted the code to use the new action groups // fActionGroups.get(2).fillContextMenu(menu); // fActionGroups.get(3).fillContextMenu(menu); // fActionGroups.get(4).fillContextMenu(menu); } /** * 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); // //menu.appendToGroup(IContextMenuConstants.GROUP_REORGANIZE, new JavaReplaceWithEditionAction(fMethodsViewer)); // addOpenWithMenu(menu, (IStructuredSelection)fMethodsViewer.getSelection()); // ContextMenuGroup.add(menu, new ContextMenuGroup[] { new BuildGroup(this, false)}, fMethodsViewer); // // // XXX workaround until we have fully converted the code to use the new action groups // fActionGroups.get(2).fillContextMenu(menu); // fActionGroups.get(3).fillContextMenu(menu); // fActionGroups.get(4).fillContextMenu(menu); } private void addOpenWithMenu(IMenuManager menu, IStructuredSelection selection) { // If one file is selected get it. // Otherwise, do not show the "open with" menu. if (selection.size() != 1) return; Object element= selection.getFirstElement(); if (!(element instanceof IJavaElement)) return; IResource resource= null; try { resource= ((IJavaElement)element).getUnderlyingResource(); } catch(JavaModelException e) { // ignore } if (!(resource instanceof IFile)) return; // Create a menu flyout. MenuManager submenu= new MenuManager(TypeHierarchyMessages.getString("TypeHierarchyViewPart.menu.open")); //$NON-NLS-1$ submenu.add(new OpenWithMenu(getSite().getPage(), (IFile) resource)); // Add the submenu. menu.appendToGroup(IContextMenuConstants.GROUP_OPEN, submenu); } /** * 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) { ISelection sel= null; 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.removeSelectionChangedListener(fSelectionChangedListener); viewer.setSelection(elem != null ? new StructuredSelection(elem) : StructuredSelection.EMPTY, reveal); viewer.addSelectionChangedListener(fSelectionChangedListener); } private void internalSelectMember(IMember member) { fMethodsViewer.removeSelectionChangedListener(fSelectionChangedListener); fMethodsViewer.setSelection(member != null ? new StructuredSelection(member) : StructuredSelection.EMPTY); fMethodsViewer.addSelectionChangedListener(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() { if (fInputElement == null) { fPagebook.showPage(fNoHierarchyShownLabel); } else { if (getCurrentViewer().containsElements() != null) { Runnable runnable= new Runnable() { public void run() { getCurrentViewer().updateContent(); // 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(IType input) { if (input != fMethodsViewer.getInput() && !fIsEnableMemberFilter && fCurrentOrientation != VIEW_ORIENTATION_SINGLE) { if (input != null) { fMethodViewerPaneLabel.setText(fPaneLabelProvider.getText(input)); fMethodViewerPaneLabel.setImage(fPaneLabelProvider.getImage(input)); } else { fMethodViewerPaneLabel.setText(""); //$NON-NLS-1$ fMethodViewerPaneLabel.setImage(null); } fMethodsViewer.setInput(input); } } private void doSelectionChanged(SelectionChangedEvent e) { if (e.getSelectionProvider() == fMethodsViewer) { methodSelectionChanged(e.getSelection()); } else { typeSelectionChanged(e.getSelection()); } } 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(); 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)) { try { getSite().getPage().removePartListener(fPartListener); EditorUtility.openInEditor(elem, false); EditorUtility.revealInEditor(editorPart, (IJavaElement) elem); getSite().getPage().addPartListener(fPartListener); } catch (CoreException e) { JavaPlugin.log(e); } } } 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(); 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(); 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 ITypeHierarchyLifeCycleListener. * Can be called from any thread */ private void doTypeHierarchyChanged(final TypeHierarchyLifeCycle typeHierarchy, final IType[] changedTypes) { Display display= getDisplay(); if (display != null) { display.asyncExec(new Runnable() { public void run() { if (fPagebook != null && !fPagebook.isDisposed()) { doTypeHierarchyChangedOnViewers(changedTypes); } } }); } } private void doTypeHierarchyChangedOnViewers(IType[] changedTypes) { if (fHierarchyLifeCycle.getHierarchy() == null || !fHierarchyLifeCycle.getHierarchy().exists()) { clearInput(); } else { if (changedTypes == null) { // hierarchy change try { fHierarchyLifeCycle.ensureRefreshedTypeHierarchy(fInputElement, new BusyIndicatorRunnableContext()); } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); clearInput(); return; } fMethodsViewer.refresh(); updateHierarchyViewer(); } else { // elements in hierarchy modified fMethodsViewer.refresh(); if (getCurrentViewer().isMethodFiltering()) { if (changedTypes.length == 1) { getCurrentViewer().refresh(changedTypes[0]); } else { updateHierarchyViewer(); } } else { getCurrentViewer().update(changedTypes, new String[] { IBasicPropertyConstants.P_TEXT, IBasicPropertyConstants.P_IMAGE } ); } } } } /** * Determines the input element to be used initially . */ private IJavaElement determineInputElement() { Object input= getSite().getPage().getInput(); if (input instanceof IJavaElement) { IJavaElement elem= (IJavaElement) input; if (elem instanceof IMember) { return elem; } else { int kind= elem.getElementType(); if (kind == IJavaElement.JAVA_PROJECT || kind == IJavaElement.PACKAGE_FRAGMENT_ROOT || kind == IJavaElement.PACKAGE_FRAGMENT) { return elem; } } } return null; } /* * @see IViewPart#init */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * @see ViewPart#saveState(IMemento) */ public void saveState(IMemento memento) { if (fPagebook == null) { // part has not been created if (fMemento != null) { //Keep the old state; memento.putMemento(fMemento); } return; } if (fInputElement != null) { String handleIndentifier= fInputElement.getHandleIdentifier(); if (fInputElement instanceof IType) { ITypeHierarchy hierarchy= fHierarchyLifeCycle.getHierarchy(); if (hierarchy != null && hierarchy.getSubtypes((IType) fInputElement).length > 1000) { // for startup performance reasons do not try to recover huge hierarchies handleIndentifier= null; } } memento.putString(TAG_INPUT, handleIndentifier); } memento.putInteger(TAG_VIEW, getViewIndex()); memento.putInteger(TAG_ORIENTATION, fCurrentOrientation); int weigths[]= fTypeMethodsSplitter.getWeights(); int ratio= (weigths[0] * 1000) / (weigths[0] + weigths[1]); memento.putInteger(TAG_RATIO, ratio); ScrollBar bar= getCurrentViewer().getTree().getVerticalBar(); int position= bar != null ? bar.getSelection() : 0; memento.putInteger(TAG_VERTICAL_SCROLL, position); IJavaElement selection= (IJavaElement)((IStructuredSelection) getCurrentViewer().getSelection()).getFirstElement(); if (selection != null) { memento.putString(TAG_SELECTION, selection.getHandleIdentifier()); } fMethodsViewer.saveState(memento); } /** * Restores the type hierarchy settings from a memento. */ private void restoreState(IMemento memento, IJavaElement defaultInput) { IJavaElement input= defaultInput; String elementId= memento.getString(TAG_INPUT); if (elementId != null) { input= JavaCore.create(elementId); if (input != null && !input.exists()) { input= null; } } 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); } /** * Link selection to active editor. */ private void editorActivated(IEditorPart editor) { if (!JavaBasePreferencePage.linkTypeHierarchySelectionToEditor()) { 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.getStatus()); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { return fInputElement; } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/BuildPathsPropertyPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation; import org.eclipse.ui.dialogs.PropertyPage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * Property page for configuring the Java build path */ public class BuildPathsPropertyPage extends PropertyPage implements IStatusChangeListener { private BuildPathsBlock fBuildPathsBlock; /* * @see PreferencePage#createControl(Composite) */ protected Control createContents(Composite parent) { WorkbenchHelp.setHelp(parent, IJavaHelpContextIds.BUILD_PATH_PROPERTY_PAGE); // ensure the page has no special buttons noDefaultAndApplyButton(); IProject project= getProject(); if (project == null || !isJavaProject(project)) { return createWithoutJava(parent); } else if (!project.isOpen()) { return createForClosedProject(parent); } else { return createWithJava(parent, project); } } /** * Content for valid projects. */ private Control createWithJava(Composite parent, IProject project) { IWorkspaceRoot root= JavaPlugin.getWorkspace().getRoot(); fBuildPathsBlock= new BuildPathsBlock(root, this, false); fBuildPathsBlock.init(JavaCore.create(project), null, null); return fBuildPathsBlock.createControl(parent); } /** * Content for non-Java projects. */ private Control createWithoutJava(Composite parent) { Label label= new Label(parent, SWT.LEFT); label.setText(JavaUIMessages.getString("BuildPathsPropertyPage.no_java_project.message")); //$NON-NLS-1$ fBuildPathsBlock= null; setValid(true); return label; } /** * Content for closed projects. */ private Control createForClosedProject(Composite parent) { Label label= new Label(parent, SWT.LEFT); label.setText(JavaUIMessages.getString("BuildPathsPropertyPage.closed_project.message")); //$NON-NLS-1$ fBuildPathsBlock= null; setValid(true); return label; } private IProject getProject() { IAdaptable adaptable= getElement(); if (adaptable != null) { IJavaElement elem= (IJavaElement) adaptable.getAdapter(IJavaElement.class); if (elem instanceof IJavaProject) { return ((IJavaProject) elem).getProject(); } } return null; } private boolean isJavaProject(IProject proj) { try { return proj.hasNature(JavaCore.NATURE_ID); } catch (CoreException e) { JavaPlugin.log(e); } return false; } /* * @see IPreferencePage#performOk */ public boolean performOk() { if (fBuildPathsBlock != null) { Shell shell= getControl().getShell(); IRunnableWithProgress runnable= new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { fBuildPathsBlock.configureJavaProject(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; IRunnableWithProgress op= new WorkspaceModifyDelegatingOperation(runnable); try { new ProgressMonitorDialog(shell).run(false, true, op); } catch (InvocationTargetException e) { String title= JavaUIMessages.getString("BuildPathsPropertyPage.error.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("BuildPathsPropertyPage.error.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, shell, title, message); return false; } catch (InterruptedException e) { // cancelled return false; } } return true; } /** * @see IStatusChangeListener#statusChanged */ public void statusChanged(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/ArchiveFileFilter.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.Arrays; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jdt.internal.ui.JavaPlugin; /** * Viewer filter for archive selection dialogs. * Archives are files with file extension 'jar' and 'zip'. * The filter is not case sensitive. */ public class ArchiveFileFilter extends ViewerFilter { private static final String[] fgArchiveExtensions= { "jar", "zip" }; //$NON-NLS-1$ //$NON-NLS-2$ private List fExcludes; /** * @param excludedFiles Excluded files will not pass the filter. * <code>null</code> is allowed if no files should be excluded. */ public ArchiveFileFilter(IFile[] excludedFiles) { if (excludedFiles != null) { fExcludes= Arrays.asList(excludedFiles); } else { fExcludes= null; } } /* * @see ViewerFilter#select */ public boolean select(Viewer viewer, Object parent, Object element) { if (element instanceof IFile) { if (fExcludes != null && fExcludes.contains(element)) { return false; } return isArchivePath(((IFile)element).getFullPath()); } else if (element instanceof IContainer) { // IProject, IFolder try { IResource[] resources= ((IContainer)element).members(); for (int i= 0; i < resources.length; i++) { // recursive! Only show containers that contain an archive if (select(viewer, parent, resources[i])) { return true; } } } catch (CoreException e) { JavaPlugin.log(e.getStatus()); } } return false; } public static boolean isArchivePath(IPath path) { String ext= path.getFileExtension(); if (ext != null && ext.length() != 0) { for (int i= 0; i < fgArchiveExtensions.length; i++) { if (ext.equalsIgnoreCase(fgArchiveExtensions[i])) { return true; } } } return false; } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/BuildPathsBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.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.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.ISelectionStatusValidator; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.corext.javadoc.JavaDocLocations; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.util.CoreUtility; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.viewsupport.ImageDisposer; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.CheckedListDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class BuildPathsBlock { public static interface IRemoveOldBinariesQuery { /** * Do the callback. Returns <code>true</code> if .class files should be removed from the * old output location. */ boolean doQuery(IPath oldOutputLocation) throws InterruptedException; } private IWorkspaceRoot fWorkspaceRoot; private CheckedListDialogField fClassPathList; private StringButtonDialogField fBuildPathDialogField; private StatusInfo fClassPathStatus; private StatusInfo fBuildPathStatus; private IJavaProject fCurrJProject; private IPath fOutputLocationPath; private IStatusChangeListener fContext; private Control fSWTWidget; private boolean fShowSourceFolderPage; private SourceContainerWorkbookPage fSourceContainerPage; private ProjectsWorkbookPage fProjectsPage; private LibrariesWorkbookPage fLibrariesPage; private BuildPathBasePage fCurrPage; public BuildPathsBlock(IWorkspaceRoot root, IStatusChangeListener context, boolean showSourceFolders) { fWorkspaceRoot= root; fContext= context; fShowSourceFolderPage= showSourceFolders; fSourceContainerPage= null; fLibrariesPage= null; fProjectsPage= null; fCurrPage= null; BuildPathAdapter adapter= new BuildPathAdapter(); String[] buttonLabels= new String[] { /* 0 */ NewWizardMessages.getString("BuildPathsBlock.classpath.up.button"), //$NON-NLS-1$ /* 1 */ NewWizardMessages.getString("BuildPathsBlock.classpath.down.button"), //$NON-NLS-1$ /* 2 */ null, /* 3 */ NewWizardMessages.getString("BuildPathsBlock.classpath.checkall.button"), //$NON-NLS-1$ /* 4 */ NewWizardMessages.getString("BuildPathsBlock.classpath.uncheckall.button") //$NON-NLS-1$ }; fClassPathList= new CheckedListDialogField(null, buttonLabels, new CPListLabelProvider()); fClassPathList.setDialogFieldListener(adapter); fClassPathList.setLabelText(NewWizardMessages.getString("BuildPathsBlock.classpath.label")); //$NON-NLS-1$ fClassPathList.setUpButtonIndex(0); fClassPathList.setDownButtonIndex(1); fClassPathList.setCheckAllButtonIndex(3); fClassPathList.setUncheckAllButtonIndex(4); fBuildPathDialogField= new StringButtonDialogField(adapter); fBuildPathDialogField.setButtonLabel(NewWizardMessages.getString("BuildPathsBlock.buildpath.button")); //$NON-NLS-1$ fBuildPathDialogField.setDialogFieldListener(adapter); fBuildPathDialogField.setLabelText(NewWizardMessages.getString("BuildPathsBlock.buildpath.label")); //$NON-NLS-1$ fBuildPathStatus= new StatusInfo(); fClassPathStatus= new StatusInfo(); fCurrJProject= null; } // -------- UI creation --------- public Control createControl(Composite parent) { fSWTWidget= parent; PixelConverter converter= new PixelConverter(parent); Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginWidth= 0; layout.numColumns= 1; composite.setLayout(layout); TabFolder folder= new TabFolder(composite, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); folder.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { tabChanged(e.item); } }); ImageRegistry imageRegistry= JavaPlugin.getDefault().getImageRegistry(); TabItem item; fSourceContainerPage= new SourceContainerWorkbookPage(fWorkspaceRoot, fClassPathList, fBuildPathDialogField); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.source")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_PACKFRAG_ROOT)); item.setData(fSourceContainerPage); item.setControl(fSourceContainerPage.getControl(folder)); IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); Image projectImage= workbench.getSharedImages().getImage(ISharedImages.IMG_OBJ_PROJECT); fProjectsPage= new ProjectsWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.projects")); //$NON-NLS-1$ item.setImage(projectImage); item.setData(fProjectsPage); item.setControl(fProjectsPage.getControl(folder)); fLibrariesPage= new LibrariesWorkbookPage(fWorkspaceRoot, fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.libraries")); //$NON-NLS-1$ item.setImage(imageRegistry.get(JavaPluginImages.IMG_OBJS_LIBRARY)); item.setData(fLibrariesPage); item.setControl(fLibrariesPage.getControl(folder)); // a non shared image Image cpoImage= JavaPluginImages.DESC_TOOL_CLASSPATH_ORDER.createImage(); composite.addDisposeListener(new ImageDisposer(cpoImage)); ClasspathOrderingWorkbookPage ordpage= new ClasspathOrderingWorkbookPage(fClassPathList); item= new TabItem(folder, SWT.NONE); item.setText(NewWizardMessages.getString("BuildPathsBlock.tab.order")); //$NON-NLS-1$ item.setImage(cpoImage); item.setData(ordpage); item.setControl(ordpage.getControl(folder)); if (fCurrJProject != null) { fSourceContainerPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); } Composite editorcomp= new Composite(composite, SWT.NONE); DialogField[] editors= new DialogField[] { fBuildPathDialogField }; LayoutUtil.doDefaultLayout(editorcomp, editors, true, 0, 0); int maxFieldWidth= converter.convertWidthInCharsToPixels(40); LayoutUtil.setWidthHint(fBuildPathDialogField.getTextControl(null), maxFieldWidth); LayoutUtil.setHorizontalGrabbing(fBuildPathDialogField.getTextControl(null)); editorcomp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); if (fShowSourceFolderPage) { folder.setSelection(0); fCurrPage= fSourceContainerPage; } else { folder.setSelection(3); fCurrPage= ordpage; fClassPathList.selectFirstElement(); } WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.BUILD_PATH_BLOCK); return composite; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Initializes the classpath for the given project. Multiple calls to init are allowed, * but all existing settings will be cleared and replace by the given or default paths. * @param project The java project to configure. Does not have to exist. * @param outputLocation The output location to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project- the * output location of the existing project * @param classpathEntries The classpath entries to be set in the page. If <code>null</code> * is passed, jdt default settings are used, or - if the project is an existing Java project - the * classpath entries of the existing project */ public void init(IJavaProject jproject, IPath outputLocation, IClasspathEntry[] classpathEntries) { fCurrJProject= jproject; boolean projectExists= false; List newClassPath= null; try { IProject project= fCurrJProject.getProject(); projectExists= (project.exists() && project.getFile(".classpath").exists()); //$NON-NLS-1$ if (projectExists) { if (outputLocation == null) { outputLocation= fCurrJProject.getOutputLocation(); } if (classpathEntries == null) { classpathEntries= fCurrJProject.getRawClasspath(); } } if (outputLocation == null) { outputLocation= getDefaultBuildPath(jproject); } if (classpathEntries != null) { newClassPath= getExistingEntries(classpathEntries); } } catch (CoreException e) { JavaPlugin.log(e); } if (newClassPath == null) { newClassPath= getDefaultClassPath(jproject); } List exportedEntries = new ArrayList(); for (int i= 0; i < newClassPath.size(); i++) { CPListElement curr= (CPListElement) newClassPath.get(i); if (curr.isExported() || curr.getEntryKind() == IClasspathEntry.CPE_SOURCE) { exportedEntries.add(curr); } } // inits the dialog field fBuildPathDialogField.setText(outputLocation.makeRelative().toString()); fClassPathList.setElements(newClassPath); fClassPathList.setCheckedElements(exportedEntries); if (fSourceContainerPage != null) { fSourceContainerPage.init(fCurrJProject); fProjectsPage.init(fCurrJProject); fLibrariesPage.init(fCurrJProject); } doStatusLineUpdate(); } private ArrayList getExistingEntries(IClasspathEntry[] classpathEntries) { ArrayList newClassPath= new ArrayList(); boolean projectExists= fCurrJProject.exists(); for (int i= 0; i < classpathEntries.length; i++) { IClasspathEntry curr= classpathEntries[i]; IPath path= curr.getPath(); // get the resource IResource res= null; boolean isMissing= false; switch (curr.getEntryKind()) { case IClasspathEntry.CPE_CONTAINER: res= null; //try { // isMissing= (JavaCore.getClasspathContainer(path, fCurrJProject) == null); //} catch (JavaModelException e) { isMissing= true; //} isMissing= false; break; case IClasspathEntry.CPE_VARIABLE: IPath resolvedPath= JavaCore.getResolvedVariablePath(path); res= null; isMissing= fWorkspaceRoot.findMember(resolvedPath) == null && !resolvedPath.toFile().isFile(); break; case IClasspathEntry.CPE_LIBRARY: res= fWorkspaceRoot.findMember(path); if (res == null) { if (!ArchiveFileFilter.isArchivePath(path)) { if (fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) { res= fWorkspaceRoot.getFolder(path); } } isMissing= !path.toFile().isFile(); // look for external JARs } break; case IClasspathEntry.CPE_SOURCE: res= fWorkspaceRoot.findMember(path); if (res == null) { if (fWorkspaceRoot.getWorkspace().validatePath(path.toString(), IResource.FOLDER).isOK()) { res= fWorkspaceRoot.getFolder(path); } isMissing= true; } break; case IClasspathEntry.CPE_PROJECT: res= fWorkspaceRoot.findMember(path); isMissing= (res == null); break; } boolean isExported= curr.isExported(); CPListElement elem= new CPListElement(fCurrJProject, curr.getEntryKind(), path, res, curr.getSourceAttachmentPath(), curr.getSourceAttachmentRootPath(), isExported); if (projectExists) { elem.setIsMissing(isMissing); } newClassPath.add(elem); } return newClassPath; } // -------- public api -------- /** * Returns the Java project. Can return <code>null<code> if the page has not * been initialized. */ public IJavaProject getJavaProject() { return fCurrJProject; } /** * Returns the current output location. Note that the path returned must not be valid. */ public IPath getOutputLocation() { return new Path(fBuildPathDialogField.getText()).makeAbsolute(); } /** * Returns the current class path (raw). Note that the entries returned must not be valid. */ public IClasspathEntry[] getRawClassPath() { List elements= fClassPathList.getElements(); int nElements= elements.size(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= 0; i < nElements; i++) { CPListElement currElement= (CPListElement) elements.get(i); entries[i]= currElement.getClasspathEntry(); } return entries; } // -------- evaluate default settings -------- private List getDefaultClassPath(IJavaProject jproj) { List list= new ArrayList(); IResource srcFolder; String sourceFolderName= NewJavaProjectPreferencePage.getSourceFolderName(); if (NewJavaProjectPreferencePage.useSrcAndBinFolders() && sourceFolderName.length() > 0) { srcFolder= jproj.getProject().getFolder(sourceFolderName); } else { srcFolder= jproj.getProject(); } list.add(new CPListElement(jproj, IClasspathEntry.CPE_SOURCE, srcFolder.getFullPath(), srcFolder)); IClasspathEntry[] jreEntries= NewJavaProjectPreferencePage.getDefaultJRELibrary(); list.addAll(getExistingEntries(jreEntries)); return list; } private IPath getDefaultBuildPath(IJavaProject jproj) { if (NewJavaProjectPreferencePage.useSrcAndBinFolders()) { String outputLocationName= NewJavaProjectPreferencePage.getOutputLocationName(); return jproj.getProject().getFullPath().append(outputLocationName); } else { return jproj.getProject().getFullPath(); } } private class BuildPathAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { buildPathChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { buildPathDialogFieldChanged(field); } } private void buildPathChangeControlPressed(DialogField field) { if (field == fBuildPathDialogField) { IContainer container= chooseContainer(); if (container != null) { fBuildPathDialogField.setText(container.getFullPath().toString()); } } } private void buildPathDialogFieldChanged(DialogField field) { if (field == fClassPathList) { updateClassPathStatus(); updateBuildPathStatus(); } else if (field == fBuildPathDialogField) { updateBuildPathStatus(); } doStatusLineUpdate(); } // -------- verification ------------------------------- private void doStatusLineUpdate() { IStatus res= findMostSevereStatus(); fContext.statusChanged(res); } private IStatus findMostSevereStatus() { return StatusUtil.getMoreSevere(fClassPathStatus, fBuildPathStatus); } /** * Validates the build path. */ private void updateClassPathStatus() { fClassPathStatus.setOK(); List elements= fClassPathList.getElements(); boolean entryMissing= false; IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); boolean isChecked= fClassPathList.isChecked(currElement); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE) { if (!isChecked) { fClassPathList.setCheckedWithoutUpdate(currElement, true); } } else { currElement.setExported(isChecked); } entries[i]= currElement.getClasspathEntry(); entryMissing= entryMissing || currElement.isMissing(); } if (entryMissing) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.EntryMissing")); //$NON-NLS-1$ } if (fCurrJProject.hasClasspathCycle(entries)) { fClassPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.CycleInClassPath")); //$NON-NLS-1$ } } /** * Validates output location & build path. */ private void updateBuildPathStatus() { fOutputLocationPath= null; String text= fBuildPathDialogField.getText(); if ("".equals(text)) { //$NON-NLS-1$ fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.EnterBuildPath")); //$NON-NLS-1$ return; } IPath path= getOutputLocation(); IResource res= fWorkspaceRoot.findMember(path); if (res != null) { // if exists, must be a folder or project if (res.getType() == IResource.FILE) { fBuildPathStatus.setError(NewWizardMessages.getString("BuildPathsBlock.error.InvalidBuildPath")); //$NON-NLS-1$ return; } } fOutputLocationPath= path; List elements= fClassPathList.getElements(); IClasspathEntry[] entries= new IClasspathEntry[elements.size()]; boolean outputFolderAlsoSourceFolder= false; for (int i= elements.size()-1 ; i >= 0 ; i--) { CPListElement currElement= (CPListElement)elements.get(i); entries[i]= currElement.getClasspathEntry(); if (currElement.getEntryKind() == IClasspathEntry.CPE_SOURCE && fOutputLocationPath.equals(currElement.getPath())) { outputFolderAlsoSourceFolder= true; } } IStatus status= JavaConventions.validateClasspath(fCurrJProject, entries, path); if (!status.isOK()) { fBuildPathStatus.setError(status.getMessage()); return; } if (res != null && res.exists() && fCurrJProject.exists()) { try { IPath oldOutputLocation= fCurrJProject.getOutputLocation(); if (!oldOutputLocation.equals(fOutputLocationPath) && !outputFolderAlsoSourceFolder) { if (((IContainer)res).members().length > 0) { fBuildPathStatus.setWarning(NewWizardMessages.getString("BuildPathsBlock.warning.OutputFolderNotEmpty")); //$NON-NLS-1$ return; } } } catch (CoreException e) { JavaPlugin.log(e); } } fBuildPathStatus.setOK(); } // -------- creation ------------------------------- public static void createProject(IProject project, IPath locationPath, IProgressMonitor monitor) throws CoreException { // create the project try { if (!project.exists()) { IProjectDescription desc= project.getWorkspace().newProjectDescription(project.getName()); if (Platform.getLocation().equals(locationPath)) { locationPath= null; } desc.setLocation(locationPath); project.create(desc, monitor); monitor= null; } if (!project.isOpen()) { project.open(monitor); monitor= null; } } finally { if (monitor != null) { monitor.done(); } } } public static void addJavaNature(IProject project, IProgressMonitor monitor) throws CoreException { if (!project.hasNature(JavaCore.NATURE_ID)) { IProjectDescription description = project.getDescription(); String[] prevNatures= description.getNatureIds(); String[] newNatures= new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length]= JavaCore.NATURE_ID; description.setNatureIds(newNatures); project.setDescription(description, monitor); } } public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("BuildPathsBlock.operationdesc"), 10); //$NON-NLS-1$ try { Shell shell= null; if (fSWTWidget != null && !fSWTWidget.getShell().isDisposed()) { shell= fSWTWidget.getShell(); } internalConfigureJavaProject(fClassPathList.getElements(), getOutputLocation(), shell, monitor); } finally { monitor.done(); } } /** * Creates the Java project and sets the configured build path and output location. * If the project already exists only build paths are updated. */ private void internalConfigureJavaProject(List classPathEntries, IPath outputLocation, Shell shell, IProgressMonitor monitor) throws CoreException, InterruptedException { // 10 monitor steps to go IRemoveOldBinariesQuery reorgQuery= null; if (shell != null) { reorgQuery= getRemoveOldBinariesQuery(shell); } // remove old .class files if (reorgQuery != null) { IPath oldOutputLocation= fCurrJProject.getOutputLocation(); if (!outputLocation.equals(oldOutputLocation)) { IResource res= fWorkspaceRoot.findMember(oldOutputLocation); if (res instanceof IContainer && hasClassfiles(res)) { if (reorgQuery.doQuery(oldOutputLocation)) { removeOldClassfiles(res); } } } } // create and set the output path first if (!fWorkspaceRoot.exists(outputLocation)) { IFolder folder= fWorkspaceRoot.getFolder(outputLocation); CoreUtility.createFolder(folder, true, true, null); } monitor.worked(2); int nEntries= classPathEntries.size(); IClasspathEntry[] classpath= new IClasspathEntry[nEntries]; // create and set the class path for (int i= 0; i < nEntries; i++) { CPListElement entry= ((CPListElement)classPathEntries.get(i)); IResource res= entry.getResource(); if ((res instanceof IFolder) && !res.exists()) { CoreUtility.createFolder((IFolder)res, true, true, null); } classpath[i]= entry.getClasspathEntry(); // set javadoc location URL javadocLocation= entry.getJavadocLocation(); if (javadocLocation != null) { IPath path= entry.getPath(); if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { path= JavaCore.getResolvedVariablePath(path); } if (path != null) { JavaDocLocations.setLibraryJavadocLocation(path, javadocLocation); } } } monitor.worked(1); fCurrJProject.setRawClasspath(classpath, outputLocation, new SubProgressMonitor(monitor, 7)); } public static boolean hasClassfiles(IResource resource) throws CoreException { if (resource.isDerived()) { //$NON-NLS-1$ return true; } if (resource instanceof IContainer) { IResource[] members= ((IContainer) resource).members(); for (int i= 0; i < members.length; i++) { if (hasClassfiles(members[i])) { return true; } } } return false; } public static void removeOldClassfiles(IResource resource) throws CoreException { if (resource.isDerived()) { resource.delete(false, null); } else if (resource instanceof IContainer) { IResource[] members= ((IContainer) resource).members(); for (int i= 0; i < members.length; i++) { removeOldClassfiles(members[i]); } } } public static IRemoveOldBinariesQuery getRemoveOldBinariesQuery(final Shell shell) { return new IRemoveOldBinariesQuery() { public boolean doQuery(final IPath oldOutputLocation) throws InterruptedException { final int[] res= new int[] { 1 }; shell.getDisplay().syncExec(new Runnable() { public void run() { String title= NewWizardMessages.getString("BuildPathsBlock.RemoveBinariesDialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("BuildPathsBlock.RemoveBinariesDialog.description", oldOutputLocation.toString()); //$NON-NLS-1$ MessageDialog dialog= new MessageDialog(shell, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); res[0]= dialog.open(); } }); if (res[0] == 0) { return true; } else if (res[0] == 1) { return false; } throw new InterruptedException(); } }; } // ---------- util method ------------ private IContainer chooseContainer() { Class[] acceptedClasses= new Class[] { IProject.class, IFolder.class }; ISelectionStatusValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); IProject[] allProjects= fWorkspaceRoot.getProjects(); ArrayList rejectedElements= new ArrayList(allProjects.length); IProject currProject= fCurrJProject.getProject(); for (int i= 0; i < allProjects.length; i++) { if (!allProjects[i].equals(currProject)) { rejectedElements.add(allProjects[i]); } } ViewerFilter filter= new TypedViewerFilter(acceptedClasses, rejectedElements.toArray()); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSelection= null; if (fOutputLocationPath != null) { initSelection= fWorkspaceRoot.findMember(fOutputLocationPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setTitle(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.title")); //$NON-NLS-1$ dialog.setValidator(validator); dialog.setMessage(NewWizardMessages.getString("BuildPathsBlock.ChooseOutputFolderDialog.description")); //$NON-NLS-1$ dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); dialog.setInitialSelection(initSelection); if (dialog.open() == dialog.OK) { return (IContainer)dialog.getFirstResult(); } return null; } // -------- tab switching ---------- private void tabChanged(Widget widget) { if (widget instanceof TabItem) { BuildPathBasePage newPage= (BuildPathBasePage) ((TabItem) widget).getData(); if (fCurrPage != null) { List selection= fCurrPage.getSelection(); if (!selection.isEmpty()) { newPage.setSelection(selection); } } fCurrPage= newPage; } } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/CPVariableElementLabelProvider.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import org.eclipse.swt.graphics.Image; import org.eclipse.core.runtime.IPath; import org.eclipse.jface.resource.ImageRegistry; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; public class CPVariableElementLabelProvider extends LabelProvider { private Image fVariableImage; private boolean fShowResolvedVariables; public CPVariableElementLabelProvider(boolean showResolvedVariables) { ImageRegistry reg= JavaPlugin.getDefault().getImageRegistry(); fVariableImage= reg.get(JavaPluginImages.IMG_OBJS_ENV_VAR); fShowResolvedVariables= showResolvedVariables; } /* * @see LabelProvider#getImage(java.lang.Object) */ public Image getImage(Object element) { if (element instanceof CPVariableElement) { return fVariableImage; } return super.getImage(element); } /* * @see LabelProvider#getText(java.lang.Object) */ public String getText(Object element) { if (element instanceof CPVariableElement) { CPVariableElement curr= (CPVariableElement)element; String name= curr.getName(); IPath path= curr.getPath(); StringBuffer buf= new StringBuffer(name); if (curr.isReserved()) { buf.append(' '); buf.append(NewWizardMessages.getString("CPVariableElementLabelProvider.reserved")); //$NON-NLS-1$ } if (fShowResolvedVariables || !curr.isReserved()) { if (path != null) { buf.append(" - "); //$NON-NLS-1$ if (!path.isEmpty()) { buf.append(path.toOSString()); } else { buf.append(NewWizardMessages.getString("CPVariableElementLabelProvider.empty")); //$NON-NLS-1$ } } } return buf.toString(); } return super.getText(element); } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/EditVariableEntryDialog.java
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/JARFileSelectionDialog.java
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/LibrariesWorkbookPage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.ArrayList; import java.util.List; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; 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.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.swt.widgets.Shell; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.jface.dialogs.IDialogSettings; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.wizard.WizardDialog; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaModel; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.IUIConstants; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.ComboDialogField; 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; public class LibrariesWorkbookPage extends BuildPathBasePage { private ListDialogField fClassPathList; private IJavaProject fCurrJProject; private ListDialogField fLibrariesList; private IWorkspaceRoot fWorkspaceRoot; private IDialogSettings fDialogSettings; private Control fSWTControl; private final int IDX_ADDJAR= 0; private final int IDX_ADDEXT= 1; private final int IDX_ADDVAR= 2; private final int IDX_ADDADV= 3; private final int IDX_EDIT= 5; private final int IDX_ATTACH= 6; private final int IDX_REMOVE= 8; public LibrariesWorkbookPage(IWorkspaceRoot root, ListDialogField classPathList) { fClassPathList= classPathList; fWorkspaceRoot= root; fSWTControl= null; fDialogSettings= JavaPlugin.getDefault().getDialogSettings(); String[] buttonLabels= new String[] { /* IDX_ADDJAR*/ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addjar.button"), //$NON-NLS-1$ /* IDX_ADDEXT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addextjar.button"), //$NON-NLS-1$ /* IDX_ADDVAR */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.addvariable.button"), //$NON-NLS-1$ /* IDX_ADDADV */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.advanced.button"), //$NON-NLS-1$ /* */ null, /* IDX_EDIT */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.edit.button"), //$NON-NLS-1$ /* IDX_ATTACH */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.setsource.button"), //$NON-NLS-1$ /* */ null, /* IDX_REMOVE */ NewWizardMessages.getString("LibrariesWorkbookPage.libraries.remove.button") //$NON-NLS-1$ }; LibrariesAdapter adapter= new LibrariesAdapter(); fLibrariesList= new ListDialogField(adapter, buttonLabels, new CPListLabelProvider()); fLibrariesList.setDialogFieldListener(adapter); fLibrariesList.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.libraries.label")); //$NON-NLS-1$ fLibrariesList.setRemoveButtonIndex(IDX_REMOVE); //$NON-NLS-1$ fLibrariesList.enableButton(IDX_EDIT, false); fLibrariesList.enableButton(IDX_ATTACH, false); fLibrariesList.setViewerSorter(new CPListElementSorter()); } public void init(IJavaProject jproject) { fCurrJProject= jproject; updateLibrariesList(); } private boolean isLibraryKind(int kind) { return kind == IClasspathEntry.CPE_LIBRARY || kind == IClasspathEntry.CPE_VARIABLE || kind == IClasspathEntry.CPE_CONTAINER; } private void updateLibrariesList() { List cpelements= fClassPathList.getElements(); List libelements= new ArrayList(cpelements.size()); int nElements= cpelements.size(); for (int i= 0; i < nElements; i++) { CPListElement cpe= (CPListElement)cpelements.get(i); if (isLibraryKind(cpe.getEntryKind())) { libelements.add(cpe); } } fLibrariesList.setElements(libelements); } // -------- ui creation public Control getControl(Composite parent) { PixelConverter converter= new PixelConverter(parent); Composite composite= new Composite(parent, SWT.NONE); LayoutUtil.doDefaultLayout(composite, new DialogField[] { fLibrariesList }, true, SWT.DEFAULT, SWT.DEFAULT); LayoutUtil.setHorizontalGrabbing(fLibrariesList.getListControl(null)); int buttonBarWidth= converter.convertWidthInCharsToPixels(24); fLibrariesList.setButtonsMinWidth(buttonBarWidth); fLibrariesList.getTableViewer().setSorter(new CPListElementSorter()); fSWTControl= composite; return composite; } private Shell getShell() { if (fSWTControl != null) { return fSWTControl.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private class LibrariesAdapter implements IDialogFieldListener, IListAdapter { // -------- IListAdapter -------- public void customButtonPressed(DialogField field, int index) { libaryPageCustomButtonPressed(field, index); } public void selectionChanged(DialogField field) { libaryPageSelectionChanged(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { libaryPageDialogFieldChanged(field); } } private void libaryPageCustomButtonPressed(DialogField field, int index) { CPListElement[] libentries= null; switch (index) { case IDX_ADDJAR: /* add jar */ libentries= openJarFileDialog(null); break; case IDX_ADDEXT: /* add external jar */ libentries= openExtJarFileDialog(null); break; case IDX_ADDVAR: /* add variable */ libentries= openVariableSelectionDialog(null); break; case IDX_ADDADV: /* addvanced */ AdvancedDialog advDialog= new AdvancedDialog(getShell()); if (advDialog.open() == advDialog.OK) { libentries= advDialog.getResult(); } break; case IDX_ATTACH: /* set source attachment */ List selElements= fLibrariesList.getSelectedElements(); CPListElement selElement= (CPListElement) selElements.get(0); SourceAttachmentDialog dialog= new SourceAttachmentDialog(getShell(), fWorkspaceRoot, selElement.getClasspathEntry()); if (dialog.open() == dialog.OK) { selElement.setSourceAttachment(dialog.getSourceAttachmentPath(), dialog.getSourceAttachmentRootPath()); fLibrariesList.refresh(); fClassPathList.refresh(); } break; case IDX_EDIT: /* edit */ editEntry(); return; } if (libentries != null) { int nElementsChosen= libentries.length; // remove duplicates List cplist= fLibrariesList.getElements(); List elementsToAdd= new ArrayList(nElementsChosen); for (int i= 0; i < nElementsChosen; i++) { CPListElement curr= libentries[i]; if (!cplist.contains(curr) && !elementsToAdd.contains(curr)) { elementsToAdd.add(curr); addAttachmentsFromExistingLibs(curr); } } fLibrariesList.addElements(elementsToAdd); fLibrariesList.postSetSelection(new StructuredSelection(libentries)); } } /** * Method editEntry. */ private void editEntry() { List selElements= fLibrariesList.getSelectedElements(); if (selElements.size() != 1) { return; } CPListElement elem= (CPListElement) selElements.get(0); CPListElement[] res= null; switch (elem.getEntryKind()) { case IClasspathEntry.CPE_CONTAINER: String title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.edit.title"); //$NON-NLS-1$ res= openContainerDialog(title, new ClasspathContainerWizard(elem.getClasspathEntry())); break; case IClasspathEntry.CPE_LIBRARY: IResource resource= elem.getResource(); if (resource == null) { res= openExtJarFileDialog(elem); } else if (resource.getType() == IResource.FOLDER) { if (resource.exists()) { res= openClassFolderDialog(elem); } else { res= openNewClassFolderDialog(elem); } } else if (resource.getType() == IResource.FILE) { res= openJarFileDialog(elem); } break; case IClasspathEntry.CPE_VARIABLE: res= openVariableSelectionDialog(elem); break; } if (res != null && res.length > 0) { fLibrariesList.replaceElement(elem, res[0]); } } private void libaryPageSelectionChanged(DialogField field) { List selElements= fLibrariesList.getSelectedElements(); fLibrariesList.enableButton(IDX_ATTACH, canDoSourceAttachment(selElements)); fLibrariesList.enableButton(IDX_EDIT, selElements.size() == 1); } private void libaryPageDialogFieldChanged(DialogField field) { if (fCurrJProject != null) { // already initialized updateClasspathList(); } } private boolean canDoSourceAttachment(List selElements) { if (selElements != null && selElements.size() == 1) { CPListElement elem= (CPListElement) selElements.get(0); if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY) { return (!(elem.getResource() instanceof IFolder)); } else if (elem.getEntryKind() == IClasspathEntry.CPE_VARIABLE) { return true; } } return false; } private void updateClasspathList() { List projelements= fLibrariesList.getElements(); boolean remove= false; List cpelements= fClassPathList.getElements(); // backwards, as entries will be deleted for (int i= cpelements.size() - 1; i >= 0; i--) { CPListElement cpe= (CPListElement)cpelements.get(i); int kind= cpe.getEntryKind(); if (isLibraryKind(kind)) { if (!projelements.remove(cpe)) { cpelements.remove(i); remove= true; } } } for (int i= 0; i < projelements.size(); i++) { cpelements.add(projelements.get(i)); } if (remove || (projelements.size() > 0)) { fClassPathList.setElements(cpelements); } } private CPListElement[] openNewClassFolderDialog(CPListElement existing) { String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.NewClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$ IProject currProject= fCurrJProject.getProject(); NewContainerDialog dialog= new NewContainerDialog(getShell(), title, currProject, getUsedContainers(existing), existing); IPath projpath= currProject.getFullPath(); dialog.setMessage(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.NewClassFolderDialog.description", projpath.toString())); //$NON-NLS-1$ if (dialog.open() == dialog.OK) { IFolder folder= dialog.getFolder(); return new CPListElement[] { newCPLibraryElement(folder) }; } return null; } private CPListElement[] openClassFolderDialog(CPListElement existing) { Class[] acceptedClasses= new Class[] { IFolder.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null); acceptedClasses= new Class[] { IProject.class, IFolder.class }; ViewerFilter filter= new TypedViewerFilter(acceptedClasses, getUsedContainers(existing)); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$ String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.ExistingClassFolderDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$ ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(title); dialog.setMessage(message); dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); if (existing == null) { dialog.setInitialSelection(fCurrJProject.getProject()); } else { dialog.setInitialSelection(existing.getResource()); } if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource) elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private CPListElement[] openJarFileDialog(CPListElement existing) { Class[] acceptedClasses= new Class[] { IFile.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, existing == null); ViewerFilter filter= new ArchiveFileFilter(getUsedJARFiles(existing)); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$ String message= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.new.description") : NewWizardMessages.getString("LibrariesWorkbookPage.JARArchiveDialog.edit.description"); //$NON-NLS-1$ //$NON-NLS-2$ ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setValidator(validator); dialog.setTitle(title); dialog.setMessage(message); dialog.addFilter(filter); dialog.setInput(fWorkspaceRoot); if (existing == null) { dialog.setInitialSelection(fCurrJProject.getProject()); } else { dialog.setInitialSelection(existing.getResource()); } if (dialog.open() == dialog.OK) { Object[] elements= dialog.getResult(); CPListElement[] res= new CPListElement[elements.length]; for (int i= 0; i < res.length; i++) { IResource elem= (IResource)elements[i]; res[i]= newCPLibraryElement(elem); } return res; } return null; } private IContainer[] getUsedContainers(CPListElement existing) { ArrayList res= new ArrayList(); if (fCurrJProject.exists()) { try { IPath outputLocation= fCurrJProject.getOutputLocation(); if (outputLocation != null) { IResource resource= fWorkspaceRoot.findMember(outputLocation); if (resource instanceof IFolder) { // != Project res.add(resource); } } } catch (JavaModelException e) { // ignore it here, just log JavaPlugin.log(e.getStatus()); } } List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) { IResource resource= elem.getResource(); if (resource instanceof IContainer && !resource.equals(existing)) { res.add(resource); } } } return (IContainer[]) res.toArray(new IContainer[res.size()]); } private IFile[] getUsedJARFiles(CPListElement existing) { List res= new ArrayList(); List cplist= fLibrariesList.getElements(); for (int i= 0; i < cplist.size(); i++) { CPListElement elem= (CPListElement)cplist.get(i); if (elem.getEntryKind() == IClasspathEntry.CPE_LIBRARY && (elem != existing)) { IResource resource= elem.getResource(); if (resource instanceof IFile) { res.add(resource); } } } return (IFile[]) res.toArray(new IFile[res.size()]); } private CPListElement newCPLibraryElement(IResource res) { return new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, res.getFullPath(), res); }; private CPListElement[] openExtJarFileDialog(CPListElement existing) { String lastUsedPath; if (existing != null) { lastUsedPath= existing.getPath().removeLastSegments(1).toOSString(); } else { lastUsedPath= fDialogSettings.get(IUIConstants.DIALOGSTORE_LASTEXTJAR); if (lastUsedPath == null) { lastUsedPath= ""; //$NON-NLS-1$ } } String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.ExtJARArchiveDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$ FileDialog dialog= new FileDialog(getShell(), existing == null ? SWT.MULTI : SWT.SINGLE); dialog.setText(title); dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(lastUsedPath); if (existing != null) { dialog.setFileName(existing.getPath().lastSegment()); } String res= dialog.open(); if (res == null) { return null; } String[] fileNames= dialog.getFileNames(); int nChosen= fileNames.length; IPath filterPath= new Path(dialog.getFilterPath()); CPListElement[] elems= new CPListElement[nChosen]; for (int i= 0; i < nChosen; i++) { IPath path= filterPath.append(fileNames[i]).makeAbsolute(); elems[i]= new CPListElement(fCurrJProject, IClasspathEntry.CPE_LIBRARY, path, null); } fDialogSettings.put(IUIConstants.DIALOGSTORE_LASTEXTJAR, filterPath.toOSString()); return elems; } private CPListElement[] openVariableSelectionDialog(CPListElement existing) { String title= (existing == null) ? NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.new.title") : NewWizardMessages.getString("LibrariesWorkbookPage.VariableSelectionDialog.edit.title"); //$NON-NLS-1$ //$NON-NLS-2$ IPath existingPath= (existing == null) ? null : existing.getPath(); NewVariableEntryDialog dialog= new NewVariableEntryDialog(getShell(), title, existingPath); if (dialog.open() == dialog.OK) { List existingElements= fLibrariesList.getElements(); IPath[] paths= dialog.getResult(); ArrayList result= new ArrayList(); for (int i = 0; i < paths.length; i++) { CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_VARIABLE, paths[i], null); IPath resolvedPath= JavaCore.getResolvedVariablePath(paths[i]); elem.setIsMissing((resolvedPath == null) || !resolvedPath.toFile().exists()); if (!existingElements.contains(elem)) { result.add(elem); } } return (CPListElement[]) result.toArray(new CPListElement[result.size()]); } return null; } private CPListElement[] openContainerDialog(String title, ClasspathContainerWizard wizard) { WizardDialog dialog= new WizardDialog(getShell(), wizard); PixelConverter converter= new PixelConverter(getShell()); dialog.setMinimumPageSize(converter.convertWidthInCharsToPixels(40), converter.convertHeightInCharsToPixels(20)); dialog.create(); dialog.getShell().setText(title); if (dialog.open() == dialog.OK) { IClasspathEntry created= wizard.getNewEntry(); if (created != null) { CPListElement elem= new CPListElement(fCurrJProject, IClasspathEntry.CPE_CONTAINER, created.getPath(), null); if (elem != null) { return new CPListElement[] { elem }; } } } return null; } private void addAttachmentsFromExistingLibs(CPListElement elem) { if (elem.getEntryKind() == IClasspathEntry.CPE_CONTAINER) { return; } try { IJavaModel jmodel= fCurrJProject.getJavaModel(); IJavaProject[] jprojects= jmodel.getJavaProjects(); for (int i= 0; i < jprojects.length; i++) { IJavaProject curr= jprojects[i]; if (!curr.equals(fCurrJProject)) { IClasspathEntry[] entries= curr.getRawClasspath(); for (int k= 0; k < entries.length; k++) { IClasspathEntry entry= entries[k]; if (entry.getEntryKind() == elem.getEntryKind() && entry.getPath().equals(elem.getPath())) { IPath attachPath= entry.getSourceAttachmentPath(); if (attachPath != null && !attachPath.isEmpty()) { elem.setSourceAttachment(attachPath, entry.getSourceAttachmentRootPath()); return; } } } } } } catch (JavaModelException e) { JavaPlugin.log(e.getStatus()); } } private class AdvancedDialog extends Dialog { private static final String DIALOGSTORE_ADV_SECTION= "LibrariesWorkbookPage.advanced"; //$NON-NLS-1$ private static final String DIALOGSTORE_SELECTED= "selected"; //$NON-NLS-1$ private static final String DIALOGSTORE_CONTAINER_IDX= "containerindex"; //$NON-NLS-1$ private DialogField fLabelField; private SelectionButtonDialogField fCreateFolderField; private SelectionButtonDialogField fAddFolderField; private SelectionButtonDialogField fAddContainerField; private ComboDialogField fCombo; private CPListElement[] fResult; private IDialogSettings fAdvSettings; private ClasspathContainerDescriptor[] fDescriptors; public AdvancedDialog(Shell parent) { super(parent); fAdvSettings= fDialogSettings.getSection(DIALOGSTORE_ADV_SECTION); if (fAdvSettings == null) { fAdvSettings= fDialogSettings.addNewSection(DIALOGSTORE_ADV_SECTION); fAdvSettings.put(DIALOGSTORE_SELECTED, 2); // container fAdvSettings.put(DIALOGSTORE_CONTAINER_IDX, 0); } fDescriptors= ClasspathContainerDescriptor.getDescriptors(); fLabelField= new DialogField(); fLabelField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.description")); //$NON-NLS-1$ fCreateFolderField= new SelectionButtonDialogField(SWT.RADIO); fCreateFolderField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.createfolder")); //$NON-NLS-1$ fAddFolderField= new SelectionButtonDialogField(SWT.RADIO); fAddFolderField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.addfolder")); //$NON-NLS-1$ fAddContainerField= new SelectionButtonDialogField(SWT.RADIO); fAddContainerField.setLabelText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.addcontainer")); //$NON-NLS-1$ String[] names= new String[fDescriptors.length]; for (int i = 0; i < names.length; i++) { names[i]= fDescriptors[i].getName(); } fCombo= new ComboDialogField(SWT.READ_ONLY); fCombo.setItems(names); fAddContainerField.attachDialogField(fCombo); int selected= fAdvSettings.getInt(DIALOGSTORE_SELECTED); fCreateFolderField.setSelection(selected == 0); fAddFolderField.setSelection(selected == 1); fAddContainerField.setSelection(selected == 2); fCombo.selectItem(fAdvSettings.getInt(DIALOGSTORE_CONTAINER_IDX)); } /* * @see Window#create(Shell) */ protected void configureShell(Shell shell) { super.configureShell(shell); shell.setText(NewWizardMessages.getString("LibrariesWorkbookPage.AdvancedDialog.title")); //$NON-NLS-1$ WorkbenchHelp.setHelp(shell, IJavaHelpContextIds.LIBRARIES_WORKBOOK_PAGE_ADVANCED_DIALOG); } protected Control createDialogArea(Composite parent) { initializeDialogUnits(parent); Composite composite= (Composite) super.createDialogArea(parent); Composite inner= new Composite(composite, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; inner.setLayout(layout); fLabelField.doFillIntoGrid(inner, 1); fCreateFolderField.doFillIntoGrid(inner, 1); fAddFolderField.doFillIntoGrid(inner, 1); fAddContainerField.doFillIntoGrid(inner, 1); Control control= fCombo.getComboControl(inner); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalIndent= convertWidthInCharsToPixels(3); control.setLayoutData(gd); return composite; } /* (non-Javadoc) * @see Dialog#okPressed() */ protected void okPressed() { fResult= null; if (fCreateFolderField.isSelected()) { fResult= openNewClassFolderDialog(null); fAdvSettings.put(DIALOGSTORE_SELECTED, 0); } else if (fAddFolderField.isSelected()) { fResult= openClassFolderDialog(null); fAdvSettings.put(DIALOGSTORE_SELECTED, 1); } else if (fAddContainerField.isSelected()) { String selected= fCombo.getText(); for (int i = 0; i < fDescriptors.length; i++) { if (fDescriptors[i].getName().equals(selected)) { String title= NewWizardMessages.getString("LibrariesWorkbookPage.ContainerDialog.new.title"); //$NON-NLS-1$ fResult= openContainerDialog(title, new ClasspathContainerWizard(fDescriptors[i])); fAdvSettings.put(DIALOGSTORE_CONTAINER_IDX, i); break; } } fAdvSettings.put(DIALOGSTORE_SELECTED, 2); } if (fResult != null) { super.okPressed(); } // stay open } public CPListElement[] getResult() { return fResult; } } // a dialog to set the source attachment properties private static class SourceAttachmentDialog extends StatusDialog implements IStatusChangeListener { private SourceAttachmentBlock fSourceAttachmentBlock; public SourceAttachmentDialog(Shell parent, IWorkspaceRoot root, IClasspathEntry entry) { super(parent); setTitle(NewWizardMessages.getFormattedString("LibrariesWorkbookPage.SourceAttachmentDialog.title", entry.getPath().toString())); //$NON-NLS-1$ fSourceAttachmentBlock= new SourceAttachmentBlock(root, this, entry); } /* * @see Windows#configureShell */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.SOURCE_ATTACHMENT_DIALOG); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite)super.createDialogArea(parent); Control inner= fSourceAttachmentBlock.createControl(composite); inner.setLayoutData(new GridData(GridData.FILL_BOTH)); return composite; } public void statusChanged(IStatus status) { updateStatus(status); } public IPath getSourceAttachmentPath() { return fSourceAttachmentBlock.getSourceAttachmentPath(); } public IPath getSourceAttachmentRootPath() { return fSourceAttachmentBlock.getSourceAttachmentRootPath(); } } /* * @see BuildPathBasePage#getSelection */ public List getSelection() { return fLibrariesList.getSelectedElements(); } /* * @see BuildPathBasePage#setSelection */ public void setSelection(List selElements) { for (int i= selElements.size()-1; i >= 0; i--) { CPListElement curr= (CPListElement) selElements.get(i); if (!isLibraryKind(curr.getEntryKind())) { selElements.remove(i); } } fLibrariesList.selectElements(new StructuredSelection(selElements)); } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/NewVariableEntryDialog.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; 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.graphics.Image; 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.Dialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.Viewer; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.dialogs.ISelectionStatusValidator; 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.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; public class NewVariableEntryDialog extends Dialog { private class VariableSelectionListener implements IDoubleClickListener, ISelectionChangedListener { public void doubleClick(DoubleClickEvent event) { doDoubleClick(); } public void selectionChanged(SelectionChangedEvent event) { doSelectionChanged(); } } private static class FileLabelProvider extends LabelProvider { private final Image IMG_FOLDER= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER); private final Image IMG_FILE= PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE); public Image getImage(Object element) { if (element instanceof File) { File curr= (File) element; if (curr.isDirectory()) { return IMG_FOLDER; } else { return IMG_FILE; } } return null; } public String getText(Object element) { if (element instanceof File) { return ((File) element).getName(); } return super.getText(element); } } private static class FileContentProvider implements ITreeContentProvider { private final Object[] EMPTY= new Object[0]; public Object[] getChildren(Object parentElement) { if (parentElement instanceof File) { File[] children= ((File) parentElement).listFiles(); if (children != null) { return children; } } return EMPTY; } public Object getParent(Object element) { if (element instanceof File) { return ((File) element).getParentFile(); } return null; } public boolean hasChildren(Object element) { return getChildren(element).length > 0; } public Object[] getElements(Object element) { return getChildren(element); } public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } } private static class ExtensionValidator implements ISelectionStatusValidator { private boolean fAllowMulitple; public ExtensionValidator(boolean allowMultiple) { fAllowMulitple= allowMultiple; } public IStatus validate(Object[] selection) { int nSelected= selection.length; if ((!fAllowMulitple && nSelected != 1) || nSelected == 0) { return new StatusInfo(StatusInfo.ERROR, ""); //$NON-NLS-1$ } for (int i= 0; i < selection.length; i++) { Object curr= selection[i]; if (curr instanceof File) { File file= (File) curr; if (!file.isFile() || !ArchiveFileFilter.isArchivePath(new Path(file.getName()))) { return new StatusInfo(StatusInfo.ERROR, ""); //$NON-NLS-1$ } } } return new StatusInfo(); } } private final int EXTEND_ID= IDialogConstants.CLIENT_ID; private VariableBlock fVariableBlock; private Button fExtensionButton; private Button fOkButton; private IPath[] fResultPaths; private IPath fExistingPath; private String fTitle; private boolean fFirstInvocation= true; public NewVariableEntryDialog(Shell parent, String title, IPath existingPath) { super(parent); fVariableBlock= new VariableBlock(false, existingPath == null ? null : existingPath.segment(0)); fResultPaths= null; fExistingPath= existingPath; fTitle= title; } /* (non-Javadoc) * @see Window#configureShell(Shell) */ protected void configureShell(Shell shell) { shell.setText(fTitle); super.configureShell(shell); WorkbenchHelp.setHelp(shell, IJavaHelpContextIds.NEW_VARIABLE_ENTRY_DIALOG); } protected Control createDialogArea(Composite parent) { VariableSelectionListener listener= new VariableSelectionListener(); Composite composite= (Composite)super.createDialogArea(parent); fVariableBlock.createContents(composite); fVariableBlock.addDoubleClickListener(listener); fVariableBlock.addSelectionChangedListener(listener); return composite; } /** * @see Dialog#createButtonsForButtonBar(Composite) */ protected void createButtonsForButtonBar(Composite parent) { fOkButton= createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); fExtensionButton= createButton(parent, EXTEND_ID, NewWizardMessages.getString("NewVariableEntryDialog.addextension.button"), false); //$NON-NLS-1$ createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } protected void okPressed() { fVariableBlock.performOk(); super.okPressed(); } public IPath[] getResult() { return fResultPaths; } /* * @see IDoubleClickListener#doubleClick(DoubleClickEvent) */ private void doDoubleClick() { if (fOkButton.isEnabled()) { okPressed(); } else if (fExtensionButton.isEnabled()) { buttonPressed(EXTEND_ID); } } private void doSelectionChanged() { boolean isValidSelection= true; List selected= fVariableBlock.getSelectedElements(); int nSelected= selected.size(); boolean canExtend= false; if (nSelected > 0) { if (fExistingPath != null && nSelected != 1) { isValidSelection= false; } else { 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()) { isValidSelection= false; } } } } else { isValidSelection= false; } fExtensionButton.setEnabled(nSelected == 1 && !isValidSelection); fOkButton.setEnabled(isValidSelection); if (fFirstInvocation) { fFirstInvocation= false; if (fExistingPath != null && fExistingPath.segmentCount() > 1 && nSelected == 1) { IPath resolved= JavaCore.getResolvedVariablePath(fExistingPath); if (resolved != null && resolved.toFile().exists()) { buttonPressed(EXTEND_ID); } } } } private IPath[] chooseExtensions(CPVariableElement elem) { File file= elem.getPath().toFile(); ILabelProvider lp= new FileLabelProvider(); ITreeContentProvider cp= new FileContentProvider(); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); 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); dialog.setValidator(new ExtensionValidator(fExistingPath == null)); if (fExistingPath != null) { IPath resolved= JavaCore.getResolvedVariablePath(fExistingPath); if (resolved != null) { dialog.setInitialSelection(resolved.toFile()); } } if (dialog.open() == dialog.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; } /* * @see Dialog#buttonPressed(int) */ protected void buttonPressed(int buttonId) { if (buttonId == EXTEND_ID) { List selected= fVariableBlock.getSelectedElements(); if (selected.size() == 1) { IPath[] extendedPaths= chooseExtensions((CPVariableElement) selected.get(0)); if (extendedPaths != null) { fResultPaths= extendedPaths; super.buttonPressed(IDialogConstants.OK_ID); } } } else { super.buttonPressed(buttonId); } } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/SourceAttachmentBlock.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.zip.ZipFile; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CLabel; import org.eclipse.swt.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.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.ITreeContentProvider; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.dialogs.ElementTreeSelectionDialog; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.ui.model.WorkbenchContentProvider; import org.eclipse.ui.model.WorkbenchLabelProvider; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.PixelConverter; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator; import org.eclipse.jdt.internal.ui.wizards.dialogfields.DialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IDialogFieldListener; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; import org.eclipse.jdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; /** * UI to set the source attachment archive and root. * Same implementation for both setting attachments for libraries from * variable entries and for normal (internal or external) jar. */ public class SourceAttachmentBlock { private IStatusChangeListener fContext; private StringButtonDialogField fFileNameField; private SelectionButtonDialogField fInternalButtonField; private StringButtonDialogField fPrefixField; private boolean fIsVariableEntry; private IStatus fNameStatus; private IStatus fPrefixStatus; private IPath fJARPath; /** * The file to which the archive path points to. * Only set when the file exists. */ private File fResolvedFile; /** * The path to which the archive variable points. * Null if invalid path or not resolvable. Must not exist. */ private IPath fFileVariablePath; private IWorkspaceRoot fRoot; private Control fSWTWidget; private CLabel fFullPathResolvedLabel; private CLabel fPrefixResolvedLabel; private IClasspathEntry fOldEntry; public SourceAttachmentBlock(IWorkspaceRoot root, IStatusChangeListener context, IClasspathEntry oldEntry) { fContext= context; fRoot= root; fOldEntry= oldEntry; // fIsVariableEntry specifies if the UI is for a variable entry fIsVariableEntry= (oldEntry.getEntryKind() == IClasspathEntry.CPE_VARIABLE); fNameStatus= new StatusInfo(); fPrefixStatus= new StatusInfo(); fJARPath= (oldEntry != null) ? oldEntry.getPath() : Path.EMPTY; SourceAttachmentAdapter adapter= new SourceAttachmentAdapter(); // create the dialog fields (no widgets yet) if (fIsVariableEntry) { fFileNameField= new VariablePathDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.varlabel")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.varbutton")); //$NON-NLS-1$ ((VariablePathDialogField)fFileNameField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.variable.button")); //$NON-NLS-1$ fPrefixField= new VariablePathDialogField(adapter); fPrefixField.setDialogFieldListener(adapter); fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varlabel")); //$NON-NLS-1$ fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.varbutton")); //$NON-NLS-1$ ((VariablePathDialogField)fPrefixField).setVariableButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.variable.button")); //$NON-NLS-1$ } else { fFileNameField= new StringButtonDialogField(adapter); fFileNameField.setDialogFieldListener(adapter); fFileNameField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.label")); //$NON-NLS-1$ fFileNameField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.filename.external.button")); //$NON-NLS-1$ fInternalButtonField= new SelectionButtonDialogField(SWT.PUSH); fInternalButtonField.setDialogFieldListener(adapter); fInternalButtonField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.filename.internal.button")); //$NON-NLS-1$ fPrefixField= new StringButtonDialogField(adapter); fPrefixField.setDialogFieldListener(adapter); fPrefixField.setLabelText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.label")); //$NON-NLS-1$ fPrefixField.setButtonLabel(NewWizardMessages.getString("SourceAttachmentBlock.prefix.button")); //$NON-NLS-1$ } // set the old settings setDefaults(); } public void setDefaults() { if (fOldEntry != null && fOldEntry.getSourceAttachmentPath() != null) { fFileNameField.setText(fOldEntry.getSourceAttachmentPath().toString()); } else { fFileNameField.setText(""); //$NON-NLS-1$ } if (fOldEntry != null && fOldEntry.getSourceAttachmentRootPath() != null) { fPrefixField.setText(fOldEntry.getSourceAttachmentRootPath().toString()); } else { fPrefixField.setText(""); //$NON-NLS-1$ } } /** * Gets the source attachment path chosen by the user */ public IPath getSourceAttachmentPath() { if (fFileNameField.getText().length() == 0) { return null; } return new Path(fFileNameField.getText()); } /** * Gets the source attachment root chosen by the user */ public IPath getSourceAttachmentRootPath() { if (getSourceAttachmentPath() == null) { return null; } else { return new Path(fPrefixField.getText()); } } /** * Creates the control */ public Control createControl(Composite parent) { PixelConverter converter= new PixelConverter(parent); fSWTWidget= parent; Composite composite= new Composite(parent, SWT.NONE); GridLayout layout= new GridLayout(); layout.marginHeight= 0; layout.marginWidth= 0; layout.numColumns= 4; composite.setLayout(layout); int widthHint= converter.convertWidthInCharsToPixels(fIsVariableEntry ? 50 : 60); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 4; Label message= new Label(composite, SWT.LEFT); message.setLayoutData(gd); message.setText(NewWizardMessages.getFormattedString("SourceAttachmentBlock.message", fJARPath.lastSegment())); //$NON-NLS-1$ if (fIsVariableEntry) { DialogField.createEmptySpace(composite, 1); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= widthHint; gd.horizontalSpan= 2; Label desc= new Label(composite, SWT.LEFT + SWT.WRAP); desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.filename.description")); //$NON-NLS-1$ desc.setLayoutData(gd); DialogField.createEmptySpace(composite, 1); } // archive name field fFileNameField.doFillIntoGrid(composite, 4); LayoutUtil.setWidthHint(fFileNameField.getTextControl(null), widthHint); LayoutUtil.setHorizontalGrabbing(fFileNameField.getTextControl(null)); if (!fIsVariableEntry) { // aditional 'browse workspace' button for normal jars DialogField.createEmptySpace(composite, 3); fInternalButtonField.doFillIntoGrid(composite, 1); } else { // label that shows the resolved path for variable jars DialogField.createEmptySpace(composite, 1); fFullPathResolvedLabel= new CLabel(composite, SWT.LEFT); fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); fFullPathResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); } // prefix description DialogField.createEmptySpace(composite, 1); gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.widthHint= widthHint; gd.horizontalSpan= 2; Label desc= new Label(composite, SWT.LEFT + SWT.WRAP); desc.setText(NewWizardMessages.getString("SourceAttachmentBlock.prefix.description")); //$NON-NLS-1$ desc.setLayoutData(gd); DialogField.createEmptySpace(composite, 1); // root path field fPrefixField.doFillIntoGrid(composite, 4); LayoutUtil.setWidthHint(fPrefixField.getTextControl(null), widthHint); if (fIsVariableEntry) { // label that shows the resolved path for variable jars DialogField.createEmptySpace(composite, 1); fPrefixResolvedLabel= new CLabel(composite, SWT.LEFT); fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false)); fPrefixResolvedLabel.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); DialogField.createEmptySpace(composite, 2); } fFileNameField.postSetFocusOnDialogField(parent.getDisplay()); WorkbenchHelp.setHelp(composite, IJavaHelpContextIds.SOURCE_ATTACHMENT_BLOCK); return composite; } private class SourceAttachmentAdapter implements IStringButtonAdapter, IDialogFieldListener { // -------- IStringButtonAdapter -------- public void changeControlPressed(DialogField field) { attachmentChangeControlPressed(field); } // ---------- IDialogFieldListener -------- public void dialogFieldChanged(DialogField field) { attachmentDialogFieldChanged(field); } } private void attachmentChangeControlPressed(DialogField field) { if (field == fFileNameField) { IPath jarFilePath= chooseExtJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } } else if (field == fPrefixField) { IPath prefixPath= choosePrefix(); if (prefixPath != null) { fPrefixField.setText(prefixPath.toString()); } } } // ---------- IDialogFieldListener -------- private void attachmentDialogFieldChanged(DialogField field) { if (field == fFileNameField) { fNameStatus= updateFileNameStatus(); } else if (field == fInternalButtonField) { IPath jarFilePath= chooseInternalJarFile(); if (jarFilePath != null) { fFileNameField.setText(jarFilePath.toString()); } return; } else if (field == fPrefixField) { fPrefixStatus= updatePrefixStatus(); } doStatusLineUpdate(); } private void doStatusLineUpdate() { fPrefixField.enableButton(canBrowsePrefix()); fFileNameField.enableButton(canBrowseFileName()); // set the resolved path for variable jars if (fFullPathResolvedLabel != null) { fFullPathResolvedLabel.setText(getResolvedLabelString(fFileNameField.getText(), true)); } if (fPrefixResolvedLabel != null) { fPrefixResolvedLabel.setText(getResolvedLabelString(fPrefixField.getText(), false)); } IStatus status= StatusUtil.getMostSevere(new IStatus[] { fNameStatus, fPrefixStatus }); fContext.statusChanged(status); } private boolean canBrowseFileName() { if (!fIsVariableEntry) { return true; } // to browse with a variable JAR, the variable name must point to a directory if (fFileVariablePath != null) { return fFileVariablePath.toFile().isDirectory(); } return false; } private boolean canBrowsePrefix() { // can browse when the archive name is poiting to a existing file // and (if variable) the prefix variable name is existing if (fResolvedFile != null) { if (fIsVariableEntry) { // prefix has valid format, is resolvable and not empty return fPrefixStatus.isOK() && fPrefixField.getText().length() > 0; } return true; } return false; } private String getResolvedLabelString(String path, boolean osPath) { IPath resolvedPath= getResolvedPath(new Path(path)); if (resolvedPath != null) { if (osPath) { return resolvedPath.toOSString(); } else { return resolvedPath.toString(); } } return ""; //$NON-NLS-1$ } private IPath getResolvedPath(IPath path) { if (path != null) { String varName= path.segment(0); if (varName != null) { IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { return varPath.append(path.removeFirstSegments(1)); } } } return null; } private IStatus updatePrefixStatus() { StatusInfo status= new StatusInfo(); String prefix= fPrefixField.getText(); if (prefix.length() == 0) { // no source attachment path return status; } else { if (!Path.EMPTY.isValidPath(prefix)) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.notvalid")); //$NON-NLS-1$ return status; } IPath path= new Path(prefix); if (fIsVariableEntry) { IPath resolvedPath= getResolvedPath(path); if (resolvedPath == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.varnotexists")); //$NON-NLS-1$ return status; } if (resolvedPath.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinvar")); //$NON-NLS-1$ return status; } } else { if (path.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.prefix.error.deviceinpath")); //$NON-NLS-1$ return status; } } } return status; } private IStatus updateFileNameStatus() { StatusInfo status= new StatusInfo(); fResolvedFile= null; fFileVariablePath= null; String fileName= fFileNameField.getText(); if (fileName.length() == 0) { // no source attachment return status; } else { if (!Path.EMPTY.isValidPath(fileName)) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$ return status; } IPath filePath= new Path(fileName); IPath resolvedPath; if (fIsVariableEntry) { if (filePath.getDevice() != null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.deviceinpath")); //$NON-NLS-1$ return status; } String varName= filePath.segment(0); if (varName == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.notvalid")); //$NON-NLS-1$ return status; } fFileVariablePath= JavaCore.getClasspathVariable(varName); if (fFileVariablePath == null) { status.setError(NewWizardMessages.getString("SourceAttachmentBlock.filename.error.varnotexists")); //$NON-NLS-1$ return status; } resolvedPath= fFileVariablePath.append(filePath.removeFirstSegments(1)); if (resolvedPath.isEmpty()) { status.setWarning(NewWizardMessages.getString("SourceAttachmentBlock.filename.warning.varempty")); //$NON-NLS-1$ return status; } File file= resolvedPath.toFile(); if (!file.isFile()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", resolvedPath.toOSString()); //$NON-NLS-1$ status.setWarning(message); return status; } fResolvedFile= file; } else { File file= filePath.toFile(); IResource res= fRoot.findMember(filePath); if (res != null) { file= res.getLocation().toFile(); } if (!file.isFile()) { String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.filename.error.filenotexists", filePath.toString()); //$NON-NLS-1$ status.setError(message); return status; } fResolvedFile= file; } } return status; } /* * Opens a dialog to choose a jar from the file system. */ private IPath chooseExtJarFile() { IPath currPath= new Path(fFileNameField.getText()); if (currPath.isEmpty()) { currPath= fJARPath; } IPath resolvedPath= currPath; if (fIsVariableEntry) { resolvedPath= getResolvedPath(currPath); if (resolvedPath == null) { resolvedPath= Path.EMPTY; } } if (ArchiveFileFilter.isArchivePath(resolvedPath)) { resolvedPath= resolvedPath.removeLastSegments(1); } FileDialog dialog= new FileDialog(getShell()); dialog.setText(NewWizardMessages.getString("SourceAttachmentBlock.extjardialog.text")); //$NON-NLS-1$ dialog.setFilterExtensions(new String[] {"*.jar;*.zip"}); //$NON-NLS-1$ dialog.setFilterPath(resolvedPath.toOSString()); String res= dialog.open(); if (res != null) { IPath returnPath= new Path(res).makeAbsolute(); if (fIsVariableEntry) { returnPath= modifyPath(returnPath, currPath.segment(0)); } return returnPath; } return null; } /* * Opens a dialog to choose an internal jar. */ private IPath chooseInternalJarFile() { String initSelection= fFileNameField.getText(); Class[] acceptedClasses= new Class[] { IFile.class }; TypedElementSelectionValidator validator= new TypedElementSelectionValidator(acceptedClasses, false); ViewerFilter filter= new ArchiveFileFilter(null); ILabelProvider lp= new WorkbenchLabelProvider(); ITreeContentProvider cp= new WorkbenchContentProvider(); IResource initSel= null; if (initSelection.length() > 0) { initSel= fRoot.findMember(new Path(initSelection)); } if (initSel == null) { initSel= fRoot.findMember(fJARPath); } ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), lp, cp); dialog.setAllowMultiple(false); dialog.setValidator(validator); dialog.addFilter(filter); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.intjardialog.message")); //$NON-NLS-1$ dialog.setInput(fRoot); dialog.setInitialSelection(initSel); if (dialog.open() == dialog.OK) { IFile file= (IFile) dialog.getFirstResult(); return file.getFullPath(); } return null; } /* * Opens a dialog to choose path in a zip file. */ private IPath choosePrefix() { if (fResolvedFile != null) { IPath currPath= new Path(fPrefixField.getText()); String initSelection= null; if (fIsVariableEntry) { IPath resolvedPath= getResolvedPath(currPath); if (resolvedPath != null) { initSelection= resolvedPath.toString(); } } else { initSelection= currPath.toString(); } try { ZipFile zipFile= new ZipFile(fResolvedFile); ZipContentProvider contentProvider= new ZipContentProvider(); contentProvider.setInitialInput(zipFile); ElementTreeSelectionDialog dialog= new ElementTreeSelectionDialog(getShell(), new ZipLabelProvider(), contentProvider); dialog.setAllowMultiple(false); dialog.setTitle(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.title")); //$NON-NLS-1$ dialog.setMessage(NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.message")); //$NON-NLS-1$ dialog.setInput(zipFile); dialog.setInitialSelection(contentProvider.getSelectedNode(initSelection)); if (dialog.open() == dialog.OK) { Object obj= dialog.getFirstResult(); IPath path= new Path(obj.toString()); if (fIsVariableEntry) { path= modifyPath(path, currPath.segment(0)); } return path; } } catch (IOException e) { String title= NewWizardMessages.getString("SourceAttachmentBlock.prefixdialog.error.title"); //$NON-NLS-1$ String message= NewWizardMessages.getFormattedString("SourceAttachmentBlock.prefixdialog.error.message", fResolvedFile.getPath()); //$NON-NLS-1$ MessageDialog.openError(getShell(), title, message); JavaPlugin.log(e); } } return null; } private Shell getShell() { if (fSWTWidget != null) { return fSWTWidget.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } /** * Takes a path and replaces the beginning with a variable name * (if the beginning matches with the variables value) */ private IPath modifyPath(IPath path, String varName) { if (varName == null || path == null) { return null; } if (path.isEmpty()) { return new Path(varName); } IPath varPath= JavaCore.getClasspathVariable(varName); if (varPath != null) { if (varPath.isPrefixOf(path)) { path= path.removeFirstSegments(varPath.segmentCount()); } else { path= new Path(path.lastSegment()); } } else { path= new Path(path.lastSegment()); } return new Path(varName).append(path); } /** * Creates a runnable that sets the source attachment by modifying the project's classpath. */ public IRunnableWithProgress getRunnable(final IJavaProject jproject, final Shell shell) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { boolean isExported= fOldEntry != null ? fOldEntry.isExported() : false; IClasspathEntry newEntry; if (fIsVariableEntry) { newEntry= JavaCore.newVariableEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported); } else { newEntry= JavaCore.newLibraryEntry(fJARPath, getSourceAttachmentPath(), getSourceAttachmentRootPath(), isExported); } IClasspathEntry[] entries= modifyClasspath(jproject, newEntry, shell); if (entries != null) { jproject.setRawClasspath(entries, monitor); } } catch (JavaModelException e) { throw new InvocationTargetException(e); } } }; } private IClasspathEntry[] modifyClasspath(IJavaProject jproject, IClasspathEntry newEntry, Shell shell) throws JavaModelException{ IClasspathEntry[] oldClasspath= jproject.getRawClasspath(); int nEntries= oldClasspath.length; ArrayList newEntries= new ArrayList(nEntries + 1); int entryKind= newEntry.getEntryKind(); IPath jarPath= newEntry.getPath(); boolean found= false; for (int i= 0; i < nEntries; i++) { IClasspathEntry curr= oldClasspath[i]; if (curr.getEntryKind() == entryKind && curr.getPath().equals(jarPath)) { // add modified entry newEntries.add(newEntry); found= true; } else { newEntries.add(curr); } } if (!found) { if (newEntry.getSourceAttachmentPath() == null || !putJarOnClasspathDialog(shell)) { return null; } // add new newEntries.add(newEntry); } return (IClasspathEntry[]) newEntries.toArray(new IClasspathEntry[newEntries.size()]); } private boolean putJarOnClasspathDialog(Shell shell) { final boolean[] result= new boolean[1]; shell.getDisplay().syncExec(new Runnable() { public void run() { String title= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.title"); //$NON-NLS-1$ String message= NewWizardMessages.getString("SourceAttachmentBlock.putoncpdialog.message"); //$NON-NLS-1$ result[0]= MessageDialog.openQuestion(JavaPlugin.getActiveWorkbenchShell(), title, message); } }); return result[0]; } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/wizards/buildpaths/VariablePathDialogField.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.wizards.buildpaths; import java.util.List; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.dialogs.StatusDialog; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.dialogfields.IStringButtonAdapter; import org.eclipse.jdt.internal.ui.wizards.dialogfields.StringButtonDialogField; public class VariablePathDialogField extends StringButtonDialogField { public static class ChooseVariableDialog extends StatusDialog implements ISelectionChangedListener, IDoubleClickListener { private VariableBlock fVariableBlock; public ChooseVariableDialog(Shell parent, String variableSelection) { super(parent); setTitle(NewWizardMessages.getString("VariablePathDialogField.variabledialog.title")); //$NON-NLS-1$ fVariableBlock= new VariableBlock(false, variableSelection); } protected Control createDialogArea(Composite parent) { Composite composite= (Composite) super.createDialogArea(parent); fVariableBlock.createContents(composite); fVariableBlock.addDoubleClickListener(this); fVariableBlock.addSelectionChangedListener(this); return composite; } protected void okPressed() { fVariableBlock.performOk(); super.okPressed(); } public String getSelectedVariable() { List elements= fVariableBlock.getSelectedElements(); return ((CPVariableElement) elements.get(0)).getName(); } /* * @see IDoubleClickListener#doubleClick(DoubleClickEvent) */ public void doubleClick(DoubleClickEvent event) { if (getStatus().isOK()) { okPressed(); } } /* (non-Javadoc) * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent) */ public void selectionChanged(SelectionChangedEvent event) { List elements= fVariableBlock.getSelectedElements(); StatusInfo status= new StatusInfo(); if (elements.size() != 1) { status.setError(""); //$NON-NLS-1$ } updateStatus(status); } /* * @see org.eclipse.jface.window.Window#configureShell(Shell) */ protected void configureShell(Shell newShell) { super.configureShell(newShell); WorkbenchHelp.setHelp(newShell, IJavaHelpContextIds.CHOOSE_VARIABLE_DIALOG); } } private Button fBrowseVariableButton; private String fVariableButtonLabel; public VariablePathDialogField(IStringButtonAdapter adapter) { super(adapter); } public void setVariableButtonLabel(String label) { fVariableButtonLabel= label; } // ------- layout helpers public Control[] doFillIntoGrid(Composite parent, int nColumns) { assertEnoughColumns(nColumns); Label label= getLabelControl(parent); label.setLayoutData(gridDataForLabel(1)); Text text= getTextControl(parent); text.setLayoutData(gridDataForText(nColumns - 3)); Button variableButton= getBrowseVariableControl(parent); variableButton.setLayoutData(gridDataForButton(variableButton, 1)); Button browseButton= getChangeControl(parent); browseButton.setLayoutData(gridDataForButton(browseButton, 1)); return new Control[] { label, text, variableButton, browseButton }; } public int getNumberOfControls() { return 4; } public Button getBrowseVariableControl(Composite parent) { if (fBrowseVariableButton == null) { assertCompositeNotNull(parent); fBrowseVariableButton= new Button(parent, SWT.PUSH); fBrowseVariableButton.setText(fVariableButtonLabel); fBrowseVariableButton.setEnabled(isEnabled()); fBrowseVariableButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) { chooseVariablePressed(); } public void widgetSelected(SelectionEvent e) { chooseVariablePressed(); } }); } return fBrowseVariableButton; } public IPath getPath() { return new Path(getText()); } public String getVariable() { IPath path= getPath(); if (!path.isEmpty()) { return path.segment(0); } return null; } public IPath getPathExtension() { return new Path(getText()).removeFirstSegments(1).setDevice(null); } public IPath getResolvedPath() { String variable= getVariable(); if (variable != null) { IPath path= JavaCore.getClasspathVariable(variable); if (path != null) { return path.append(getPathExtension()); } } return null; } private Shell getShell() { if (fBrowseVariableButton != null) { return fBrowseVariableButton.getShell(); } return JavaPlugin.getActiveWorkbenchShell(); } private void chooseVariablePressed() { String variable= getVariable(); ChooseVariableDialog dialog= new ChooseVariableDialog(getShell(), variable); if (dialog.open() == dialog.OK) { IPath newPath= new Path(dialog.getSelectedVariable()).append(getPathExtension()); setText(newPath.toString()); } } protected void updateEnableState() { super.updateEnableState(); if (isOkToUse(fBrowseVariableButton)) { fBrowseVariableButton.setEnabled(isEnabled()); } } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/JavaCapabilityConfigurationPage.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * Standard wizard page for creating new Java projects. This page can be used in * project creation wizards. The page shows UI to configure the project with a Java * build path and output location. On finish the page will also configure the Java nature. * <p> * This is a replacement for <code>NewJavaProjectWizardPage</code> with a cleaner API. * </p> * * @since 2.0 */ public class JavaCapabilityConfigurationPage extends NewElementWizardPage { private static final String PAGE_NAME= "JavaCapabilityConfigurationPage"; //$NON-NLS-1$ private IJavaProject fJavaProject; private BuildPathsBlock fBuildPathsBlock; /** * Creates a wizard page that can be used in a Java project creation wizard. * It contains UI to configure a the classpath and the output folder. * * <p> * After constructing, a call to <code>init</code> is required * </p> */ public JavaCapabilityConfigurationPage() { super(PAGE_NAME); fJavaProject= null; setTitle(NewWizardMessages.getString("JavaCapabilityConfigurationPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("JavaCapabilityConfigurationPage.description")); //$NON-NLS-1$ IStatusChangeListener listener= new IStatusChangeListener() { public void statusChanged(IStatus status) { updateStatus(status); } }; fBuildPathsBlock= new BuildPathsBlock(ResourcesPlugin.getWorkspace().getRoot(), listener, true); } /** * Initializes the page with the project and default classpaths. * <p> * The default classpath entries must correspond the the given project. * </p> * <p> * The caller of this method is responsible for creating the underlying project. The page will create the output, * source and library folders if required. * </p> * <p> * The project does not have to exist at the time of initialization, but must exist when executing the runnable * obtained by <code>getRunnable()</code>. * </p> * @param project The Java project. * @param entries The default classpath entries or <code>null</code> to let the page choose the default * @param path The folder to be taken as the default output path or <code>null</code> to let the page choose the default * @return overrideExistingClasspath If set to <code>true</code>, an existing '.classpath' file is ignored. If set to <code>false</code> * the given default classpath and output location is only used if no '.classpath' exists. */ public void init(IJavaProject jproject, IPath defaultOutputLocation, IClasspathEntry[] defaultEntries, boolean defaultsOverrideExistingClasspath) { if (!defaultsOverrideExistingClasspath && jproject.exists() && jproject.getProject().getFile(".classpath").exists()) { //$NON-NLS-1$ defaultOutputLocation= null; defaultEntries= null; } fBuildPathsBlock.init(jproject, defaultOutputLocation, defaultEntries); fJavaProject= jproject; } /* (non-Javadoc) * @see WizardPage#createControl */ public void createControl(Composite parent) { Control control= fBuildPathsBlock.createControl(parent); setControl(control); WorkbenchHelp.setHelp(control, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE); } /** * Returns the currently configured output location. Note that the returned path * might not be a valid path. * * @return the currently configured output location */ public IPath getOutputLocation() { return fBuildPathsBlock.getOutputLocation(); } /** * Returns the currently configured classpath. Note that the classpath might * not be valid. * * @return the currently configured classpath */ public IClasspathEntry[] getRawClassPath() { return fBuildPathsBlock.getRawClassPath(); } /** * Returns the Java project that was passed in <code>init</code> or <code>null</code> if the * page has not been initialized yet. * * @return the managed Java project or <code>null</code> */ public IJavaProject getJavaProject() { return fJavaProject; } /** * Returns the runnable that will create the Java project or <code>null</code> if the page has * not been initialized. The runnable sets the project's classpath and output location to the values * configured in the page and adds the Java nature if not set yet. The method requires that the * project is created and opened. * * @return the runnable that creates the new Java project */ public IRunnableWithProgress getRunnable() { if (getJavaProject() != null) { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { configureJavaProject(monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }; } return null; } /** * Adds the Java nature to the project (if not set yet) and configures the build classpath. * * @param monitor a progress monitor to report progress or <code>null</code> if * progress reporting is not desired */ public void configureJavaProject(IProgressMonitor monitor) throws CoreException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } int nSteps= 5; monitor.beginTask(NewWizardMessages.getString("JavaCapabilityConfigurationPage.op_desc"), nSteps); //$NON-NLS-1$ try { IProject project= getJavaProject().getProject(); fBuildPathsBlock.addJavaNature(project, new SubProgressMonitor(monitor, 1)); fBuildPathsBlock.configureJavaProject(new SubProgressMonitor(monitor, 5)); } finally { monitor.done(); } } }
22,508
Bug 22508 Add Variable Window Small/Not Persistant [build path]
1.It would be very useful if when you went to a java project -> properties it not only remembered that you were in Java Build Path but also that you were, for example in the "Libraries" page. Frequently, I have to go to a project and add a variable and switch pages to do so. 2. In the "Add Variable" option of the above listed page (Properties->Java Build Path-> Libraries) the variable list window is considerably to small for easy use and worse cannot be resized. 3. When going to "Extend..." of the above option, it would be convient to be able to simply double click an item/folder to expand it or select it rather than have to specifically select the tree expand box. Also, is there any reason this now uses a tree instead of the normal file browser as it was in Eclipse 1.0. (The tree is uneccesarily cluttered with non compatible files like .txt, instead of just .jar and .zip files). Thanks! ~Scott Admiraal ~IBM PvC - Telematics
resolved fixed
bf87a86
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-24T17:18:50Z
2002-08-17T07:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/ui/wizards/NewJavaProjectWizardPage.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.ui.wizards; import java.lang.reflect.InvocationTargetException; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IWorkspaceRoot; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.util.Assert; import org.eclipse.ui.dialogs.WizardNewProjectCreationPage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.preferences.NewJavaProjectPreferencePage; import org.eclipse.jdt.internal.ui.wizards.IStatusChangeListener; import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages; import org.eclipse.jdt.internal.ui.wizards.buildpaths.BuildPathsBlock; /** * Standard wizard page for creating new Java projects. This page can be used in * project creation wizards for projects and will configure the project with the * Java nature. This page also allows the user to configure the Java project's * output location for class files generated by the Java builder. * <p> * Whenever possible clients should use the class <code>JavaCapabilityConfigurationPage * </code> in favour of this class. * </p> */ public class NewJavaProjectWizardPage extends NewElementWizardPage { private static final String PAGE_NAME= "NewJavaProjectWizardPage"; //$NON-NLS-1$ private WizardNewProjectCreationPage fMainPage; private IPath fOutputLocation; private IClasspathEntry[] fClasspathEntries; private boolean fAddJRE; private BuildPathsBlock fBuildPathsBlock; private boolean fProjectModified; /** * Creates a Java project wizard creation page. * <p> * The Java project wizard reads project name and location from the main page. * </p> * * @param root the workspace root * @param mainpage the main page of the wizard */ public NewJavaProjectWizardPage(IWorkspaceRoot root, WizardNewProjectCreationPage mainpage) { super(PAGE_NAME); setTitle(NewWizardMessages.getString("NewJavaProjectWizardPage.title")); //$NON-NLS-1$ setDescription(NewWizardMessages.getString("NewJavaProjectWizardPage.description")); //$NON-NLS-1$ fMainPage= mainpage; IStatusChangeListener listener= new IStatusChangeListener() { public void statusChanged(IStatus status) { updateStatus(status); } }; fBuildPathsBlock= new BuildPathsBlock(root, listener, true); fProjectModified= true; fOutputLocation= null; fClasspathEntries= null; fAddJRE= false; } /** * Sets the default output location to be used for the new Java project. * This is the path of the folder (with the project) into which the Java builder * will generate binary class files corresponding to the project's Java source * files. * <p> * The wizard will create this folder if required. * </p> * <p> * The default classpath will be applied when <code>initBuildPaths</code> is * called. This is done automatically when the page becomes visible and * the project or the default paths have changed. * </p> * * @param path the folder to be taken as the default output path */ public void setDefaultOutputFolder(IPath path) { fOutputLocation= path; setProjectModified(); } /** * Sets the default classpath to be used for the new Java project. * <p> * The caller of this method is responsible for creating the classpath entries * for the <code>IJavaProject</code> that corresponds to the created project. * The caller is responsible for creating any new folders that might be mentioned * on the classpath. * </p> * <p> * The default output location will be applied when <code>initBuildPaths</code> is * called. This is done automatically when the page becomes visible and * the project or the default paths have changed. * </p> * * @param entries the default classpath entries * @param appendDefaultJRE <code>true</code> a variable entry for the * default JRE (specified in the preferences) will be added to the classpath. */ public void setDefaultClassPath(IClasspathEntry[] entries, boolean appendDefaultJRE) { if (entries != null && appendDefaultJRE) { IClasspathEntry[] jreEntry= NewJavaProjectPreferencePage.getDefaultJRELibrary(); IClasspathEntry[] newEntries= new IClasspathEntry[entries.length + jreEntry.length]; System.arraycopy(entries, 0, newEntries, 0, entries.length); System.arraycopy(jreEntry, 0, newEntries, entries.length, jreEntry.length); entries= newEntries; } fClasspathEntries= entries; fAddJRE= appendDefaultJRE; setProjectModified(); } /** * Sets the project state to modified. Doing so will initialize the page * the next time it becomes visible. * * @since 2.0 */ public void setProjectModified() { fProjectModified= true; } /** * Returns the project handle. Subclasses should override this * method if they don't provide a main page or if they provide * their own main page implementation. * * @return the project handle */ protected IProject getProjectHandle() { Assert.isNotNull(fMainPage); return fMainPage.getProjectHandle(); } /** * Returns the project locaction path. Subclasses should override this * method if they don't provide a main page or if they provide * their own main page implementation. * * @return the project location path */ protected IPath getLocationPath() { Assert.isNotNull(fMainPage); return fMainPage.getLocationPath(); } /** * Returns the Java project handle by converting the result of * <code>getProjectHandle()</code> into a Java project. * * @return the Java project handle * @see #getProjectHandle() */ public IJavaProject getNewJavaProject() { return JavaCore.create(getProjectHandle()); } /* (non-Javadoc) * @see WizardPage#createControl */ public void createControl(Composite parent) { Control control= fBuildPathsBlock.createControl(parent); setControl(control); WorkbenchHelp.setHelp(control, IJavaHelpContextIds.NEW_JAVAPROJECT_WIZARD_PAGE); } /** * Forces the initialization of the Java project page. Default classpath or buildpath * will be used if set. The initialization should only be performed when the project * or default paths have changed. Toggeling back and forward the pages without * changes should not re-initialize the page, as changes from the user will be * overwritten. * * @since 2.0 */ protected void initBuildPaths() { fBuildPathsBlock.init(getNewJavaProject(), fOutputLocation, fClasspathEntries); } /** * Extend this method to set a user defined default classpath or output location. * The method <code>initBuildPaths</code> is called when the page becomes * visible the first time or the project or the default paths have changed. * * @param visible if <code>true</code> the page becomes visible; otherwise * it becomes invisible */ public void setVisible(boolean visible) { if (visible) { // evaluate if a initialization is required if (fProjectModified || isNewProjectHandle()) { // only initialize the project when needed initBuildPaths(); fProjectModified= false; } } super.setVisible(visible); } private boolean isNewProjectHandle() { IProject oldProject= fBuildPathsBlock.getJavaProject().getProject(); return !oldProject.equals(getProjectHandle()); } /** * Returns the currently configured output location. Note that the returned path * might not be valid. * * @return the configured output location * * @since 2.0 */ public IPath getOutputLocation() { return fBuildPathsBlock.getOutputLocation(); } /** * Returns the currently configured classpath. Note that the classpath might * not be valid. * * @return the configured classpath * * @since 2.0 */ public IClasspathEntry[] getRawClassPath() { return fBuildPathsBlock.getRawClassPath(); } /** * Returns the runnable that will create the Java project. The runnable will create * and open the project if needed. The runnable will add the Java nature to the * project, and set the project's classpath and output location. * <p> * To create the new java project, execute this runnable * </p> * * @return the runnable */ public IRunnableWithProgress getRunnable() { return new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { if (monitor == null) { monitor= new NullProgressMonitor(); } monitor.beginTask(NewWizardMessages.getString("NewJavaProjectWizardPage.op_desc"), 10); //$NON-NLS-1$ int workLeft= 10; // initialize if needed if (fProjectModified || isNewProjectHandle()) { initBuildPaths(); } // create the project try { fBuildPathsBlock.createProject(getProjectHandle(), getLocationPath(), new SubProgressMonitor(monitor, 2)); fBuildPathsBlock.addJavaNature(getProjectHandle(), new SubProgressMonitor(monitor, 2)); fBuildPathsBlock.configureJavaProject(new SubProgressMonitor(monitor, 6)); } catch (CoreException e) { throw new InvocationTargetException(e); } finally { monitor.done(); } } }; } }
24,031
Bug 24031 CompilerPreferencePage has strange temps
there're 4 locals called: fTaskTagsStatus, fResourceFilterStatus, fMaxNumberProblemsStatus, fComplianceStatus the first 3 are not even read
resolved fixed
8009c8c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-25T09:35:07Z
2002-09-24T15:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/preferences/CompilerPreferencePage.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.preferences; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Hashtable; import java.util.StringTokenizer; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.IWorkspace; import org.eclipse.core.resources.IncrementalProjectBuilder; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.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.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.preference.PreferencePage; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPreferencePage; import org.eclipse.ui.help.WorkbenchHelp; import org.eclipse.jdt.core.JavaConventions; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.dialogs.StatusInfo; import org.eclipse.jdt.internal.ui.dialogs.StatusUtil; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.TabFolderLayout; import org.eclipse.jdt.internal.ui.wizards.dialogfields.LayoutUtil; /* * The page for setting the compiler options. */ public class CompilerPreferencePage extends PreferencePage implements IWorkbenchPreferencePage { // Preference store keys, see JavaCore.getOptions private static final String PREF_LOCAL_VARIABLE_ATTR= JavaCore.COMPILER_LOCAL_VARIABLE_ATTR; private static final String PREF_LINE_NUMBER_ATTR= JavaCore.COMPILER_LINE_NUMBER_ATTR; private static final String PREF_SOURCE_FILE_ATTR= JavaCore.COMPILER_SOURCE_FILE_ATTR; private static final String PREF_CODEGEN_UNUSED_LOCAL= JavaCore.COMPILER_CODEGEN_UNUSED_LOCAL; private static final String PREF_CODEGEN_TARGET_PLATFORM= JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; private static final String PREF_PB_UNREACHABLE_CODE= JavaCore.COMPILER_PB_UNREACHABLE_CODE; private static final String PREF_PB_INVALID_IMPORT= JavaCore.COMPILER_PB_INVALID_IMPORT; private static final String PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD= JavaCore.COMPILER_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD; private static final String PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME= JavaCore.COMPILER_PB_METHOD_WITH_CONSTRUCTOR_NAME; private static final String PREF_PB_DEPRECATION= JavaCore.COMPILER_PB_DEPRECATION; private static final String PREF_PB_HIDDEN_CATCH_BLOCK= JavaCore.COMPILER_PB_HIDDEN_CATCH_BLOCK; private static final String PREF_PB_UNUSED_LOCAL= JavaCore.COMPILER_PB_UNUSED_LOCAL; private static final String PREF_PB_UNUSED_PARAMETER= JavaCore.COMPILER_PB_UNUSED_PARAMETER; private static final String PREF_PB_SYNTHETIC_ACCESS_EMULATION= JavaCore.COMPILER_PB_SYNTHETIC_ACCESS_EMULATION; private static final String PREF_PB_NON_EXTERNALIZED_STRINGS= JavaCore.COMPILER_PB_NON_NLS_STRING_LITERAL; private static final String PREF_PB_ASSERT_AS_IDENTIFIER= JavaCore.COMPILER_PB_ASSERT_IDENTIFIER; private static final String PREF_PB_MAX_PER_UNIT= JavaCore.COMPILER_PB_MAX_PER_UNIT; private static final String PREF_PB_UNUSED_IMPORT= JavaCore.COMPILER_PB_UNUSED_IMPORT; private static final String PREF_PB_STATIC_ACCESS_RECEIVER= JavaCore.COMPILER_PB_STATIC_ACCESS_RECEIVER; private static final String PREF_SOURCE_COMPATIBILITY= JavaCore.COMPILER_SOURCE; private static final String PREF_COMPLIANCE= JavaCore.COMPILER_COMPLIANCE; private static final String PREF_RESOURCE_FILTER= JavaCore.CORE_JAVA_BUILD_RESOURCE_COPY_FILTER; private static final String PREF_BUILD_INVALID_CLASSPATH= JavaCore.CORE_JAVA_BUILD_INVALID_CLASSPATH; private static final String PREF_PB_INCOMPLETE_BUILDPATH= JavaCore.CORE_INCOMPLETE_CLASSPATH; private static final String PREF_PB_CIRCULAR_BUILDPATH= JavaCore.CORE_CIRCULAR_CLASSPATH; private static final String PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE= JavaCore.COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE; private static final String PREF_COMPILER_TASK_TAGS= JavaCore.COMPILER_TASK_TAGS; private static final String INTR_DEFAULT_COMPLIANCE= "internal.default.compliance"; //$NON-NLS-1$ // values private static final String GENERATE= JavaCore.GENERATE; private static final String DO_NOT_GENERATE= JavaCore.DO_NOT_GENERATE; private static final String PRESERVE= JavaCore.PRESERVE; private static final String OPTIMIZE_OUT= JavaCore.OPTIMIZE_OUT; private static final String VERSION_1_1= JavaCore.VERSION_1_1; private static final String VERSION_1_2= JavaCore.VERSION_1_2; private static final String VERSION_1_3= JavaCore.VERSION_1_3; private static final String VERSION_1_4= JavaCore.VERSION_1_4; private static final String ERROR= JavaCore.ERROR; private static final String WARNING= JavaCore.WARNING; private static final String IGNORE= JavaCore.IGNORE; private static final String ABORT= JavaCore.ABORT; private static final String ENABLED= JavaCore.ENABLED; private static final String DISABLED= JavaCore.DISABLED; private static final String DEFAULT= "default"; //$NON-NLS-1$ private static final String USER= "user"; //$NON-NLS-1$ private static String[] getAllKeys() { return new String[] { PREF_LOCAL_VARIABLE_ATTR, PREF_LINE_NUMBER_ATTR, PREF_SOURCE_FILE_ATTR, PREF_CODEGEN_UNUSED_LOCAL, PREF_CODEGEN_TARGET_PLATFORM, PREF_PB_UNREACHABLE_CODE, PREF_PB_INVALID_IMPORT, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, PREF_PB_DEPRECATION, PREF_PB_HIDDEN_CATCH_BLOCK, PREF_PB_UNUSED_LOCAL, PREF_PB_UNUSED_PARAMETER, PREF_PB_SYNTHETIC_ACCESS_EMULATION, PREF_PB_NON_EXTERNALIZED_STRINGS, PREF_PB_ASSERT_AS_IDENTIFIER, PREF_PB_UNUSED_IMPORT, PREF_PB_MAX_PER_UNIT, PREF_SOURCE_COMPATIBILITY, PREF_COMPLIANCE, PREF_RESOURCE_FILTER, PREF_BUILD_INVALID_CLASSPATH, PREF_PB_STATIC_ACCESS_RECEIVER, PREF_PB_INCOMPLETE_BUILDPATH, PREF_PB_CIRCULAR_BUILDPATH, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, PREF_COMPILER_TASK_TAGS }; } /** * Initializes the current options (read from preference store) */ public static void initDefaults(IPreferenceStore store) { } private static class ControlData { private String fKey; private String[] fValues; public ControlData(String key, String[] values) { fKey= key; fValues= values; } public String getKey() { return fKey; } public String getValue(boolean selection) { int index= selection ? 0 : 1; return fValues[index]; } public String getValue(int index) { return fValues[index]; } public int getSelection(String value) { for (int i= 0; i < fValues.length; i++) { if (value.equals(fValues[i])) { return i; } } throw new IllegalArgumentException(); } } private Hashtable fWorkingValues; private ArrayList fCheckBoxes; private ArrayList fComboBoxes; private ArrayList fTextBoxes; private SelectionListener fSelectionListener; private ModifyListener fTextModifyListener; private ArrayList fComplianceControls; IStatus fComplianceStatus, fMaxNumberProblemsStatus, fResourceFilterStatus, fTaskTagsStatus; public CompilerPreferencePage() { setPreferenceStore(JavaPlugin.getDefault().getPreferenceStore()); setDescription(JavaUIMessages.getString("CompilerPreferencePage.description")); //$NON-NLS-1$ fWorkingValues= JavaCore.getOptions(); fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance()); fCheckBoxes= new ArrayList(); fComboBoxes= new ArrayList(); fTextBoxes= new ArrayList(2); fComplianceControls= new ArrayList(); fSelectionListener= new SelectionListener() { public void widgetDefaultSelected(SelectionEvent e) {} public void widgetSelected(SelectionEvent e) { controlChanged(e.widget); } }; fTextModifyListener= new ModifyListener() { public void modifyText(ModifyEvent e) { textChanged((Text) e.widget); } }; fComplianceStatus= new StatusInfo(); fMaxNumberProblemsStatus= new StatusInfo(); fResourceFilterStatus= new StatusInfo(); fTaskTagsStatus= new StatusInfo(); } /** * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) */ public void init(IWorkbench workbench) { } /** * @see PreferencePage#createControl(Composite) */ public void createControl(Composite parent) { // added for 1GEUGE6: ITPJUI:WIN2000 - Help is the same on all preference pages super.createControl(parent); WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.COMPILER_PREFERENCE_PAGE); } /** * @see PreferencePage#createContents(Composite) */ protected Control createContents(Composite parent) { initializeDialogUnits(parent); TabFolder folder= new TabFolder(parent, SWT.NONE); folder.setLayout(new TabFolderLayout()); folder.setLayoutData(new GridData(GridData.FILL_BOTH)); Composite warningsComposite= createWarningsTabContent(folder); Composite markersComposite= createMarkersTabContent(folder); Composite codeGenComposite= createCodeGenTabContent(folder); Composite complianceComposite= createComplianceTabContent(folder); Composite othersComposite= createOthersTabContent(folder); TabItem item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.tabtitle")); //$NON-NLS-1$ item.setControl(warningsComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.tabtitle")); //$NON-NLS-1$ item.setControl(markersComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.generation.tabtitle")); //$NON-NLS-1$ item.setControl(codeGenComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.compliance.tabtitle")); //$NON-NLS-1$ item.setControl(complianceComposite); item= new TabItem(folder, SWT.NONE); item.setText(JavaUIMessages.getString("CompilerPreferencePage.others.tabtitle")); //$NON-NLS-1$ item.setControl(othersComposite); validateSettings(null, null); return folder; } private Composite createMarkersTabContent(TabFolder folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$ }; String[] enabledDisabled= new String[] { ENABLED, DISABLED }; Composite markersComposite= new Composite(folder, SWT.NULL); markersComposite.setLayout(new GridLayout()); GridLayout layout= new GridLayout(); layout.numColumns= 2; Group group= new Group(markersComposite, SWT.NONE); group.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.deprecated.label")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); int indent= convertWidthInCharsToPixels(2); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_PB_DEPRECATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_deprecation_in_deprecation.label"); //$NON-NLS-1$ addCheckBox(group, label, PREF_COMPILER_PB_DEPRECATION_IN_DEPRECATED_CODE, enabledDisabled, indent); layout= new GridLayout(); layout.numColumns= 1; group= new Group(markersComposite, SWT.NONE); group.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.taskmarkers.label")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); label= JavaUIMessages.getString("CompilerPreferencePage.pb_todo_comments.label"); //$NON-NLS-1$ Text text= addTextField(group, label, PREF_COMPILER_TASK_TAGS); GridData gd= (GridData) text.getLayoutData(); gd.grabExcessHorizontalSpace= true; gd.widthHint= convertWidthInCharsToPixels(10); layout= new GridLayout(); layout.numColumns= 2; group= new Group(markersComposite, SWT.NONE); group.setText(JavaUIMessages.getString("CompilerPreferencePage.markers.nls.label")); group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); group.setLayout(layout); label= JavaUIMessages.getString("CompilerPreferencePage.pb_non_externalized_strings.label"); //$NON-NLS-1$ addComboBox(group, label, PREF_PB_NON_EXTERNALIZED_STRINGS, errorWarningIgnore, errorWarningIgnoreLabels, 0); return markersComposite; } private Composite createOthersTabContent(TabFolder folder) { String[] abortIgnoreValues= new String[] { ABORT, IGNORE }; String[] errorWarning= new String[] { ERROR, WARNING }; String[] errorWarningLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning") //$NON-NLS-1$ }; GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite othersComposite= new Composite(folder, SWT.NULL); othersComposite.setLayout(layout); Label description= new Label(othersComposite, SWT.WRAP); description.setText(JavaUIMessages.getString("CompilerPreferencePage.build_warnings.description")); //$NON-NLS-1$ GridData gd= new GridData(GridData.FILL_HORIZONTAL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; // gd.widthHint= convertWidthInCharsToPixels(50); description.setLayoutData(gd); Composite combos= new Composite(othersComposite, SWT.NULL); gd= new GridData(GridData.FILL | GridData.GRAB_HORIZONTAL); gd.horizontalSpan= 2; combos.setLayoutData(gd); GridLayout cl= new GridLayout(); cl.numColumns=2; cl.marginWidth= 0; cl.marginHeight= 0; combos.setLayout(cl); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_incomplete_build_path.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_INCOMPLETE_BUILDPATH, errorWarning, errorWarningLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_build_path_cycles.label"); //$NON-NLS-1$ addComboBox(combos, label, PREF_PB_CIRCULAR_BUILDPATH, errorWarning, errorWarningLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.build_invalid_classpath.label"); //$NON-NLS-1$ addCheckBox(othersComposite, label, PREF_BUILD_INVALID_CLASSPATH, abortIgnoreValues, 0); description= new Label(othersComposite, SWT.WRAP); description.setText(JavaUIMessages.getString("CompilerPreferencePage.resource_filter.description")); //$NON-NLS-1$ gd= new GridData(GridData.FILL); gd.horizontalSpan= 2; gd.widthHint= convertWidthInCharsToPixels(60); description.setLayoutData(gd); label= JavaUIMessages.getString("CompilerPreferencePage.resource_filter.label"); //$NON-NLS-1$ Text text= addTextField(othersComposite, label, PREF_RESOURCE_FILTER); gd= (GridData) text.getLayoutData(); gd.grabExcessHorizontalSpace= true; gd.widthHint= convertWidthInCharsToPixels(10); return othersComposite; } private Composite createWarningsTabContent(Composite folder) { String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$ }; GridLayout layout= new GridLayout(); layout.numColumns= 2; layout.verticalSpacing= 2; Composite warningsComposite= new Composite(folder, SWT.NULL); warningsComposite.setLayout(layout); Label description= new Label(warningsComposite, SWT.WRAP); description.setText(JavaUIMessages.getString("CompilerPreferencePage.warnings.description")); //$NON-NLS-1$ GridData gd= new GridData(); gd.horizontalSpan= 2; gd.widthHint= convertWidthInCharsToPixels(50); description.setLayoutData(gd); String label= JavaUIMessages.getString("CompilerPreferencePage.pb_unreachable_code.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNREACHABLE_CODE, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_invalid_import.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_INVALID_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_local.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_LOCAL, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_overriding_pkg_dflt.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_OVERRIDING_PACKAGE_DEFAULT_METHOD, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_method_naming.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_METHOD_WITH_CONSTRUCTOR_NAME, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_hidden_catchblock.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_HIDDEN_CATCH_BLOCK, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_imports.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_IMPORT, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_unused_parameter.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_UNUSED_PARAMETER, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_static_access_receiver.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_STATIC_ACCESS_RECEIVER, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_synth_access_emul.label"); //$NON-NLS-1$ addComboBox(warningsComposite, label, PREF_PB_SYNTHETIC_ACCESS_EMULATION, errorWarningIgnore, errorWarningIgnoreLabels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.pb_max_per_unit.label"); //$NON-NLS-1$ Text text= addTextField(warningsComposite, label, PREF_PB_MAX_PER_UNIT); text.setTextLimit(6); return warningsComposite; } private Composite createCodeGenTabContent(Composite folder) { String[] generateValues= new String[] { GENERATE, DO_NOT_GENERATE }; GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite codeGenComposite= new Composite(folder, SWT.NULL); codeGenComposite.setLayout(layout); String label= JavaUIMessages.getString("CompilerPreferencePage.variable_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_LOCAL_VARIABLE_ATTR, generateValues, 0); label= JavaUIMessages.getString("CompilerPreferencePage.line_number_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_LINE_NUMBER_ATTR, generateValues, 0); label= JavaUIMessages.getString("CompilerPreferencePage.source_file_attr.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_SOURCE_FILE_ATTR, generateValues, 0); label= JavaUIMessages.getString("CompilerPreferencePage.codegen_unused_local.label"); //$NON-NLS-1$ addCheckBox(codeGenComposite, label, PREF_CODEGEN_UNUSED_LOCAL, new String[] { PRESERVE, OPTIMIZE_OUT }, 0); return codeGenComposite; } private Composite createComplianceTabContent(Composite folder) { GridLayout layout= new GridLayout(); layout.numColumns= 2; Composite complianceComposite= new Composite(folder, SWT.NULL); complianceComposite.setLayout(layout); String[] values34= new String[] { VERSION_1_3, VERSION_1_4 }; String[] values34Labels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.version13"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version14") //$NON-NLS-1$ }; String label= JavaUIMessages.getString("CompilerPreferencePage.compiler_compliance.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_COMPLIANCE, values34, values34Labels, 0); label= JavaUIMessages.getString("CompilerPreferencePage.default_settings.label"); //$NON-NLS-1$ addCheckBox(complianceComposite, label, INTR_DEFAULT_COMPLIANCE, new String[] { DEFAULT, USER }, 0); int indent= convertWidthInCharsToPixels(2); Control[] otherChildren= complianceComposite.getChildren(); String[] values14= new String[] { VERSION_1_1, VERSION_1_2, VERSION_1_3, VERSION_1_4 }; String[] values14Labels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.version11"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version12"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version13"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.version14") //$NON-NLS-1$ }; label= JavaUIMessages.getString("CompilerPreferencePage.codegen_targetplatform.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_CODEGEN_TARGET_PLATFORM, values14, values14Labels, indent); label= JavaUIMessages.getString("CompilerPreferencePage.source_compatibility.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_SOURCE_COMPATIBILITY, values34, values34Labels, indent); String[] errorWarningIgnore= new String[] { ERROR, WARNING, IGNORE }; String[] errorWarningIgnoreLabels= new String[] { JavaUIMessages.getString("CompilerPreferencePage.error"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.warning"), //$NON-NLS-1$ JavaUIMessages.getString("CompilerPreferencePage.ignore") //$NON-NLS-1$ }; label= JavaUIMessages.getString("CompilerPreferencePage.pb_assert_as_identifier.label"); //$NON-NLS-1$ addComboBox(complianceComposite, label, PREF_PB_ASSERT_AS_IDENTIFIER, errorWarningIgnore, errorWarningIgnoreLabels, indent); Control[] allChildren= complianceComposite.getChildren(); fComplianceControls.addAll(Arrays.asList(allChildren)); fComplianceControls.removeAll(Arrays.asList(otherChildren)); return complianceComposite; } private void addCheckBox(Composite parent, String label, String key, String[] values, int indent) { ControlData data= new ControlData(key, values); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL); gd.horizontalSpan= 2; gd.horizontalIndent= indent; Button checkBox= new Button(parent, SWT.CHECK); checkBox.setText(label); checkBox.setData(data); checkBox.setLayoutData(gd); checkBox.addSelectionListener(fSelectionListener); String currValue= (String)fWorkingValues.get(key); checkBox.setSelection(data.getSelection(currValue) == 0); fCheckBoxes.add(checkBox); } private void addComboBox(Composite parent, String label, String key, String[] values, String[] valueLabels, int indent) { ControlData data= new ControlData(key, values); GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING); gd.horizontalIndent= indent; Label labelControl= new Label(parent, SWT.LEFT | SWT.WRAP); labelControl.setText(label); labelControl.setLayoutData(gd); Combo comboBox= new Combo(parent, SWT.READ_ONLY); comboBox.setItems(valueLabels); comboBox.setData(data); comboBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); comboBox.addSelectionListener(fSelectionListener); String currValue= (String)fWorkingValues.get(key); comboBox.select(data.getSelection(currValue)); fComboBoxes.add(comboBox); } private Text addTextField(Composite parent, String label, String key) { Label labelControl= new Label(parent, SWT.NONE); labelControl.setText(label); labelControl.setLayoutData(new GridData()); Text textBox= new Text(parent, SWT.BORDER | SWT.SINGLE); textBox.setData(key); textBox.setLayoutData(new GridData()); String currValue= (String) fWorkingValues.get(key); textBox.setText(currValue); textBox.addModifyListener(fTextModifyListener); textBox.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); fTextBoxes.add(textBox); return textBox; } private void controlChanged(Widget widget) { ControlData data= (ControlData) widget.getData(); String newValue= null; if (widget instanceof Button) { newValue= data.getValue(((Button)widget).getSelection()); } else if (widget instanceof Combo) { newValue= data.getValue(((Combo)widget).getSelectionIndex()); } else { return; } fWorkingValues.put(data.getKey(), newValue); validateSettings(data.getKey(), newValue); } private void textChanged(Text textControl) { String key= (String) textControl.getData(); String number= textControl.getText(); fWorkingValues.put(key, number); validateSettings(key, number); } private boolean checkValue(String key, String value) { return value.equals(fWorkingValues.get(key)); } /* (non-javadoc) * Update fields and validate. * @param changedKey Key that changed, or null, if all changed. */ private void validateSettings(String changedKey, String newValue) { if (changedKey != null) { if (INTR_DEFAULT_COMPLIANCE.equals(changedKey)) { updateComplianceEnableState(); if (DEFAULT.equals(newValue)) { updateComplianceDefaultSettings(); } } else if (PREF_COMPLIANCE.equals(changedKey)) { if (checkValue(INTR_DEFAULT_COMPLIANCE, DEFAULT)) { updateComplianceDefaultSettings(); } } else if (PREF_SOURCE_COMPATIBILITY.equals(changedKey) || PREF_CODEGEN_TARGET_PLATFORM.equals(changedKey) || PREF_PB_ASSERT_AS_IDENTIFIER.equals(changedKey)) { fComplianceStatus= validateCompliance(); } else if (!PREF_PB_MAX_PER_UNIT.equals(changedKey)) { fMaxNumberProblemsStatus= validateMaxNumberProblems(); } else if (!PREF_RESOURCE_FILTER.equals(changedKey)) { fResourceFilterStatus= validateResourceFilters(); } else if (!PREF_COMPILER_TASK_TAGS.equals(changedKey)) { fTaskTagsStatus= validateTaskTags(); } else { return; } } else { updateComplianceEnableState(); } IStatus fComplianceStatus= validateCompliance(); IStatus fMaxNumberProblemsStatus= validateMaxNumberProblems(); IStatus fResourceFilterStatus= validateResourceFilters(); IStatus fTaskTagsStatus= validateTaskTags(); IStatus status= StatusUtil.getMostSevere(new IStatus[] { fComplianceStatus, validateMaxNumberProblems(), validateResourceFilters(), validateTaskTags() }); updateStatus(status); } private IStatus validateCompliance() { StatusInfo status= new StatusInfo(); if (checkValue(PREF_COMPLIANCE, VERSION_1_3)) { if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.cpl13src14.error")); //$NON-NLS-1$ return status; } else if (checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.cpl13trg14.error")); //$NON-NLS-1$ return status; } } if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { if (!checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.src14asrterr.error")); //$NON-NLS-1$ return status; } } if (checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4)) { if (!checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4)) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.src14tgt14.error")); //$NON-NLS-1$ return status; } } return status; } private IStatus validateMaxNumberProblems() { String number= (String) fWorkingValues.get(PREF_PB_MAX_PER_UNIT); StatusInfo status= new StatusInfo(); if (number.length() == 0) { status.setError(JavaUIMessages.getString("CompilerPreferencePage.empty_input")); //$NON-NLS-1$ } else { try { int value= Integer.parseInt(number); if (value <= 0) { status.setError(JavaUIMessages.getFormattedString("CompilerPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } catch (NumberFormatException e) { status.setError(JavaUIMessages.getFormattedString("CompilerPreferencePage.invalid_input", number)); //$NON-NLS-1$ } } return status; } private IStatus validateResourceFilters() { String text= (String) fWorkingValues.get(PREF_RESOURCE_FILTER); IWorkspace workspace= ResourcesPlugin.getWorkspace(); String[] filters= getFilters(text); for (int i= 0; i < filters.length; i++) { String fileName= filters[i].replace('*', 'x'); int resourceType= IResource.FILE; int lastCharacter= fileName.length() - 1; if (lastCharacter >= 0 && fileName.charAt(lastCharacter) == '/') { fileName= fileName.substring(0, lastCharacter); resourceType= IResource.FOLDER; } IStatus status= workspace.validateName(fileName, resourceType); if (status.matches(IStatus.ERROR)) { String message= JavaUIMessages.getFormattedString("CompilerPreferencePage.filter.invalidsegment.error", status.getMessage()); //$NON-NLS-1$ return new StatusInfo(IStatus.ERROR, message); } } return new StatusInfo(); } private IStatus validateTaskTags() { String text= (String) fWorkingValues.get(PREF_COMPILER_TASK_TAGS); IWorkspace workspace= ResourcesPlugin.getWorkspace(); String[] tags= getFilters(text); for (int i= 0; i < tags.length; i++) { if (tags[i].length() == 0) { String message= JavaUIMessages.getString("CompilerPreferencePage.task.invalidsegment.error"); //$NON-NLS-1$ return new StatusInfo(IStatus.ERROR, message); } } return new StatusInfo(); } private String[] getFilters(String text) { StringTokenizer tok= new StringTokenizer(text, ","); //$NON-NLS-1$ int nTokens= tok.countTokens(); String[] res= new String[nTokens]; for (int i= 0; i < res.length; i++) { res[i]= tok.nextToken(); } return res; } /* * Update the compliance controls' enable state */ private void updateComplianceEnableState() { boolean enabled= checkValue(INTR_DEFAULT_COMPLIANCE, USER); for (int i= fComplianceControls.size() - 1; i >= 0; i--) { Control curr= (Control) fComplianceControls.get(i); curr.setEnabled(enabled); } } /* * Set the default compliance values derived from the chosen level */ private void updateComplianceDefaultSettings() { Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE); if (VERSION_1_3.equals(complianceLevel)) { fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE); fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_3); fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1); } else if (VERSION_1_4.equals(complianceLevel)) { fWorkingValues.put(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR); fWorkingValues.put(PREF_SOURCE_COMPATIBILITY, VERSION_1_4); fWorkingValues.put(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4); } updateControls(); } /* * Evaluate if the current compliance setting correspond to a default setting */ private String getCurrentCompliance() { Object complianceLevel= fWorkingValues.get(PREF_COMPLIANCE); if ((VERSION_1_3.equals(complianceLevel) && checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, IGNORE) && checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_3) && checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_1)) || (VERSION_1_4.equals(complianceLevel) && checkValue(PREF_PB_ASSERT_AS_IDENTIFIER, ERROR) && checkValue(PREF_SOURCE_COMPATIBILITY, VERSION_1_4) && checkValue(PREF_CODEGEN_TARGET_PLATFORM, VERSION_1_4))) { return DEFAULT; } return USER; } /* * @see IPreferencePage#performOk() */ public boolean performOk() { String[] allKeys= getAllKeys(); // preserve other options // store in JCore and the preferences Hashtable actualOptions= JavaCore.getOptions(); boolean hasChanges= false; for (int i= 0; i < allKeys.length; i++) { String key= allKeys[i]; String val= (String) fWorkingValues.get(key); String oldVal= (String) actualOptions.get(key); hasChanges= hasChanges | !val.equals(oldVal); actualOptions.put(key, val); } if (hasChanges) { String title= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("CompilerPreferencePage.needsbuild.message"); //$NON-NLS-1$ MessageDialog dialog= new MessageDialog(getShell(), title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); int res= dialog.open(); if (res != 0 && res != 1) { JavaPlugin.getDefault().savePluginPreferences(); return false; } JavaCore.setOptions(actualOptions); if (res == 0) { doFullBuild(); } } JavaPlugin.getDefault().savePluginPreferences(); return super.performOk(); } public static boolean openQuestion(Shell parent, String title, String message) { MessageDialog dialog= new MessageDialog(parent, title, null, message, MessageDialog.QUESTION, new String[] { IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL, IDialogConstants.CANCEL_LABEL }, 2); return dialog.open() == 0; } private void doFullBuild() { ProgressMonitorDialog dialog= new ProgressMonitorDialog(getShell()); try { dialog.run(true, true, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException { try { JavaPlugin.getWorkspace().build(IncrementalProjectBuilder.FULL_BUILD, monitor); } catch (CoreException e) { throw new InvocationTargetException(e); } } }); } catch (InterruptedException e) { // cancelled by user } catch (InvocationTargetException e) { String title= JavaUIMessages.getString("CompilerPreferencePage.builderror.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("CompilerPreferencePage.builderror.message"); //$NON-NLS-1$ ExceptionHandler.handle(e, getShell(), title, message); } } /* * @see PreferencePage#performDefaults() */ protected void performDefaults() { fWorkingValues= JavaCore.getDefaultOptions(); fWorkingValues.put(INTR_DEFAULT_COMPLIANCE, getCurrentCompliance()); updateControls(); validateSettings(null, null); super.performDefaults(); } private void updateControls() { // update the UI for (int i= fCheckBoxes.size() - 1; i >= 0; i--) { Button curr= (Button) fCheckBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.setSelection(data.getSelection(currValue) == 0); } for (int i= fComboBoxes.size() - 1; i >= 0; i--) { Combo curr= (Combo) fComboBoxes.get(i); ControlData data= (ControlData) curr.getData(); String currValue= (String) fWorkingValues.get(data.getKey()); curr.select(data.getSelection(currValue)); } for (int i= fTextBoxes.size() - 1; i >= 0; i--) { Text curr= (Text) fTextBoxes.get(i); String key= (String) curr.getData(); String currValue= (String) fWorkingValues.get(key); curr.setText(currValue); } } private void updateStatus(IStatus status) { setValid(!status.matches(IStatus.ERROR)); StatusUtil.applyToStatusLine(this, status); } }
24,025
Bug 24025 Quick fix create method gets wrong parameters if parameters are arrays
Steps: 1)type somewhere: Object[] test1= new Object[]{}; Object[] test2= new Object[]{}; if(compareTheseArrays(test1,test2)){ System.out.println("they are the same"); } 2)A Quick fix icon will appear and ask you to create Method compareTheseArrays, select this. 3)note that the method created takes Object as parameters and not Object[]. Should this be? version. 20020920. JRT.
verified fixed
b1c038d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-25T10:09:10Z
2002-09-24T12:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTResolving.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.jdt.core.IBuffer; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.ToolFactory; import org.eclipse.jdt.core.compiler.IScanner; import org.eclipse.jdt.core.compiler.ITerminalSymbols; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.corext.dom.GenericVisitor; import org.eclipse.jdt.internal.corext.dom.Selection; import org.eclipse.jdt.internal.corext.dom.SelectionAnalyzer; public class ASTResolving { private static class SelectionFinder extends GenericVisitor { private int fStart; private int fEnd; private ASTNode fCoveringNode; private ASTNode fCoveredNode; public SelectionFinder(int offset, int length) { fStart= offset; fEnd= offset + length; } protected boolean visitNode(ASTNode node) { int nodeStart= node.getStartPosition(); int nodeEnd= nodeStart + node.getLength(); if (nodeStart <= fStart && fEnd <= nodeEnd) { fCoveringNode= node; } else { return false; } if (fStart <= nodeStart && nodeEnd <= fEnd) { fCoveredNode= node; return false; } return true; } /** * Returns the coveredNode. * @return ASTNode */ public ASTNode getCoveredNode() { return fCoveredNode; } /** * Returns the coveringNode. * @return ASTNode */ public ASTNode getCoveringNode() { return fCoveringNode; } } public static ASTNode findCoveringNode(CompilationUnit cuNode, int offset, int length) { SelectionFinder selectionFinder= new SelectionFinder(offset, length); cuNode.accept(selectionFinder); return selectionFinder.getCoveringNode(); } public static ASTNode findSelectedNode(CompilationUnit cuNode, int offset, int length) { SelectionAnalyzer analyzer= new SelectionAnalyzer(Selection.createFromStartLength(offset, length), true); cuNode.accept(analyzer); if (analyzer.hasSelectedNodes()) { return analyzer.getFirstSelectedNode(); } return analyzer.getLastCoveringNode(); } public static ITypeBinding getTypeBinding(ASTNode node) { ITypeBinding binding= getPossibleTypeBinding(node); if (binding != null) { String name= binding.getName(); if (binding.isNullType() || "void".equals(name)) { //$NON-NLS-1$ return node.getAST().resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$ } else if (binding.isAnonymous()) { return binding.getSuperclass(); } } return binding; } private static ITypeBinding getPossibleTypeBinding(ASTNode node) { ASTNode parent= node.getParent(); switch (parent.getNodeType()) { case ASTNode.ASSIGNMENT: Assignment assignment= (Assignment) parent; if (node.equals(assignment.getLeftHandSide())) { // field write access: xx= expression return assignment.getRightHandSide().resolveTypeBinding(); } // read access return assignment.getLeftHandSide().resolveTypeBinding(); case ASTNode.INFIX_EXPRESSION: InfixExpression infix= (InfixExpression) parent; if (node.equals(infix.getLeftOperand())) { // xx == expression return infix.getRightOperand().resolveTypeBinding(); } // expression == xx InfixExpression.Operator op= infix.getOperator(); if (op == InfixExpression.Operator.LEFT_SHIFT || op == InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED || op == InfixExpression.Operator.RIGHT_SHIFT_SIGNED) { return infix.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } return infix.getLeftOperand().resolveTypeBinding(); case ASTNode.INSTANCEOF_EXPRESSION: InstanceofExpression instanceofExpression= (InstanceofExpression) parent; return instanceofExpression.getRightOperand().resolveBinding(); case ASTNode.VARIABLE_DECLARATION_FRAGMENT: VariableDeclarationFragment frag= (VariableDeclarationFragment) parent; if (frag.getInitializer().equals(node)) { ASTNode declaration= frag.getParent(); if (declaration instanceof VariableDeclarationStatement) { return ((VariableDeclarationStatement)declaration).getType().resolveBinding(); } else if (declaration instanceof FieldDeclaration) { return ((FieldDeclaration)declaration).getType().resolveBinding(); } } break; case ASTNode.METHOD_INVOCATION: MethodInvocation methodInvocation= (MethodInvocation) parent; SimpleName name= methodInvocation.getName(); IMethodBinding methodBinding= ASTNodes.getMethodBinding(name); if (methodBinding != null) { return getParameterTypeBinding(node, methodInvocation.arguments(), methodBinding); } break; case ASTNode.SUPER_CONSTRUCTOR_INVOCATION: SuperConstructorInvocation superInvocation= (SuperConstructorInvocation) parent; IMethodBinding superBinding= superInvocation.resolveConstructorBinding(); if (superBinding != null) { return getParameterTypeBinding(node, superInvocation.arguments(), superBinding); } break; case ASTNode.CONSTRUCTOR_INVOCATION: ConstructorInvocation constrInvocation= (ConstructorInvocation) parent; IMethodBinding constrBinding= constrInvocation.resolveConstructorBinding(); if (constrBinding != null) { return getParameterTypeBinding(node, constrInvocation.arguments(), constrBinding); } break; case ASTNode.CLASS_INSTANCE_CREATION: ClassInstanceCreation creation= (ClassInstanceCreation) parent; IMethodBinding creationBinding= creation.resolveConstructorBinding(); if (creationBinding != null) { return getParameterTypeBinding(node, creation.arguments(), creationBinding); } break; case ASTNode.PARENTHESIZED_EXPRESSION: return getTypeBinding(parent); case ASTNode.ARRAY_ACCESS: if (((ArrayAccess) parent).getIndex().equals(node)) { return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } break; case ASTNode.ARRAY_CREATION: if (((ArrayCreation) parent).dimensions().contains(node)) { return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } break; case ASTNode.ARRAY_INITIALIZER: ASTNode initializerParent= parent.getParent(); if (initializerParent instanceof ArrayCreation) { return ((ArrayCreation) initializerParent).getType().getElementType().resolveBinding(); } break; case ASTNode.CONDITIONAL_EXPRESSION: ConditionalExpression expression= (ConditionalExpression) parent; if (node.equals(expression.getExpression())) { return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$ } if (node.equals(expression.getElseExpression())) { return expression.getThenExpression().resolveTypeBinding(); } return expression.getElseExpression().resolveTypeBinding(); case ASTNode.POSTFIX_EXPRESSION: return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ case ASTNode.PREFIX_EXPRESSION: if (((PrefixExpression) parent).getOperator() == PrefixExpression.Operator.NOT) { return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$ } return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ case ASTNode.IF_STATEMENT: case ASTNode.WHILE_STATEMENT: case ASTNode.DO_STATEMENT: if (node instanceof Expression) { return parent.getAST().resolveWellKnownType("boolean"); //$NON-NLS-1$ } break; case ASTNode.SWITCH_STATEMENT: if (((SwitchStatement) parent).getExpression().equals(node)) { return parent.getAST().resolveWellKnownType("int"); //$NON-NLS-1$ } break; case ASTNode.RETURN_STATEMENT: MethodDeclaration decl= findParentMethodDeclaration(parent); if (decl != null) { return decl.getReturnType().resolveBinding(); } break; case ASTNode.CAST_EXPRESSION: return ((CastExpression) parent).getType().resolveBinding(); case ASTNode.THROW_STATEMENT: case ASTNode.CATCH_CLAUSE: return parent.getAST().resolveWellKnownType("java.lang.Exception"); //$NON-NLS-1$ } return null; } private static ITypeBinding getParameterTypeBinding(ASTNode node, List args, IMethodBinding binding) { ITypeBinding[] paramTypes= binding.getParameterTypes(); int index= args.indexOf(node); if (index >= 0 && index < paramTypes.length) { return paramTypes[index]; } return null; } private static MethodDeclaration findParentMethodDeclaration(ASTNode node) { while ((node != null) && (node.getNodeType() != ASTNode.METHOD_DECLARATION)) { node= node.getParent(); } return (MethodDeclaration) node; } public static BodyDeclaration findParentBodyDeclaration(ASTNode node) { while ((node != null) && (!(node instanceof BodyDeclaration))) { node= node.getParent(); } return (BodyDeclaration) node; } public static CompilationUnit findParentCompilationUnit(ASTNode node) { while ((node != null) && (node.getNodeType() != ASTNode.COMPILATION_UNIT)) { node= node.getParent(); } return (CompilationUnit) node; } /** * Returns either a TypeDeclaration or an AnonymousTypeDeclaration * @param node * @return CompilationUnit */ public static ASTNode findParentType(ASTNode node) { while ((node != null) && (node.getNodeType() != ASTNode.TYPE_DECLARATION) && (node.getNodeType() != ASTNode.ANONYMOUS_CLASS_DECLARATION)) { node= node.getParent(); } return node; } public static Statement findParentStatement(ASTNode node) { while ((node != null) && (!(node instanceof Statement))) { node= node.getParent(); } return (Statement) node; } public static boolean isInStaticContext(ASTNode selectedNode) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode); if (decl instanceof MethodDeclaration) { return Modifier.isStatic(((MethodDeclaration)decl).getModifiers()); } else if (decl instanceof Initializer) { return Modifier.isStatic(((Initializer)decl).getModifiers()); } else if (decl instanceof FieldDeclaration) { return Modifier.isStatic(((FieldDeclaration)decl).getModifiers()); } return false; } public static IScanner createScanner(ICompilationUnit cu, int pos) throws InvalidInputException, JavaModelException { IScanner scanner= ToolFactory.createScanner(false, false, false, false); IBuffer buf= cu.getBuffer(); scanner.setSource(buf.getCharacters()); scanner.resetTo(pos, buf.getLength()); return scanner; } public static void overreadToken(IScanner scanner, int[] prevTokens) throws InvalidInputException { boolean found; do { found= false; int curr= scanner.getNextToken(); if (curr == ITerminalSymbols.TokenNameEOF) { throw new InvalidInputException("End of File"); } for (int i= 0; i < prevTokens.length; i++) { if (prevTokens[i] == curr) { found= true; break; } } } while (found); } public static void readToToken(IScanner scanner, int tok) throws InvalidInputException { int curr= 0; do { curr= scanner.getNextToken(); if (curr == ITerminalSymbols.TokenNameEOF) { throw new InvalidInputException("End of File"); } } while (curr != tok); } public static int getPositionAfter(IScanner scanner, int token) throws InvalidInputException { readToToken(scanner, token); return scanner.getCurrentTokenEndPosition() + 1; } public static int getPositionBefore(IScanner scanner, int token) throws InvalidInputException { readToToken(scanner, token); return scanner.getCurrentTokenStartPosition(); } public static int getPositionAfter(IScanner scanner, int defaultPos, int[] tokens) throws InvalidInputException { int pos= defaultPos; loop: while(true) { int curr= scanner.getNextToken(); if (curr == ITerminalSymbols.TokenNameEOF) { return pos; } for (int i= 0; i < tokens.length; i++) { if (tokens[i] == curr) { pos= scanner.getCurrentTokenEndPosition() + 1; continue loop; } } return pos; } } public static Type getTypeFromTypeBinding(AST ast, ITypeBinding binding) { if (binding.isArray()) { int dim= binding.getDimensions(); return ast.newArrayType(getTypeFromTypeBinding(ast, binding.getElementType()), dim); } else if (binding.isPrimitive()) { String name= binding.getName(); return ast.newPrimitiveType(PrimitiveType.toCode(name)); } else if (!binding.isNullType() && !binding.isAnonymous()) { return ast.newSimpleType(ast.newSimpleName(binding.getName())); } return null; } public static Expression getInitExpression(Type type) { if (type.isPrimitiveType()) { PrimitiveType primitiveType= (PrimitiveType) type; if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.BOOLEAN) { return type.getAST().newBooleanLiteral(false); } else if (primitiveType.getPrimitiveTypeCode() == PrimitiveType.VOID) { return null; } else { return type.getAST().newNumberLiteral("0"); } } return type.getAST().newNullLiteral(); } private static class NodeFoundException extends RuntimeException { public ASTNode node; } public static ASTNode findClonedNode(ASTNode cloneRoot, final ASTNode node) { try { cloneRoot.accept(new ASTVisitor() { public void preVisit(ASTNode curr) { if (curr.getNodeType() == node.getNodeType() && curr.getStartPosition() == node.getStartPosition() && curr.getLength() == node.getLength()) { NodeFoundException exc= new NodeFoundException(); exc.node= curr; throw exc; } } }); } catch (NodeFoundException e) { return e.node; } return null; } private static TypeDeclaration findTypeDeclaration(List decls, String name) { for (Iterator iter= decls.iterator(); iter.hasNext();) { ASTNode elem= (ASTNode) iter.next(); if (elem instanceof TypeDeclaration) { TypeDeclaration decl= (TypeDeclaration) elem; if (name.equals(decl.getName().getIdentifier())) { return decl; } } } return null; } public static TypeDeclaration findTypeDeclaration(CompilationUnit root, ITypeBinding binding) { ArrayList names= new ArrayList(5); while (binding != null) { names.add(binding.getName()); binding= binding.getDeclaringClass(); } List types= root.types(); for (int i= names.size() - 1; i >= 0; i--) { String name= (String) names.get(i); TypeDeclaration decl= findTypeDeclaration(types, name); if (decl == null || i == 0) { return decl; } types= decl.bodyDeclarations(); } return null; } }
24,025
Bug 24025 Quick fix create method gets wrong parameters if parameters are arrays
Steps: 1)type somewhere: Object[] test1= new Object[]{}; Object[] test2= new Object[]{}; if(compareTheseArrays(test1,test2)){ System.out.println("they are the same"); } 2)A Quick fix icon will appear and ask you to create Method compareTheseArrays, select this. 3)note that the method created takes Object as parameters and not Object[]. Should this be? version. 20020920. JRT.
verified fixed
b1c038d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-25T10:09:10Z
2002-09-24T12:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ASTRewriteCorrectionProposal.java
package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.internal.corext.codemanipulation.ImportEdit; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; 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.TextEdit; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; /** */ public class ASTRewriteCorrectionProposal extends CUCorrectionProposal { private ASTRewrite fRewrite; private ImportEdit fImportEdit; public ASTRewriteCorrectionProposal(String name, ICompilationUnit cu, ASTRewrite rewrite, int relevance, Image image) { super(name, cu, relevance, image); fRewrite= rewrite; fImportEdit= null; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.text.correction.CUCorrectionProposal#createCompilationUnitChange(String, ICompilationUnit, TextEdit) */ protected CompilationUnitChange createCompilationUnitChange(String name, ICompilationUnit cu, TextEdit rootEdit) throws CoreException { CompilationUnitChange change= super.createCompilationUnitChange(name, cu, rootEdit); TextBuffer buffer= null; try { buffer= TextBuffer.acquire(change.getFile()); ArrayList groupDescriptions= new ArrayList(5); getRewrite().rewriteNode(buffer, rootEdit, groupDescriptions); for (int i= 0; i < groupDescriptions.size(); i++) { change.addGroupDescription((GroupDescription) groupDescriptions.get(i)); } } finally { if (buffer != null) { TextBuffer.release(buffer); } } if (fImportEdit != null && !fImportEdit.isEmpty()) { rootEdit.add(fImportEdit); } return change; } public void addImport(String qualifiedTypeName) { if (fImportEdit == null) { fImportEdit= new ImportEdit(getCompilationUnit(), JavaPreferencesSettings.getCodeGenerationSettings()); } fImportEdit.addImport(qualifiedTypeName); } protected ASTRewrite getRewrite() { return fRewrite; } }
24,025
Bug 24025 Quick fix create method gets wrong parameters if parameters are arrays
Steps: 1)type somewhere: Object[] test1= new Object[]{}; Object[] test2= new Object[]{}; if(compareTheseArrays(test1,test2)){ System.out.println("they are the same"); } 2)A Quick fix icon will appear and ask you to create Method compareTheseArrays, select this. 3)note that the method created takes Object as parameters and not Object[]. Should this be? version. 20020920. JRT.
verified fixed
b1c038d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-25T10:09:10Z
2002-09-24T12:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.NameProposer; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; 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.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class NewMethodCompletionProposal extends ASTRewriteCorrectionProposal { private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation private List fArguments; private ITypeBinding fSenderBinding; private boolean fIsLocalChange; public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance) { super(label, targetCU, null, relevance, JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC)); fNode= invocationNode; fArguments= arguments; fSenderBinding= binding; } protected ASTRewrite getRewrite() { ASTRewrite rewrite; CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; if (typeDecl != null) { fIsLocalChange= true; ASTCloner cloner= new ASTCloner(new AST(), astRoot); CompilationUnit newRoot= (CompilationUnit) cloner.getClonedRoot(); rewrite= new ASTRewrite(newRoot); newTypeDecl= cloner.getCloned(typeDecl); } else { fIsLocalChange= false; CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true); rewrite= new ASTRewrite(newRoot); newTypeDecl= ASTResolving.findTypeDeclaration(newRoot, fSenderBinding); } if (newTypeDecl != null) { List methods; if (fSenderBinding.isAnonymous()) { methods= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations(); } else { methods= ((TypeDeclaration) newTypeDecl).bodyDeclarations(); } MethodDeclaration newStub= getStub(newTypeDecl.getAST()); if (fIsLocalChange) { methods.add(findInsertIndex(methods, fNode.getStartPosition()), newStub); } else if (isConstructor()) { methods.add(0, newStub); } else { methods.add(newStub); } rewrite.markAsInserted(newStub); } return rewrite; } private boolean isConstructor() { return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION; } private MethodDeclaration getStub(AST ast) { MethodDeclaration decl= ast.newMethodDeclaration(); decl.setConstructor(isConstructor()); decl.setModifiers(evaluateModifiers()); decl.setName(ast.newSimpleName(getMethodName())); NameProposer nameProposer= new NameProposer(); List arguments= fArguments; List params= decl.parameters(); int nArguments= arguments.size(); ArrayList names= new ArrayList(nArguments); for (int i= 0; i < arguments.size(); i++) { Expression elem= (Expression) arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); Type type= evaluateParameterType(ast, elem); param.setType(type); param.setName(ast.newSimpleName(getParameterName(nameProposer, names, elem, type))); params.add(param); } Block body= ast.newBlock(); if (!isConstructor()) { Type returnType= evaluateMethodType(ast); decl.setReturnType(returnType); ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(ASTResolving.getInitExpression(returnType)); body.statements().add(returnStatement); } decl.setBody(body); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (settings.createComments && !fSenderBinding.isAnonymous()) { StringBuffer buf= new StringBuffer(); String[] namesArray= (String[]) names.toArray(new String[names.size()]); String name= decl.getName().getIdentifier(); if (isConstructor()) { StubUtility.genJavaDocStub("Constructor " + name, namesArray, null, null, buf); } else { String returnTypeSig= Signature.createTypeSignature(ASTNodes.asString(decl.getReturnType()), true); StubUtility.genJavaDocStub("Method " + name, namesArray, returnTypeSig, null, buf); } Javadoc javadoc= ast.newJavadoc(); javadoc.setComment(buf.toString()); decl.setJavadoc(javadoc); } return decl; } private String getParameterName(NameProposer nameProposer, ArrayList takenNames, Expression argNode, Type type) { String name; if (argNode instanceof SimpleName) { name= ((SimpleName) argNode).getIdentifier(); } else { name= nameProposer.proposeParameterName(ASTNodes.asString(type)); } String base= name; int i= 1; while (takenNames.contains(name)) { name= base + i++; } takenNames.add(name); return name; } private int findInsertIndex(List decls, int currPos) { int nDecls= decls.size(); for (int i= 0; i < nDecls; i++) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) { return i + 1; } } return nDecls; } private String getMethodName() { if (fNode instanceof MethodInvocation) { return ((MethodInvocation)fNode).getName().getIdentifier(); } else if (fNode instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)fNode).getName().getIdentifier(); } else { return fSenderBinding.getName(); // name of the class } } private int evaluateModifiers() { if (fNode instanceof MethodInvocation) { int modifiers= 0; Expression expression= ((MethodInvocation)fNode).getExpression(); if (expression != null) { if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } else if (ASTResolving.isInStaticContext(fNode)) { modifiers |= Modifier.STATIC; } if (fIsLocalChange) { modifiers |= Modifier.PRIVATE; } else if (!fSenderBinding.isInterface()) { modifiers |= Modifier.PUBLIC; } return modifiers; } return Modifier.PUBLIC; } private Type evaluateMethodType(AST ast) { ITypeBinding binding= ASTResolving.getTypeBinding(fNode); if (binding != null) { ITypeBinding baseType= binding.isArray() ? binding.getElementType() : binding; if (!baseType.isPrimitive()) { addImport(Bindings.getFullyQualifiedName(baseType)); } return ASTResolving.getTypeFromTypeBinding(ast, baseType); } return ast.newPrimitiveType(PrimitiveType.VOID); } private Type evaluateParameterType(AST ast, Expression expr) { ITypeBinding binding= expr.resolveTypeBinding(); if (binding != null && !binding.isNullType()) { ITypeBinding baseType= binding.isArray() ? binding.getElementType() : binding; if (!baseType.isPrimitive()) { addImport(Bindings.getFullyQualifiedName(baseType)); } return ASTResolving.getTypeFromTypeBinding(ast, baseType); } return ast.newSimpleType(ast.newSimpleName("Object")); } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (!fIsLocalChange) { change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(getCompilationUnit(), true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
24,025
Bug 24025 Quick fix create method gets wrong parameters if parameters are arrays
Steps: 1)type somewhere: Object[] test1= new Object[]{}; Object[] test2= new Object[]{}; if(compareTheseArrays(test1,test2)){ System.out.println("they are the same"); } 2)A Quick fix icon will appear and ask you to create Method compareTheseArrays, select this. 3)note that the method created takes Object as parameters and not Object[]. Should this be? version. 20020920. JRT.
verified fixed
b1c038d
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-25T10:09:10Z
2002-09-24T12:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewVariableCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.Assignment; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.BodyDeclaration; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Initializer; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Statement; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.core.dom.VariableDeclarationFragment; import org.eclipse.jdt.internal.corext.dom.ASTNodes; import org.eclipse.jdt.internal.corext.dom.ASTRewrite; import org.eclipse.jdt.internal.corext.dom.Bindings; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class NewVariableCompletionProposal extends ASTRewriteCorrectionProposal { public static final int LOCAL= 1; public static final int FIELD= 2; public static final int PARAM= 3; private int fVariableKind; private SimpleName fOriginalNode; public NewVariableCompletionProposal(String label, ICompilationUnit cu, int variableKind, SimpleName node, int relevance) { super(label, cu, null, relevance, null); fVariableKind= variableKind; fOriginalNode= node; if (variableKind == FIELD) { setImage(JavaPluginImages.get(JavaPluginImages.IMG_MISC_PUBLIC)); } else { setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL)); } } protected ASTRewrite getRewrite() { AST ast= new AST(); CompilationUnit origCU= ASTResolving.findParentCompilationUnit(fOriginalNode); ASTCloner cloner= new ASTCloner(ast, origCU); CompilationUnit cu= (CompilationUnit) cloner.getClonedRoot(); SimpleName node= (SimpleName) cloner.getCloned(fOriginalNode); cloner= null; ASTRewrite rewrite= new ASTRewrite(cu); if (fVariableKind == PARAM) { doAddParam(ast, node, rewrite); } else if (fVariableKind == FIELD) { doAddField(ast, node, rewrite); } else if (fVariableKind == LOCAL) { doAddLocal(ast, node, rewrite); } return rewrite; } private void doAddParam(AST ast, SimpleName node, ASTRewrite rewrite) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration) { SingleVariableDeclaration newDecl= ast.newSingleVariableDeclaration(); newDecl.setType(evaluateVariableType(ast)); newDecl.setName(ast.newSimpleName(node.getIdentifier())); rewrite.markAsInserted(newDecl); ((MethodDeclaration)decl).parameters().add(newDecl); } } private void doAddLocal(AST ast, SimpleName node, ASTRewrite rewrite) { BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(node); if (decl instanceof MethodDeclaration || decl instanceof Initializer) { VariableDeclarationFragment newDeclFrag= ast.newVariableDeclarationFragment(); VariableDeclarationStatement newDecl= ast.newVariableDeclarationStatement(newDeclFrag); Type type= evaluateVariableType(ast); newDecl.setType(type); newDeclFrag.setName(ast.newSimpleName(node.getIdentifier())); newDeclFrag.setInitializer(ASTResolving.getInitExpression(type)); ASTNode parent= node.getParent(); if (parent.getNodeType() == ASTNode.ASSIGNMENT) { Assignment assignment= (Assignment) parent; if (node.equals(assignment.getLeftHandSide())) { int parentParentKind= parent.getParent().getNodeType(); if (parentParentKind == ASTNode.EXPRESSION_STATEMENT) { Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); newDeclFrag.setInitializer(placeholder); rewrite.markAsReplaced(assignment.getParent(), newDecl); return; } else if (parentParentKind == ASTNode.FOR_STATEMENT) { ForStatement forStatement= (ForStatement) parent.getParent(); if (forStatement.initializers().size() == 1 && assignment.equals(forStatement.initializers().get(0))) { VariableDeclarationFragment frag= ast.newVariableDeclarationFragment(); VariableDeclarationExpression expression= ast.newVariableDeclarationExpression(frag); frag.setName(ast.newSimpleName(node.getIdentifier())); Expression placeholder= (Expression) rewrite.createCopy(assignment.getRightHandSide()); frag.setInitializer(placeholder); expression.setType(evaluateVariableType(ast)); rewrite.markAsReplaced(assignment, expression); return; } } } } else if (parent.getNodeType() == ASTNode.EXPRESSION_STATEMENT) { rewrite.markAsReplaced(parent, newDecl); return; } Statement statement= ASTResolving.findParentStatement(node); if (statement != null && statement.getParent() instanceof Block) { Block block= (Block) statement.getParent(); List statements= block.statements(); statements.add(0, newDecl); rewrite.markAsInserted(newDecl); } } } private void doAddField(AST ast, SimpleName node, ASTRewrite rewrite) { ASTNode parentType= ASTResolving.findParentType(node); if (parentType != null) { VariableDeclarationFragment fragment= ast.newVariableDeclarationFragment(); fragment.setName(ast.newSimpleName(node.getIdentifier())); FieldDeclaration newDecl= ast.newFieldDeclaration(fragment); newDecl.setType(evaluateVariableType(ast)); int modifiers= Modifier.PRIVATE; if (ASTResolving.isInStaticContext(node)) { modifiers |= Modifier.STATIC; } newDecl.setModifiers(modifiers); boolean isAnonymous= parentType.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION; List decls= isAnonymous ? ((AnonymousClassDeclaration) parentType).bodyDeclarations() : ((TypeDeclaration) parentType).bodyDeclarations(); decls.add(findInsertIndex(decls, node.getStartPosition()), newDecl); rewrite.markAsInserted(newDecl); } } private int findInsertIndex(List decls, int currPos) { for (int i= decls.size() - 1; i >= 0; i--) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof FieldDeclaration && currPos > curr.getStartPosition() + curr.getLength()) { return i + 1; } } return 0; } private Type evaluateVariableType(AST ast) { ITypeBinding binding= ASTResolving.getTypeBinding(fOriginalNode); if (binding != null) { ITypeBinding baseType= binding.isArray() ? binding.getElementType() : binding; if (!baseType.isPrimitive()) { addImport(Bindings.getFullyQualifiedName(baseType)); } return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newSimpleType(ast.newSimpleName("Object")); } }
23,710
Bug 23710 Search "Remove Selected Matchs" is removing all elements from the view [search]
!ENTRY org.eclipse.jdt.ui 4 1 Sep 18, 2002 09:54:31.614 !MESSAGE An error occurred while creating a Java element !STACK 1 org.eclipse.core.internal.resources.ResourceException: Marker id: 48235 not found. at org.eclipse.core.internal.resources.Marker.checkInfo(Marker.java (Compiled Code)) at org.eclipse.core.internal.resources.Marker.getAttribute (Marker.java:89) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.convertSelection (SearchViewSiteAdapter.java:106) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.access$1 (SearchViewSiteAdapter.java:101) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleInvalidSelection (StructuredViewer.java:514) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:700) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:532) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:552) at org.eclipse.search.internal.ui.SearchResultViewer.handleRemoveMatch (SearchResultViewer.java:589) at org.eclipse.search.internal.ui.SearchManager.handleRemoveMatch (SearchManager.java:417) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkerChanged (SearchManager.java:363) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkersChanged (SearchManager.java:350) at org.eclipse.search.internal.ui.SearchManager.access$2 (SearchManager.java:339) at org.eclipse.search.internal.ui.SearchManager$7.run (SearchManager.java:476) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java (Compiled Code)) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java (Compiled Code)) at org.eclipse.swt.widgets.Display.syncExec(Display.java(Compiled Code)) at org.eclipse.search.internal.ui.SearchManager.resourceChanged (SearchManager.java:486) at org.eclipse.core.internal.events.NotificationManager$1.run (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java(Compiled Code)) at org.eclipse.core.runtime.Platform.run(Platform.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.notify (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges (NotificationManager.java:67) at org.eclipse.core.internal.resources.Workspace.broadcastChanges (Workspace.java:133) at org.eclipse.core.internal.resources.Workspace.endOperation (Workspace.java(Compiled Code)) at org.eclipse.core.internal.resources.Workspace.deleteMarkers (Workspace.java:659) at org.eclipse.search.internal.ui.RemoveResultAction$1.run (RemoveResultAction.java:47) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:66) at org.eclipse.search.internal.ui.RemoveResultAction.run (RemoveResultAction.java:44) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.core.resources 4 376 Sep 18, 2002 09:54:32.94 !MESSAGE Marker id: 48235 not found. !ENTRY org.eclipse.core.resources 4 2 Sep 18, 2002 09:54:32.605 !MESSAGE Problems occurred when invoking code from plug- in: "org.eclipse.core.resources". !STACK 0 org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java(Compiled Code)) at org.eclipse.jface.viewers.SelectionChangedEvent.<init> (SelectionChangedEvent.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleInvalidSelection (StructuredViewer.java:514) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:700) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:532) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:552) at org.eclipse.search.internal.ui.SearchResultViewer.handleRemoveMatch (SearchResultViewer.java:589) at org.eclipse.search.internal.ui.SearchManager.handleRemoveMatch (SearchManager.java:417) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkerChanged (SearchManager.java:363) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkersChanged (SearchManager.java:350) at org.eclipse.search.internal.ui.SearchManager.access$2 (SearchManager.java:339) at org.eclipse.search.internal.ui.SearchManager$7.run (SearchManager.java:476) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java (Compiled Code)) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java (Compiled Code)) at org.eclipse.swt.widgets.Display.syncExec(Display.java(Compiled Code)) at org.eclipse.search.internal.ui.SearchManager.resourceChanged (SearchManager.java:486) at org.eclipse.core.internal.events.NotificationManager$1.run (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java(Compiled Code)) at org.eclipse.core.runtime.Platform.run(Platform.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.notify (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges (NotificationManager.java:67) at org.eclipse.core.internal.resources.Workspace.broadcastChanges (Workspace.java:133) at org.eclipse.core.internal.resources.Workspace.endOperation (Workspace.java(Compiled Code)) at org.eclipse.core.internal.resources.Workspace.deleteMarkers (Workspace.java:659) at org.eclipse.search.internal.ui.RemoveResultAction$1.run (RemoveResultAction.java:47) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:66) at org.eclipse.search.internal.ui.RemoveResultAction.run (RemoveResultAction.java:44) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.jdt.ui 4 1 Sep 18, 2002 09:54:43.240 !MESSAGE An error occurred while creating a Java element !STACK 1 org.eclipse.core.internal.resources.ResourceException: Marker id: 48235 not found. at org.eclipse.core.internal.resources.Marker.checkInfo(Marker.java (Compiled Code)) at org.eclipse.core.internal.resources.Marker.getAttribute(Marker.java (Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.convertSelection (SearchViewSiteAdapter.java:106) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.access$1 (SearchViewSiteAdapter.java:101) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:904) at org.eclipse.search.internal.ui.SearchResultViewer.selectResult (SearchResultViewer.java:504) at org.eclipse.search.internal.ui.SearchResultViewer.showPreviousResult (SearchResultViewer.java:487) at org.eclipse.search.internal.ui.ShowPreviousResultAction.run (ShowPreviousResultAction.java:21) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.core.resources 4 376 Sep 18, 2002 09:54:43.471 !MESSAGE Marker id: 48235 not found. !ENTRY org.eclipse.ui 4 4 Sep 18, 2002 09:54:43.551 !MESSAGE Unhandled exception caught in event loop. Unhandled exception caught in event loop. Reason: !ENTRY org.eclipse.ui 4 0 Sep 18, 2002 09:54:43.851 !MESSAGE null argument; !STACK 0 org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java(Compiled Code)) at org.eclipse.jface.viewers.SelectionChangedEvent.<init> (SelectionChangedEvent.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:904) at org.eclipse.search.internal.ui.SearchResultViewer.selectResult (SearchResultViewer.java:504) at org.eclipse.search.internal.ui.SearchResultViewer.showPreviousResult (SearchResultViewer.java:487) at org.eclipse.search.internal.ui.ShowPreviousResultAction.run (ShowPreviousResultAction.java:21) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) null argument; org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java(Compiled Code)) at org.eclipse.jface.viewers.SelectionChangedEvent.<init> (SelectionChangedEvent.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.setSelection (StructuredViewer.java:904) at org.eclipse.search.internal.ui.SearchResultViewer.selectResult (SearchResultViewer.java:504) at org.eclipse.search.internal.ui.SearchResultViewer.showPreviousResult (SearchResultViewer.java:487) at org.eclipse.search.internal.ui.ShowPreviousResultAction.run (ShowPreviousResultAction.java:21) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.jdt.ui 4 1 Sep 18, 2002 09:54:53.225 !MESSAGE An error occurred while creating a Java element !STACK 1 org.eclipse.core.internal.resources.ResourceException: Marker id: 48235 not found. at org.eclipse.core.internal.resources.Marker.checkInfo(Marker.java (Compiled Code)) at org.eclipse.core.internal.resources.Marker.getAttribute(Marker.java (Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.convertSelection (SearchViewSiteAdapter.java:106) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.access$1 (SearchViewSiteAdapter.java:101) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:544) at org.eclipse.jface.viewers.StructuredViewer$1.widgetSelected (StructuredViewer.java:568) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.core.resources 4 376 Sep 18, 2002 09:54:53.415 !MESSAGE Marker id: 48235 not found. !ENTRY org.eclipse.ui 4 4 Sep 18, 2002 09:54:53.425 !MESSAGE Unhandled exception caught in event loop. Unhandled exception caught in event loop. Reason: !ENTRY org.eclipse.ui 4 0 Sep 18, 2002 09:54:53.645 !MESSAGE null argument; !STACK 0 org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java(Compiled Code)) at org.eclipse.jface.viewers.SelectionChangedEvent.<init> (SelectionChangedEvent.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:544) at org.eclipse.jface.viewers.StructuredViewer$1.widgetSelected (StructuredViewer.java:568) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) null argument; org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java(Compiled Code)) at org.eclipse.jface.viewers.SelectionChangedEvent.<init> (SelectionChangedEvent.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java:85) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleSelect (StructuredViewer.java:544) at org.eclipse.jface.viewers.StructuredViewer$1.widgetSelected (StructuredViewer.java:568) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java (Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) Snapshot took: 3956 milliseconds. Starting snapshot delay thread !ENTRY org.eclipse.jdt.ui 4 1 Sep 18, 2002 10:06:29.216 !MESSAGE An error occurred while creating a Java element !STACK 1 org.eclipse.core.internal.resources.ResourceException: Marker id: 48323 not found. at org.eclipse.core.internal.resources.Marker.checkInfo(Marker.java (Compiled Code)) at org.eclipse.core.internal.resources.Marker.getAttribute(Marker.java (Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter.convertSelection (SearchViewSiteAdapter.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java(Compiled Code)) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleInvalidSelection (StructuredViewer.java:514) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:700) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:532) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:552) at org.eclipse.search.internal.ui.SearchResultViewer.handleRemoveMatch (SearchResultViewer.java:589) at org.eclipse.search.internal.ui.SearchManager.handleRemoveMatch (SearchManager.java:417) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkerChanged (SearchManager.java:363) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkersChanged (SearchManager.java:350) at org.eclipse.search.internal.ui.SearchManager.access$2 (SearchManager.java:339) at org.eclipse.search.internal.ui.SearchManager$7.run (SearchManager.java:476) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java (Compiled Code)) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java (Compiled Code)) at org.eclipse.swt.widgets.Display.syncExec(Display.java(Compiled Code)) at org.eclipse.search.internal.ui.SearchManager.resourceChanged (SearchManager.java:486) at org.eclipse.core.internal.events.NotificationManager$1.run (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java(Compiled Code)) at org.eclipse.core.runtime.Platform.run(Platform.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.notify (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges (NotificationManager.java:67) at org.eclipse.core.internal.resources.Workspace.broadcastChanges (Workspace.java:133) at org.eclipse.core.internal.resources.Workspace.endOperation (Workspace.java(Compiled Code)) at org.eclipse.core.internal.resources.Workspace.deleteMarkers (Workspace.java:659) at org.eclipse.search.internal.ui.RemoveResultAction$1.run (RemoveResultAction.java:47) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:66) at org.eclipse.search.internal.ui.RemoveResultAction.run (RemoveResultAction.java:44) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.core.resources 4 376 Sep 18, 2002 10:06:29.776 !MESSAGE Marker id: 48323 not found. !ENTRY org.eclipse.core.resources 4 2 Sep 18, 2002 10:06:30.417 !MESSAGE Problems occurred when invoking code from plug- in: "org.eclipse.core.resources". !STACK 0 org.eclipse.jface.util.Assert$AssertionFailedException: null argument; at org.eclipse.jface.util.Assert.isNotNull(Assert.java:133) at org.eclipse.jface.util.Assert.isNotNull(Assert.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java(Compiled Code)) at org.eclipse.jdt.internal.ui.search.SearchViewSiteAdapter$2.selectionChanged (SearchViewSiteAdapter.java(Compiled Code)) at org.eclipse.jface.viewers.Viewer.fireSelectionChanged(Viewer.java (Compiled Code)) at org.eclipse.jface.viewers.StructuredViewer.updateSelection (StructuredViewer.java:1155) at org.eclipse.jface.viewers.StructuredViewer.handleInvalidSelection (StructuredViewer.java:514) at org.eclipse.jface.viewers.StructuredViewer.preservingSelection (StructuredViewer.java:700) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:532) at org.eclipse.jface.viewers.TableViewer.remove(TableViewer.java:552) at org.eclipse.search.internal.ui.SearchResultViewer.handleRemoveMatch (SearchResultViewer.java:589) at org.eclipse.search.internal.ui.SearchManager.handleRemoveMatch (SearchManager.java:417) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkerChanged (SearchManager.java:363) at org.eclipse.search.internal.ui.SearchManager.handleSearchMarkersChanged (SearchManager.java:350) at org.eclipse.search.internal.ui.SearchManager.access$2 (SearchManager.java:339) at org.eclipse.search.internal.ui.SearchManager$7.run (SearchManager.java:476) at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java (Compiled Code)) at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java (Compiled Code)) at org.eclipse.swt.widgets.Display.syncExec(Display.java(Compiled Code)) at org.eclipse.search.internal.ui.SearchManager.resourceChanged (SearchManager.java:486) at org.eclipse.core.internal.events.NotificationManager$1.run (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.runtime.InternalPlatform.run (InternalPlatform.java(Compiled Code)) at org.eclipse.core.runtime.Platform.run(Platform.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.notify (NotificationManager.java(Compiled Code)) at org.eclipse.core.internal.events.NotificationManager.broadcastChanges (NotificationManager.java:67) at org.eclipse.core.internal.resources.Workspace.broadcastChanges (Workspace.java:133) at org.eclipse.core.internal.resources.Workspace.endOperation (Workspace.java(Compiled Code)) at org.eclipse.core.internal.resources.Workspace.deleteMarkers (Workspace.java:659) at org.eclipse.search.internal.ui.RemoveResultAction$1.run (RemoveResultAction.java:47) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:66) at org.eclipse.search.internal.ui.RemoveResultAction.run (RemoveResultAction.java:44) at org.eclipse.jface.action.Action.runWithEvent(Action.java:749) at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection (ActionContributionItem.java:407) at org.eclipse.jface.action.ActionContributionItem.handleWidgetEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.jface.action.ActionContributionItem$ActionListener.handleEvent (ActionContributionItem.java(Compiled Code)) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java (Compiled Code)) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java(Compiled Code)) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java (Compiled Code)) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java (Compiled Code)) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1239) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24)
resolved fixed
657e45a
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-26T09:36:39Z
2002-09-18T14:40:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/search/SearchViewSiteAdapter.java
/******************************************************************************* * Copyright (c) 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.search; import org.eclipse.core.resources.IMarker; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.ui.IKeyBindingService; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkbenchSite; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.util.ExceptionHandler; import org.eclipse.jdt.internal.ui.util.SelectionUtil; /** * This class adapts a Search view site. * It converts selection of Search view entries to * be a selection of Java elements. * * @since 2.0 */ class SearchViewSiteAdapter implements IWorkbenchPartSite { private ISelectionProvider fProvider; private IWorkbenchSite fSite; private ISelectionChangedListener fListener; public SearchViewSiteAdapter(IWorkbenchSite site){ fSite= site; setSelectionProvider(site.getSelectionProvider()); } public IWorkbenchPage getPage() { return fSite.getPage(); } public ISelectionProvider getSelectionProvider() { return fProvider; } public Shell getShell() { return JavaPlugin.getActiveWorkbenchShell(); } public IWorkbenchWindow getWorkbenchWindow() { return fSite.getWorkbenchWindow(); } public void setSelectionProvider(final ISelectionProvider provider) { Assert.isNotNull(provider); fProvider= new ISelectionProvider() { public void addSelectionChangedListener(final ISelectionChangedListener listener) { fListener= new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { listener.selectionChanged(new SelectionChangedEvent(fProvider, convertSelection(event.getSelection()))); } }; provider.addSelectionChangedListener(fListener); } public ISelection getSelection() { return convertSelection(provider.getSelection()); } public void removeSelectionChangedListener(ISelectionChangedListener listener) { provider.removeSelectionChangedListener(fListener); } public void setSelection(ISelection selection) { } }; } private ISelection convertSelection(ISelection selection) { Object element= SelectionUtil.getSingleElement(selection); if (element instanceof ISearchResultViewEntry) { IMarker marker= ((ISearchResultViewEntry)element).getSelectedMarker(); try { IJavaElement je= JavaCore.create((String) ((IMarker) marker).getAttribute(IJavaSearchUIConstants.ATT_JE_HANDLE_ID)); if (je != null) return new StructuredSelection(je); } catch (CoreException ex) { ExceptionHandler.log(ex, SearchMessages.getString("Search.Error.createJavaElement.message")); //$NON-NLS-1$ return null; } } return StructuredSelection.EMPTY; } // --------- only empty stubs below --------- /* * @see org.eclipse.ui.IWorkbenchPartSite#getId() */ public String getId() { return null; } /* * @see org.eclipse.ui.IWorkbenchPartSite#getKeyBindingService() */ public IKeyBindingService getKeyBindingService() { return null; } /* * @see org.eclipse.ui.IWorkbenchPartSite#getPluginId() */ public String getPluginId() { return null; } /* * @see org.eclipse.ui.IWorkbenchPartSite#getRegisteredName() */ public String getRegisteredName() { return null; } /* * @see org.eclipse.ui.IWorkbenchPartSite#registerContextMenu(MenuManager, ISelectionProvider) */ public void registerContextMenu(MenuManager menuManager, ISelectionProvider selectionProvider) { } /* * @see org.eclipse.ui.IWorkbenchPartSite#registerContextMenu(String, MenuManager, ISelectionProvider) */ public void registerContextMenu(String menuId, MenuManager menuManager, ISelectionProvider selectionProvider) { } }
24,040
Bug 24040 JavaBrowsingPerspective - the packages/types and members view clear selection and then contents when an IStructuredSelection event is fired that isn't an IJavaElement
We have an editor in WebSphere Studio that is able to be opened on a .java source file. In this editor the user can select objects. When this occurs in the Java Browsing Perspective the packages/types and members views are cleared out of their contents. It would be nicer if the views weren't clear out. The reason the views are cleared is codein org.eclipse.jdt.internal.ui.browsing.JavaBrowsingPart. This listens to selection and if the selection is an IStructuredSelection ( which our editorpart signals ) it first de-selects the selected items in the editor and then clears the editor contents. If the selection is an IStructuredSelection and the items implement IAdapter but don't return an IJavaElement then the behavior should be the same as for a TextSelectionEvent which the Java Editor fires right now as the user selects text and doesn't reset the viewers' contents to null.
resolved fixed
d01bc69
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-26T12:13:15Z
2002-09-24T15:06:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/JavaBrowsingPart.java
/* * (c) Copyright IBM Corp. 2000, 2002. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.swt.SWT; import org.eclipse.swt.dnd.DND; import org.eclipse.swt.dnd.DragSource; import org.eclipse.swt.dnd.DragSourceEvent; import org.eclipse.swt.dnd.Transfer; import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.Shell; import org.eclipse.jface.action.IAction; import org.eclipse.jface.action.IMenuListener; import org.eclipse.jface.action.IMenuManager; import org.eclipse.jface.action.IStatusLineManager; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.action.MenuManager; import org.eclipse.jface.text.ITextSelection; import org.eclipse.jface.util.Assert; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.DecoratingLabelProvider; import org.eclipse.jface.viewers.IContentProvider; import org.eclipse.jface.viewers.ILabelDecorator; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IOpenListener; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.ISelectionChangedListener; import org.eclipse.jface.viewers.ISelectionProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.OpenEvent; import org.eclipse.jface.viewers.SelectionChangedEvent; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.ui.IActionBars; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IFileEditorInput; import org.eclipse.ui.IMemento; import org.eclipse.ui.IPartListener; import org.eclipse.ui.ISelectionListener; import org.eclipse.ui.IViewSite; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.IWorkbenchPartSite; import org.eclipse.ui.IWorkingSet; import org.eclipse.ui.IWorkingSetManager; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.actions.ActionContext; import org.eclipse.ui.actions.ActionGroup; import org.eclipse.ui.part.ResourceTransfer; import org.eclipse.ui.part.ViewPart; import org.eclipse.search.ui.ISearchResultView; import org.eclipse.search.ui.ISearchResultViewEntry; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.IWorkingCopy; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.IContextMenuConstants; import org.eclipse.jdt.ui.IWorkingCopyManager; import org.eclipse.jdt.ui.JavaElementLabelProvider; import org.eclipse.jdt.ui.JavaElementSorter; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.StandardJavaElementContentProvider; import org.eclipse.jdt.ui.actions.BuildActionGroup; import org.eclipse.jdt.ui.actions.CCPActionGroup; import org.eclipse.jdt.ui.actions.CustomFiltersActionGroup; import org.eclipse.jdt.ui.actions.GenerateActionGroup; import org.eclipse.jdt.ui.actions.ImportActionGroup; import org.eclipse.jdt.ui.actions.JavaSearchActionGroup; import org.eclipse.jdt.ui.actions.OpenEditorActionGroup; import org.eclipse.jdt.ui.actions.OpenViewActionGroup; import org.eclipse.jdt.ui.actions.RefactorActionGroup; import org.eclipse.jdt.ui.actions.ShowActionGroup; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.actions.CompositeActionGroup; import org.eclipse.jdt.internal.ui.actions.NewWizardsActionGroup; import org.eclipse.jdt.internal.ui.dnd.DelegatingDragAdapter; import org.eclipse.jdt.internal.ui.dnd.DelegatingDropAdapter; import org.eclipse.jdt.internal.ui.dnd.LocalSelectionTransfer; import org.eclipse.jdt.internal.ui.dnd.ResourceTransferDragAdapter; import org.eclipse.jdt.internal.ui.dnd.TransferDragSourceListener; import org.eclipse.jdt.internal.ui.dnd.TransferDropTargetListener; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.javaeditor.IClassFileEditorInput; import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDragAdapter; import org.eclipse.jdt.internal.ui.packageview.SelectionTransferDropAdapter; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.search.SearchUtil; import org.eclipse.jdt.internal.ui.util.JavaUIHelp; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider; import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTableViewer; import org.eclipse.jdt.internal.ui.viewsupport.StatusBarUpdater; import org.eclipse.jdt.internal.ui.workingsets.WorkingSetFilterActionGroup; abstract class JavaBrowsingPart extends ViewPart implements IMenuListener, ISelectionListener, IViewPartInputProvider { private static final String TAG_SELECTED_ELEMENTS= "selectedElements"; //$NON-NLS-1$ private static final String TAG_SELECTED_ELEMENT= "selectedElement"; //$NON-NLS-1$ private static final String TAG_SELECTED_ELEMENT_PATH= "selectedElementPath"; //$NON-NLS-1$ private ILabelProvider fLabelProvider; private ILabelProvider fTitleProvider; private StructuredViewer fViewer; private IMemento fMemento; private JavaElementTypeComparator fTypeComparator; // Actions private WorkingSetFilterActionGroup fWorkingSetFilterActionGroup; private boolean fHasWorkingSetFilter= true; private boolean fHasCustomFilter= true; private OpenEditorActionGroup fOpenEditorGroup; private CCPActionGroup fCCPActionGroup; private BuildActionGroup fBuildActionGroup; protected CompositeActionGroup fActionGroups; // Filters private CustomFiltersActionGroup fCustomFiltersActionGroup; private Menu fContextMenu; private IWorkbenchPart fPreviousSelectionProvider; private Object fPreviousSelectedElement; /* * Ensure selection changed events being processed only if * initiated by user interaction with this part. */ private boolean fProcessSelectionEvents= true; private IPartListener fPartListener= new IPartListener() { public void partActivated(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partBroughtToTop(IWorkbenchPart part) { setSelectionFromEditor(part); } public void partClosed(IWorkbenchPart part) { } public void partDeactivated(IWorkbenchPart part) { } public void partOpened(IWorkbenchPart part) { } }; /* * Implements method from IViewPart. */ public void init(IViewSite site, IMemento memento) throws PartInitException { super.init(site, memento); fMemento= memento; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { if (fViewer == null) { // part has not been created if (fMemento != null) //Keep the old state; memento.putMemento(fMemento); return; } if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup.saveState(memento); if (fHasCustomFilter) fCustomFiltersActionGroup.saveState(memento); saveSelectionState(memento); } private void saveSelectionState(IMemento memento) { Object elements[]= ((IStructuredSelection) fViewer.getSelection()).toArray(); if (elements.length > 0) { IMemento selectionMem= memento.createChild(TAG_SELECTED_ELEMENTS); for (int i= 0; i < elements.length; i++) { IMemento elementMem= selectionMem.createChild(TAG_SELECTED_ELEMENT); // we can only persist JavaElements for now Object o= elements[i]; if (o instanceof IJavaElement) elementMem.putString(TAG_SELECTED_ELEMENT_PATH, ((IJavaElement) elements[i]).getHandleIdentifier()); } } } protected void restoreState(IMemento memento) { if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup.restoreState(memento); if (fHasCustomFilter) fCustomFiltersActionGroup.restoreState(memento); if (fHasCustomFilter || fHasWorkingSetFilter) { fViewer.getControl().setRedraw(false); fViewer.refresh(); fViewer.getControl().setRedraw(true); } // restoreSelectionState(memento); } private ISelection restoreSelectionState(IMemento memento) { if (memento == null) return null; IMemento childMem; childMem= memento.getChild(TAG_SELECTED_ELEMENTS); if (childMem != null) { ArrayList list= new ArrayList(); IMemento[] elementMem= childMem.getChildren(TAG_SELECTED_ELEMENT); for (int i= 0; i < elementMem.length; i++) { IJavaElement element= JavaCore.create(elementMem[i].getString(TAG_SELECTED_ELEMENT_PATH)); if (element != null && element.exists()) list.add(element); } return new StructuredSelection(list); } return null; } /** * Creates the search list inner viewer. */ public void createPartControl(Composite parent) { Assert.isTrue(fViewer == null); fTypeComparator= new JavaElementTypeComparator(); // Setup viewer fViewer= createViewer(parent); fLabelProvider= createLabelProvider(); ILabelDecorator decorationMgr= PlatformUI.getWorkbench().getDecoratorManager().getLabelDecorator(); fViewer.setLabelProvider(new DecoratingLabelProvider(fLabelProvider, decorationMgr)); fViewer.setSorter(new JavaElementSorter()); fViewer.setUseHashlookup(true); fTitleProvider= createTitleProvider(); MenuManager menuMgr= new MenuManager("#PopupMenu"); //$NON-NLS-1$ menuMgr.setRemoveAllWhenShown(true); menuMgr.addMenuListener(this); fContextMenu= menuMgr.createContextMenu(fViewer.getControl()); fViewer.getControl().setMenu(fContextMenu); getSite().registerContextMenu(menuMgr, fViewer); getSite().setSelectionProvider(fViewer); createActions(); // call before registering for selection changes addKeyListener(); // Custom filter group if (fHasCustomFilter) fCustomFiltersActionGroup= new CustomFiltersActionGroup(this, fViewer); if (fMemento != null) restoreState(fMemento); getSite().setSelectionProvider(fViewer); // Status line IStatusLineManager slManager= getViewSite().getActionBars().getStatusLineManager(); fViewer.addSelectionChangedListener(new StatusBarUpdater(slManager)); hookViewerListeners(); // Filters addFilters(); // Initialize viewer input fViewer.setContentProvider(createContentProvider()); setInitialInput(); initDragAndDrop(); // Initialize selecton setInitialSelection(); fMemento= null; // Listen to workbench window changes getViewSite().getWorkbenchWindow().getSelectionService().addPostSelectionListener(this); getViewSite().getPage().addPartListener(fPartListener); fillActionBars(getViewSite().getActionBars()); setHelp(); } private void initDragAndDrop() { int ops= DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_LINK; Transfer[] transfers= new Transfer[] { LocalSelectionTransfer.getInstance(), ResourceTransfer.getInstance()}; // Drop Adapter TransferDropTargetListener[] dropListeners= new TransferDropTargetListener[] { new SelectionTransferDropAdapter(fViewer) }; fViewer.addDropSupport(ops | DND.DROP_DEFAULT, transfers, new DelegatingDropAdapter(dropListeners)); // Drag Adapter Control control= fViewer.getControl(); TransferDragSourceListener[] dragListeners= new TransferDragSourceListener[] { new SelectionTransferDragAdapter(fViewer), new ResourceTransferDragAdapter(fViewer) }; DragSource source= new DragSource(control, ops); // Note, that the transfer agents are set by the delegating drag adapter itself. source.addDragListener(new DelegatingDragAdapter(dragListeners) { public void dragStart(DragSourceEvent event) { IStructuredSelection selection= (IStructuredSelection)getSelectionProvider().getSelection(); for (Iterator iter= selection.iterator(); iter.hasNext(); ) { if (iter.next() instanceof IMember) { setPossibleListeners(new TransferDragSourceListener[] {new SelectionTransferDragAdapter(fViewer)}); break; } } super.dragStart(event); } }); } protected void fillActionBars(IActionBars actionBars) { IToolBarManager toolBar= actionBars.getToolBarManager(); fillToolBar(toolBar); if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup.fillActionBars(getViewSite().getActionBars()); actionBars.updateActionBars(); fActionGroups.fillActionBars(actionBars); if (fHasCustomFilter) fCustomFiltersActionGroup.fillActionBars(actionBars); } //---- IWorkbenchPart ------------------------------------------------------ public void setFocus() { fViewer.getControl().setFocus(); } public void dispose() { if (fViewer != null) { getViewSite().getWorkbenchWindow().getSelectionService().removePostSelectionListener(this); getViewSite().getPage().removePartListener(fPartListener); fViewer= null; } if (fActionGroups != null) fActionGroups.dispose(); super.dispose(); } /** * Adds the KeyListener */ protected void addKeyListener() { fViewer.getControl().addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent event) { handleKeyReleased(event); } }); } protected void handleKeyReleased(KeyEvent event) { if (event.stateMask != 0) return; int key= event.keyCode; IAction action; if (key == SWT.F5) { action= fBuildActionGroup.getRefreshAction(); if (action.isEnabled()) action.run(); } if (event.character == SWT.DEL) { action= fCCPActionGroup.getDeleteAction(); if (action.isEnabled()) action.run(); } } //---- Adding Action to Toolbar ------------------------------------------- protected void fillToolBar(IToolBarManager tbm) { } /** * Called when the context menu is about to open. * Override to add your own context dependent menu contributions. */ public void menuAboutToShow(IMenuManager menu) { JavaPlugin.createStandardGroups(menu); IStructuredSelection selection= (IStructuredSelection) fViewer.getSelection(); int size= selection.size(); Object element= selection.getFirstElement(); if (size == 1) addOpenNewWindowAction(menu, element); fActionGroups.setContext(new ActionContext(selection)); fActionGroups.fillContextMenu(menu); fActionGroups.setContext(null); } private boolean isNewTarget(IJavaElement element) { if (element == null) return false; int type= element.getElementType(); return type == IJavaElement.JAVA_PROJECT || type == IJavaElement.PACKAGE_FRAGMENT_ROOT || type == IJavaElement.PACKAGE_FRAGMENT || type == IJavaElement.COMPILATION_UNIT || type == IJavaElement.TYPE; } private void addOpenNewWindowAction(IMenuManager menu, Object element) { if (element instanceof IJavaElement) { try { element= ((IJavaElement)element).getCorrespondingResource(); } catch(JavaModelException e) { } } if (!(element instanceof IContainer)) return; menu.appendToGroup( IContextMenuConstants.GROUP_OPEN, new PatchedOpenInNewWindowAction(getSite().getWorkbenchWindow(), (IContainer)element)); } protected void createActions() { fActionGroups= new CompositeActionGroup(new ActionGroup[] { new NewWizardsActionGroup(this.getSite()), fOpenEditorGroup= new OpenEditorActionGroup(this), new OpenViewActionGroup(this), new ShowActionGroup(this), fCCPActionGroup= new CCPActionGroup(this), new RefactorActionGroup(this), new ImportActionGroup(this), new GenerateActionGroup(this), fBuildActionGroup= new BuildActionGroup(this), new JavaSearchActionGroup(this)}); String viewId= getConfigurationElement().getAttribute("id"); //$NON-NLS-1$ Assert.isNotNull(viewId); IPropertyChangeListener titleUpdater= new IPropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { String property= event.getProperty(); if (IWorkingSetManager.CHANGE_WORKING_SET_NAME_CHANGE.equals(property)) updateTitle(); } }; if (fHasWorkingSetFilter) fWorkingSetFilterActionGroup= new WorkingSetFilterActionGroup(fViewer, viewId, getShell(), titleUpdater); } /** * Returns the shell to use for opening dialogs. * Used in this class, and in the actions. */ private Shell getShell() { return fViewer.getControl().getShell(); } protected final Display getDisplay() { return fViewer.getControl().getDisplay(); } /** * Returns the selection provider. */ ISelectionProvider getSelectionProvider() { return fViewer; } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ abstract protected boolean isValidInput(Object element); /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element == null) return false; element= getSuitableJavaElement(element); if (element == null) return false; Object input= getViewer().getInput(); if (input == null) return false; if (input instanceof Collection) return ((Collection)input).contains(element); else return input.equals(element); } private boolean isInputResetBy(Object newInput, Object input, IWorkbenchPart part) { if (newInput == null) return part == fPreviousSelectionProvider; if (input instanceof IJavaElement && newInput instanceof IJavaElement) return getTypeComparator().compare(newInput, input) > 0; else return false; } private boolean isInputResetBy(IWorkbenchPart part) { if (!(part instanceof JavaBrowsingPart)) return true; Object thisInput= getViewer().getInput(); Object partInput= ((JavaBrowsingPart)part).getViewer().getInput(); if (thisInput instanceof IJavaElement && partInput instanceof IJavaElement) return getTypeComparator().compare(partInput, thisInput) > 0; else return true; } protected boolean isAncestorOf(Object ancestor, Object element) { if (element instanceof IJavaElement && ancestor instanceof IJavaElement) return !element.equals(ancestor) && internalIsAncestorOf((IJavaElement)ancestor, (IJavaElement)element); return false; } private boolean internalIsAncestorOf(IJavaElement ancestor, IJavaElement element) { if (element != null) return element.equals(ancestor) || internalIsAncestorOf(ancestor, element.getParent()); else return false; } public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (!fProcessSelectionEvents || part == this || (part instanceof ISearchResultView) || !(selection instanceof IStructuredSelection)) return; // Set selection Object selectedElement= getSingleElementFromSelection(selection); if (selectedElement != null && part.equals(fPreviousSelectionProvider) && selectedElement.equals(fPreviousSelectedElement)) return; fPreviousSelectedElement= selectedElement; Object currentInput= (IJavaElement)getViewer().getInput(); if (selectedElement != null && selectedElement.equals(currentInput)) { IJavaElement elementToSelect= findElementToSelect(selectedElement); if (elementToSelect != null && getTypeComparator().compare(selectedElement, elementToSelect) < 0) setSelection(new StructuredSelection(elementToSelect), true); else if (elementToSelect == null && (this instanceof MembersView)) { setSelection(StructuredSelection.EMPTY, true); fPreviousSelectedElement= StructuredSelection.EMPTY; } fPreviousSelectionProvider= part; return; } // Clear input if needed if (part != fPreviousSelectionProvider && selectedElement != null && !selectedElement.equals(currentInput) && isInputResetBy(selectedElement, currentInput, part)) { if (!isAncestorOf(selectedElement, currentInput)) setInput(null); fPreviousSelectionProvider= part; return; } else if (selection.isEmpty() && !isInputResetBy(part)) { fPreviousSelectionProvider= part; return; } else if (selectedElement == null && part == fPreviousSelectionProvider) { setInput(null); fPreviousSelectionProvider= part; return; } fPreviousSelectionProvider= part; // Adjust input and set selection and if (selectedElement instanceof IJavaElement) adjustInputAndSetSelection((IJavaElement)selectedElement); else setSelection(StructuredSelection.EMPTY, true); } void setHasWorkingSetFilter(boolean state) { fHasWorkingSetFilter= state; } void setHasCustomSetFilter(boolean state) { fHasCustomFilter= state; } protected void setInput(Object input) { setViewerInput(input); updateTitle(); } private void setViewerInput(Object input) { fProcessSelectionEvents= false; fViewer.setInput(input); fProcessSelectionEvents= true; } void updateTitle() { setTitleToolTip(getToolTipText(fViewer.getInput())); } /** * Returns the tool tip text for the given element. */ String getToolTipText(Object element) { String result; if (!(element instanceof IResource)) { result= JavaElementLabels.getTextLabel(element, AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS); } else { IPath path= ((IResource) element).getFullPath(); if (path.isRoot()) { result= getConfigurationElement().getAttribute("name"); //$NON-NLS-1$ } else { result= path.makeRelative().toString(); } } if (fWorkingSetFilterActionGroup == null || fWorkingSetFilterActionGroup.getWorkingSet() == null) return result; IWorkingSet ws= fWorkingSetFilterActionGroup.getWorkingSet(); String wsstr= JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip", new String[] { ws.getName() }); //$NON-NLS-1$ if (result.length() == 0) return wsstr; return JavaBrowsingMessages.getFormattedString("JavaBrowsingPart.toolTip2", new String[] { result, ws.getName() }); //$NON-NLS-1$ } public String getTitleToolTip() { if (fViewer == null) return super.getTitleToolTip(); return getToolTipText(fViewer.getInput()); } protected final StructuredViewer getViewer() { return fViewer; } protected ILabelProvider createLabelProvider() { return new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS | JavaElementImageProvider.SMALL_ICONS, AppearanceAwareLabelProvider.getDecorators(true, null) ); } protected ILabelProvider createTitleProvider() { return new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_SMALL_ICONS); } protected final ILabelProvider getLabelProvider() { return fLabelProvider; } protected final ILabelProvider getTitleProvider() { return fTitleProvider; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { return new ProblemTableViewer(parent, SWT.MULTI); } protected int getLabelProviderFlags() { return JavaElementLabelProvider.SHOW_BASICS | JavaElementLabelProvider.SHOW_OVERLAY_ICONS | JavaElementLabelProvider.SHOW_SMALL_ICONS | JavaElementLabelProvider.SHOW_VARIABLE | JavaElementLabelProvider.SHOW_PARAMETERS; } /** * Adds filters the viewer of this part. */ protected void addFilters() { // default is to have no filters } /** * Creates the the content provider of this part. */ protected IContentProvider createContentProvider() { return new JavaBrowsingContentProvider(true, this); } protected void setInitialInput() { // Use the selection, if any ISelection selection= getSite().getPage().getSelection(); Object input= getSingleElementFromSelection(selection); if (!(input instanceof IJavaElement)) { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement) && input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); } setInput(findInputForJavaElement((IJavaElement)input)); } protected void setInitialSelection() { // Use the selection, if any Object input; IWorkbenchPage page= getSite().getPage(); ISelection selection= null; if (page != null) selection= page.getSelection(); if (selection instanceof ITextSelection) { Object part= PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); if (part instanceof IEditorPart) { setSelectionFromEditor((IEditorPart)part); if (fViewer.getSelection() != null) return; } } // Use saved selection from memento if (selection == null || selection.isEmpty()) selection= restoreSelectionState(fMemento); if (selection != null && !selection.isEmpty()) input= getSingleElementFromSelection(selection); else { // Use the input of the page input= getSite().getPage().getInput(); if (!(input instanceof IJavaElement)) { if (input instanceof IAdaptable) input= ((IAdaptable)input).getAdapter(IJavaElement.class); else return; } } if (findElementToSelect((IJavaElement)input) != null) adjustInputAndSetSelection((IJavaElement)input); } final protected void setHelp() { JavaUIHelp.setHelp(fViewer, getHelpContextId()); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ abstract protected String getHelpContextId(); /** * Adds additional listeners to this view. * This method can be overridden but should * call super. */ protected void hookViewerListeners() { fViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { if (!fProcessSelectionEvents) return; fPreviousSelectedElement= getSingleElementFromSelection(event.getSelection()); IWorkbenchPage page= getSite().getPage(); if (page == null) return; if (page.equals(JavaPlugin.getActivePage()) && JavaBrowsingPart.this.equals(page.getActivePart())) { linkToEditor((IStructuredSelection)event.getSelection()); } } }); fViewer.addOpenListener(new IOpenListener() { public void open(OpenEvent event) { IAction open= fOpenEditorGroup.getOpenAction(); if (open.isEnabled()) { open.run(); restoreSelection(); } } }); } void restoreSelection() { // Default is to do nothing } void adjustInputAndSetSelection(IJavaElement je) { IJavaElement elementToSelect= getSuitableJavaElement(findElementToSelect(je)); IJavaElement newInput= findInputForJavaElement(je); if (elementToSelect == null && !isValidInput(newInput)) // Clear input setInput(null); else if (elementToSelect == null || getViewer().testFindItem(elementToSelect) == null) { // Adjust input to selection setInput(newInput); // Recompute suitable element since it depends on the viewer's input elementToSelect= getSuitableJavaElement(elementToSelect); } if (elementToSelect != null && elementToSelect.exists()) setSelection(new StructuredSelection(elementToSelect), true); else setSelection(StructuredSelection.EMPTY, true); } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; if (isValidInput(je)) return je; return findInputForJavaElement(je.getParent()); } final protected IJavaElement findElementToSelect(Object obj) { if (obj instanceof IJavaElement) return findElementToSelect((IJavaElement)obj); return null; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ abstract protected IJavaElement findElementToSelect(IJavaElement je); protected final Object getSingleElementFromSelection(ISelection selection) { if (!(selection instanceof StructuredSelection) || selection.isEmpty()) return null; Iterator iter= ((StructuredSelection)selection).iterator(); Object firstElement= iter.next(); if (!(firstElement instanceof IJavaElement)) { if (firstElement instanceof ISearchResultViewEntry) { IJavaElement je= SearchUtil.getJavaElement((ISearchResultViewEntry)firstElement); if (je != null) return je; firstElement= ((ISearchResultViewEntry)firstElement).getResource(); } if (firstElement instanceof IAdaptable) { IJavaElement je= (IJavaElement)((IAdaptable)firstElement).getAdapter(IJavaElement.class); if (je == null && firstElement instanceof IFile) { IContainer parent= ((IFile)firstElement).getParent(); if (parent != null) return (IJavaElement)parent.getAdapter(IJavaElement.class); else return null; } else return je; } else return firstElement; } Object currentInput= (IJavaElement)getViewer().getInput(); if (currentInput == null || !currentInput.equals(findInputForJavaElement((IJavaElement)firstElement))) if (iter.hasNext()) // multi selection and view is empty return null; else // ok: single selection and view is empty return firstElement; // be nice to multi selection while (iter.hasNext()) { Object element= iter.next(); if (!(element instanceof IJavaElement)) return null; if (!currentInput.equals(findInputForJavaElement((IJavaElement)element))) return null; } return firstElement; } /** * Gets the typeComparator. * @return Returns a JavaElementTypeComparator */ protected Comparator getTypeComparator() { return fTypeComparator; } /** * Links to editor (if option enabled) */ private void linkToEditor(IStructuredSelection selection) { Object obj= selection.getFirstElement(); if (selection.size() == 1) { IEditorPart part= EditorUtility.isOpenInEditor(obj); if (part != null) { IWorkbenchPage page= getSite().getPage(); page.bringToTop(part); if (obj instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) obj); } } } void setSelectionFromEditor(IWorkbenchPart part) { if (!JavaBasePreferencePage.linkBrowsingViewSelectionToEditor()) return; if (part == null) return; IWorkbenchPartSite site= part.getSite(); if (site == null) return; ISelectionProvider provider= site.getSelectionProvider(); if (provider != null) setSelectionFromEditor(part, provider.getSelection()); } private void setSelectionFromEditor(IWorkbenchPart part, ISelection selection) { if (part instanceof IEditorPart) { IEditorInput ei= ((IEditorPart)part).getEditorInput(); if (selection instanceof ITextSelection) { int offset= ((ITextSelection)selection).getOffset(); IJavaElement element= getElementForInputAt(ei, offset); if (element != null) { adjustInputAndSetSelection(element); return; } } if (ei instanceof IFileEditorInput) { IFile file= ((IFileEditorInput)ei).getFile(); IJavaElement je= (IJavaElement)file.getAdapter(IJavaElement.class); if (je == null) { IContainer container= ((IFileEditorInput)ei).getFile().getParent(); if (container != null) je= (IJavaElement)container.getAdapter(IJavaElement.class); } if (je == null) { setSelection(null, false); return; } adjustInputAndSetSelection(je); } else if (ei instanceof IClassFileEditorInput) { IClassFile cf= ((IClassFileEditorInput)ei).getClassFile(); adjustInputAndSetSelection(cf); } } } /** * Returns the element contained in the EditorInput */ Object getElementOfInput(IEditorInput input) { if (input instanceof IClassFileEditorInput) return ((IClassFileEditorInput)input).getClassFile(); else if (input instanceof IFileEditorInput) return ((IFileEditorInput)input).getFile(); else if (input instanceof JarEntryEditorInput) return ((JarEntryEditorInput)input).getStorage(); return null; } private IResource getResourceFor(Object element) { if (element instanceof IJavaElement) { if (element instanceof IWorkingCopy) { IWorkingCopy wc= (IWorkingCopy)element; IJavaElement original= wc.getOriginalElement(); if (original != null) element= original; } try { element= ((IJavaElement)element).getUnderlyingResource(); } catch (JavaModelException e) { return null; } } if (!(element instanceof IResource) || ((IResource)element).isPhantom()) { return null; } return (IResource)element; } private void setSelection(ISelection selection, boolean reveal) { if (selection != null && selection.equals(fViewer.getSelection())) return; fProcessSelectionEvents= false; fViewer.setSelection(selection, reveal); fProcessSelectionEvents= true; } /** * Tries to find the given element in a workingcopy. */ protected static IJavaElement getWorkingCopy(IJavaElement input) { try { if (input instanceof ICompilationUnit) return ((ICompilationUnit)input).findSharedWorkingCopy(JavaUI.getBufferFactory()); else return EditorUtility.getWorkingCopy(input, false); } catch (JavaModelException ex) { } return null; } /** * Returns the original element from which the specified working copy * element was created from. This is a handle only method, the * returned element may or may not exist. * * @param workingCopy the element for which to get the original * @return the original Java element or <code>null</code> if this is not a working copy element */ protected static IJavaElement getOriginal(IJavaElement workingCopy) { ICompilationUnit cu= getCompilationUnit(workingCopy); if (cu != null) return ((IWorkingCopy)cu).getOriginal(workingCopy); return null; } /** * Returns the compilation unit for the given java element. * * @param element the java element whose compilation unit is searched for * @return the compilation unit of the given java element */ protected static ICompilationUnit getCompilationUnit(IJavaElement element) { if (element == null) return null; if (element instanceof IMember) return ((IMember) element).getCompilationUnit(); int type= element.getElementType(); if (IJavaElement.COMPILATION_UNIT == type) return (ICompilationUnit) element; if (IJavaElement.CLASS_FILE == type) return null; return getCompilationUnit(element.getParent()); } /** * Converts the given Java element to one which is suitable for this * view. It takes into account wether the view shows working copies or not. * * @param element the Java element to be converted * @return an element suitable for this view */ IJavaElement getSuitableJavaElement(Object obj) { if (!(obj instanceof IJavaElement)) return null; IJavaElement element= (IJavaElement)obj; if (fTypeComparator.compare(element, IJavaElement.COMPILATION_UNIT) > 0) return element; if (element.getElementType() == IJavaElement.CLASS_FILE) return element; if (isInputAWorkingCopy()) { IJavaElement wc= getWorkingCopy(element); if (wc != null) element= wc; return element; } else { ICompilationUnit cu= getCompilationUnit(element); if (cu != null && ((IWorkingCopy)cu).isWorkingCopy()) return ((IWorkingCopy)cu).getOriginal(element); else return element; } } boolean isInputAWorkingCopy() { return ((StandardJavaElementContentProvider)getViewer().getContentProvider()).getProvideWorkingCopy(); } /** * @see JavaEditor#getElementAt(int) */ protected IJavaElement getElementForInputAt(IEditorInput input, int offset) { if (input instanceof IClassFileEditorInput) { try { return ((IClassFileEditorInput)input).getClassFile().getElementAt(offset); } catch (JavaModelException ex) { return null; } } IWorkingCopyManager manager= JavaPlugin.getDefault().getWorkingCopyManager(); ICompilationUnit unit= manager.getWorkingCopy(input); if (unit != null) try { unit.reconcile(); return unit.getElementAt(offset); } catch (JavaModelException ex) { } return null; } protected IType getTypeForCU(ICompilationUnit cu) { cu= (ICompilationUnit)getSuitableJavaElement(cu); // Use primary type if possible IType primaryType= cu.findPrimaryType(); if (primaryType != null) return primaryType; // Use first top-level type try { IType[] types= cu.getTypes(); if (types.length > 0) return types[0]; else return null; } catch (JavaModelException ex) { return null; } } void setProcessSelectionEvents(boolean state) { fProcessSelectionEvents= state; } /* (non-Javadoc) * @see org.eclipse.jdt.internal.ui.viewsupport.IViewPartInputProvider#getViewPartInput() */ public Object getViewPartInput() { if (fViewer != null) { return fViewer.getInput(); } return null; } }
24,082
Bug 24082 Do refesh when JavaElementSorter changes
MembersOrderPreferencePage.PREF_OUTLINE_SORT_OPTION is the pref key. Must be added to the browsing views that show members.
resolved fixed
8b0c314
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-26T14:11:36Z
2002-09-25T13:20:00Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/browsing/MembersView.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.browsing; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Composite; import org.eclipse.jface.action.IToolBarManager; import org.eclipse.jface.viewers.DoubleClickEvent; import org.eclipse.jface.viewers.IDoubleClickListener; import org.eclipse.jface.viewers.ILabelProvider; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.viewers.StructuredViewer; import org.eclipse.jface.viewers.TreeViewer; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IMemento; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportContainer; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.ui.OverrideIndicatorLabelDecorator; import org.eclipse.jdt.ui.actions.MemberFilterActionGroup; import org.eclipse.jdt.internal.ui.IJavaHelpContextIds; import org.eclipse.jdt.internal.ui.viewsupport.AppearanceAwareLabelProvider; import org.eclipse.jdt.internal.ui.viewsupport.ProblemTreeViewer; public class MembersView extends JavaBrowsingPart { private MemberFilterActionGroup fMemberFilterActionGroup; public MembersView() { setHasWorkingSetFilter(false); setHasCustomSetFilter(false); } /** * Creates and returns the label provider for this part. * * @return the label provider * @see ILabelProvider */ protected ILabelProvider createLabelProvider() { return new AppearanceAwareLabelProvider( AppearanceAwareLabelProvider.DEFAULT_TEXTFLAGS, AppearanceAwareLabelProvider.DEFAULT_IMAGEFLAGS, AppearanceAwareLabelProvider.getDecorators(true, new OverrideIndicatorLabelDecorator(null)) ); } /** * Returns the context ID for the Help system * * @return the string used as ID for the Help context */ protected String getHelpContextId() { return IJavaHelpContextIds.MEMBERS_VIEW; } /** * Creates the the viewer of this part. * * @param parent the parent for the viewer */ protected StructuredViewer createViewer(Composite parent) { ProblemTreeViewer viewer= new ProblemTreeViewer(parent, SWT.MULTI); fMemberFilterActionGroup= new MemberFilterActionGroup(viewer, JavaUI.ID_MEMBERS_VIEW); return viewer; } protected void fillToolBar(IToolBarManager tbm) { tbm.add(new LexicalSortingAction(getViewer(), JavaUI.ID_MEMBERS_VIEW)); fMemberFilterActionGroup.contributeToToolBar(tbm); } /** * Answers if the given <code>element</code> is a valid * input for this part. * * @param element the object to test * @return <true> if the given element is a valid input */ protected boolean isValidInput(Object element) { if (element instanceof IType) { IType type= (IType)element; return type.isBinary() || type.getDeclaringType() == null; } return false; } /** * Answers if the given <code>element</code> is a valid * element for this part. * * @param element the object to test * @return <true> if the given element is a valid element */ protected boolean isValidElement(Object element) { if (element instanceof IMember) return super.isValidElement(((IMember)element).getDeclaringType()); else if (element instanceof IImportDeclaration) return isValidElement(((IJavaElement)element).getParent()); else if (element instanceof IImportContainer) { Object input= getViewer().getInput(); if (input instanceof IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { ICompilationUnit importContainerCu= (ICompilationUnit)((IJavaElement)element).getAncestor(IJavaElement.COMPILATION_UNIT); return cu.equals(importContainerCu); } else { IClassFile cf= (IClassFile)((IJavaElement)input).getAncestor(IJavaElement.CLASS_FILE); IClassFile importContainerCf= (IClassFile)((IJavaElement)element).getAncestor(IJavaElement.CLASS_FILE); return cf != null && cf.equals(importContainerCf); } } } return false; } /** * Finds the element which has to be selected in this part. * * @param je the Java element which has the focus */ protected IJavaElement findElementToSelect(IJavaElement je) { if (je == null) return null; switch (je.getElementType()) { case IJavaElement.TYPE: if (((IType)je).getDeclaringType() == null) return null; // fall through case IJavaElement.METHOD: // fall through case IJavaElement.FIELD: // fall through case IJavaElement.PACKAGE_DECLARATION: // fall through case IJavaElement.IMPORT_CONTAINER: return getSuitableJavaElement(je); case IJavaElement.IMPORT_DECLARATION: je= getSuitableJavaElement(je); if (je != null) { ICompilationUnit cu= (ICompilationUnit)je.getParent().getParent(); try { if (cu.getImports()[0].equals(je)) { Object selectedElement= getSingleElementFromSelection(getViewer().getSelection()); if (selectedElement instanceof IImportContainer) return (IImportContainer)selectedElement; } } catch (JavaModelException ex) { // return je; } return je; } break; } return null; } /** * Finds the closest Java element which can be used as input for * this part and has the given Java element as child * * @param je the Java element for which to search the closest input * @return the closest Java element used as input for this part */ protected IJavaElement findInputForJavaElement(IJavaElement je) { if (je == null || !je.exists()) return null; switch (je.getElementType()) { case IJavaElement.TYPE: IType type= ((IType)je).getDeclaringType(); if (type == null) return je; else return findInputForJavaElement(type); case IJavaElement.COMPILATION_UNIT: return getTypeForCU((ICompilationUnit)je); case IJavaElement.CLASS_FILE: try { return findInputForJavaElement(((IClassFile)je).getType()); } catch (JavaModelException ex) { return null; } case IJavaElement.IMPORT_DECLARATION: return findInputForJavaElement(je.getParent()); case IJavaElement.PACKAGE_DECLARATION: case IJavaElement.IMPORT_CONTAINER: IJavaElement parent= je.getParent(); if (parent instanceof ICompilationUnit) { IType[] types; try { types= ((ICompilationUnit)parent).getAllTypes(); } catch (JavaModelException ex) { return null; } if (types.length > 0) return types[0]; else return null; } else if (parent instanceof IClassFile) return findInputForJavaElement(parent); default: if (je instanceof IMember) return findInputForJavaElement(((IMember)je).getDeclaringType()); } return null; } /* * Implements method from IViewPart. */ public void saveState(IMemento memento) { super.saveState(memento); fMemberFilterActionGroup.saveState(memento); } protected void restoreState(IMemento memento) { super.restoreState(memento); fMemberFilterActionGroup.restoreState(memento); getViewer().getControl().setRedraw(false); getViewer().refresh(); getViewer().getControl().setRedraw(true); } protected void hookViewerListeners() { super.hookViewerListeners(); getViewer().addDoubleClickListener(new IDoubleClickListener() { public void doubleClick(DoubleClickEvent event) { TreeViewer viewer= (TreeViewer)getViewer(); Object element= ((IStructuredSelection)event.getSelection()).getFirstElement(); if (viewer.isExpandable(element)) viewer.setExpandedState(element, !viewer.getExpandedState(element)); } }); } boolean isInputAWorkingCopy() { Object input= getViewer().getInput(); if (input instanceof IJavaElement) { ICompilationUnit cu= (ICompilationUnit)((IJavaElement)input).getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) return cu.isWorkingCopy(); } return false; } protected void restoreSelection() { IEditorPart editor= getViewSite().getPage().getActiveEditor(); if (editor != null) setSelectionFromEditor(editor); } }
24,124
Bug 24124 Opening hierarchy on method shows <Unknown Label>
Build 20020924 1. Preferences->Workbench->Perspectives->Open a new perspective->In a new window 2. Perefereces->Java->When opening a Type Hierarchy->Open a new Type Hierarchy Perspective 3. Create the following cu: public class X { void foo() { } } 4. In Outline select foo 5. Open type hierarchy Observe: A new window opens but its title starts with <Unknown Label>
resolved fixed
0a14e04
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-27T08:36:49Z
2002-09-26T11:33:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/util/OpenTypeHierarchyUtil.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.util; import org.eclipse.core.runtime.CoreException; import org.eclipse.jface.util.Assert; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IPerspectiveDescriptor; import org.eclipse.ui.IPerspectiveRegistry; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.WorkbenchException; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IImportDeclaration; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IMember; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.ui.JavaUI; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaUIMessages; import org.eclipse.jdt.internal.ui.actions.OpenActionUtil; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaBasePreferencePage; import org.eclipse.jdt.internal.ui.typehierarchy.TypeHierarchyViewPart; public class OpenTypeHierarchyUtil { private OpenTypeHierarchyUtil() { } /** * @deprecated Use org.eclipse.jdt.ui.actions.OpenTypeHierarchyAction directly */ public static boolean canOperateOn(ISelection s) { Object element= getElement(s); return (element != null) ? (getCandidates(element) != null) : false; } public static TypeHierarchyViewPart open(IJavaElement element, IWorkbenchWindow window) { IJavaElement[] candidates= getCandidates(element); if (candidates != null) { return open(candidates, window); } return null; } public static TypeHierarchyViewPart open(IJavaElement[] candidates, IWorkbenchWindow window) { Assert.isTrue(candidates != null && candidates.length != 0); IJavaElement input= null; if (candidates.length > 1) { String title= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.title"); //$NON-NLS-1$ String message= JavaUIMessages.getString("OpenTypeHierarchyUtil.selectionDialog.message"); //$NON-NLS-1$ input= OpenActionUtil.selectJavaElement(candidates, window.getShell(), title, message); } else { input= candidates[0]; } if (input == null) return null; try { if (JavaBasePreferencePage.openTypeHierarchyInPerspective()) { return openInPerspective(window, input); } else { return openInViewPart(window, input); } } catch (WorkbenchException e) { ExceptionHandler.handle(e, window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_perspective"), //$NON-NLS-1$ e.getMessage()); } catch (JavaModelException e) { ExceptionHandler.handle(e, window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_editor"), //$NON-NLS-1$ e.getMessage()); } return null; } private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IJavaElement input) { IWorkbenchPage page= window.getActivePage(); try { // 1GEUMSG: ITPJUI:WINNT - Class hierarchy not shown when fast view if (input instanceof IMember) { openEditor(input); } TypeHierarchyViewPart result= (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); result.setInputElement(input); if (input instanceof IMember) { result.selectMember((IMember) input); } return result; } catch (CoreException e) { ExceptionHandler.handle(e, window.getShell(), JavaUIMessages.getString("OpenTypeHierarchyUtil.error.open_view"), e.getMessage()); //$NON-NLS-1$ } return null; } private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement input) throws WorkbenchException, JavaModelException { IWorkbench workbench= JavaPlugin.getDefault().getWorkbench(); // The problem is that the input element can be a working copy. So we first convert it to the original element if // it exists. if (input instanceof IMember) { ICompilationUnit cu= ((IMember)input).getCompilationUnit(); if (cu != null && cu.isWorkingCopy()) { IJavaElement je= cu.getOriginal(input); if (je != null) input= je; } } IWorkbenchPage page= workbench.showPerspective(JavaUI.ID_HIERARCHYPERSPECTIVE, window, input); if (input instanceof IMember) { openEditor(input); } return (TypeHierarchyViewPart)page.showView(JavaUI.ID_TYPE_HIERARCHY); } private static void openEditor(Object input) throws PartInitException, JavaModelException { IEditorPart part= EditorUtility.openInEditor(input, true); if (input instanceof IJavaElement) EditorUtility.revealInEditor(part, (IJavaElement) input); } private static IWorkbenchPage findPage(IWorkbenchWindow window) { IPerspectiveRegistry registry= PlatformUI.getWorkbench().getPerspectiveRegistry(); IPerspectiveDescriptor pd= registry.findPerspectiveWithId(JavaUI.ID_HIERARCHYPERSPECTIVE); IWorkbenchPage pages[]= window.getPages(); for (int i= 0; i < pages.length; i++) { IWorkbenchPage page= pages[i]; if (page.getPerspective().equals(pd)) return page; } return null; } private static Object getElement(ISelection s) { if (!(s instanceof IStructuredSelection)) return null; IStructuredSelection selection= (IStructuredSelection)s; if (selection.size() != 1) return null; return selection.getFirstElement(); } /** * Converts the input to a possible input candidates */ public static IJavaElement[] getCandidates(Object input) { if (!(input instanceof IJavaElement)) { return null; } try { IJavaElement elem= (IJavaElement) input; switch (elem.getElementType()) { case IJavaElement.INITIALIZER: case IJavaElement.METHOD: case IJavaElement.FIELD: case IJavaElement.TYPE: case IJavaElement.PACKAGE_FRAGMENT_ROOT: case IJavaElement.JAVA_PROJECT: return new IJavaElement[] { elem }; case IJavaElement.PACKAGE_FRAGMENT: if (((IPackageFragment)elem).containsJavaResources()) return new IJavaElement[] {elem}; break; case IJavaElement.PACKAGE_DECLARATION: return new IJavaElement[] { elem.getAncestor(IJavaElement.PACKAGE_FRAGMENT) }; case IJavaElement.IMPORT_DECLARATION: IImportDeclaration decl= (IImportDeclaration) elem; if (decl.isOnDemand()) { elem= JavaModelUtil.findTypeContainer(elem.getJavaProject(), Signature.getQualifier(elem.getElementName())); } else { elem= elem.getJavaProject().findType(elem.getElementName()); } if (elem == null) return null; return new IJavaElement[] {elem}; case IJavaElement.CLASS_FILE: return new IJavaElement[] { ((IClassFile)input).getType() }; case IJavaElement.COMPILATION_UNIT: { ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); if (cu != null) { IType[] types= cu.getTypes(); if (types.length > 0) { return types; } } break; } default: } } catch (JavaModelException e) { JavaPlugin.log(e); } return null; } }
24,101
Bug 24101 JavaWorkingSetPage.setSelection should work without container being set [general issue]
null
verified fixed
6166ea9
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-27T10:13:26Z
2002-09-25T18:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/workingsets/JavaWorkingSetPage.java
24,174
Bug 24174 quick fix: should not add 'return' to new void methods [quick fix]
20020924 it creates methods like: private void md() { return; } which is bogus
resolved fixed
ef9113c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-27T12:10:59Z
2002-09-27T09:46:40Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/NewMethodCompletionProposal.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.swt.graphics.Image; import org.eclipse.jface.text.IDocument; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.texteditor.ITextEditor; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.Signature; import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.dom.AST; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.AnonymousClassDeclaration; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IBinding; import org.eclipse.jdt.core.dom.ITypeBinding; import org.eclipse.jdt.core.dom.Javadoc; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.MethodInvocation; import org.eclipse.jdt.core.dom.Modifier; import org.eclipse.jdt.core.dom.Name; import org.eclipse.jdt.core.dom.PrimitiveType; import org.eclipse.jdt.core.dom.ReturnStatement; import org.eclipse.jdt.core.dom.SimpleName; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.Type; import org.eclipse.jdt.core.dom.TypeDeclaration; import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings; import org.eclipse.jdt.internal.corext.codemanipulation.NameProposer; import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility; 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.refactoring.changes.CompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextRange; import org.eclipse.jdt.internal.ui.JavaPlugin; import org.eclipse.jdt.internal.ui.JavaPluginImages; import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility; import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings; public class NewMethodCompletionProposal extends ASTRewriteCorrectionProposal { private ASTNode fNode; // MethodInvocation, ConstructorInvocation, SuperConstructorInvocation, ClassInstanceCreation, SuperMethodInvocation private List fArguments; private ITypeBinding fSenderBinding; private boolean fIsLocalChange; public NewMethodCompletionProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode, List arguments, ITypeBinding binding, int relevance, Image image) { super(label, targetCU, null, relevance, image); fNode= invocationNode; fArguments= arguments; fSenderBinding= binding; } protected ASTRewrite getRewrite() throws CoreException { ASTRewrite rewrite; CompilationUnit astRoot= ASTResolving.findParentCompilationUnit(fNode); ASTNode typeDecl= astRoot.findDeclaringNode(fSenderBinding); ASTNode newTypeDecl= null; if (typeDecl != null) { fIsLocalChange= true; ASTCloner cloner= new ASTCloner(new AST(), astRoot); CompilationUnit newRoot= (CompilationUnit) cloner.getClonedRoot(); rewrite= new ASTRewrite(newRoot); newTypeDecl= cloner.getCloned(typeDecl); } else { fIsLocalChange= false; CompilationUnit newRoot= AST.parseCompilationUnit(getCompilationUnit(), true); rewrite= new ASTRewrite(newRoot); newTypeDecl= ASTResolving.findTypeDeclaration(newRoot, fSenderBinding); } if (newTypeDecl != null) { List methods; if (fSenderBinding.isAnonymous()) { methods= ((AnonymousClassDeclaration) newTypeDecl).bodyDeclarations(); } else { methods= ((TypeDeclaration) newTypeDecl).bodyDeclarations(); } MethodDeclaration newStub= getStub(newTypeDecl.getAST()); if (fIsLocalChange) { methods.add(findInsertIndex(methods, fNode.getStartPosition()), newStub); } else if (isConstructor()) { methods.add(0, newStub); } else { methods.add(newStub); } rewrite.markAsInserted(newStub); } return rewrite; } private boolean isConstructor() { return fNode.getNodeType() != ASTNode.METHOD_INVOCATION && fNode.getNodeType() != ASTNode.SUPER_METHOD_INVOCATION; } private MethodDeclaration getStub(AST ast) throws CoreException { MethodDeclaration decl= ast.newMethodDeclaration(); decl.setConstructor(isConstructor()); decl.setModifiers(evaluateModifiers()); decl.setName(ast.newSimpleName(getMethodName())); NameProposer nameProposer= new NameProposer(); List arguments= fArguments; List params= decl.parameters(); int nArguments= arguments.size(); ArrayList names= new ArrayList(nArguments); for (int i= 0; i < arguments.size(); i++) { Expression elem= (Expression) arguments.get(i); SingleVariableDeclaration param= ast.newSingleVariableDeclaration(); Type type= evaluateParameterType(ast, elem); param.setType(type); param.setName(ast.newSimpleName(getParameterName(nameProposer, names, elem, type))); params.add(param); } Block body= ast.newBlock(); if (!isConstructor()) { Type returnType= evaluateMethodType(ast); decl.setReturnType(returnType); ReturnStatement returnStatement= ast.newReturnStatement(); returnStatement.setExpression(ASTResolving.getInitExpression(returnType)); body.statements().add(returnStatement); } decl.setBody(body); CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(); if (settings.createComments && !fSenderBinding.isAnonymous()) { StringBuffer buf= new StringBuffer(); String[] namesArray= (String[]) names.toArray(new String[names.size()]); String name= decl.getName().getIdentifier(); if (isConstructor()) { StubUtility.genJavaDocStub("Constructor " + name, namesArray, null, null, buf); } else { String returnTypeSig= Signature.createTypeSignature(ASTNodes.asString(decl.getReturnType()), true); StubUtility.genJavaDocStub("Method " + name, namesArray, returnTypeSig, null, buf); } Javadoc javadoc= ast.newJavadoc(); javadoc.setComment(buf.toString()); decl.setJavadoc(javadoc); } return decl; } private String getParameterName(NameProposer nameProposer, ArrayList takenNames, Expression argNode, Type type) { String name; if (argNode instanceof SimpleName) { name= ((SimpleName) argNode).getIdentifier(); } else { name= nameProposer.proposeParameterName(ASTNodes.asString(type)); } String base= name; int i= 1; while (takenNames.contains(name)) { name= base + i++; } takenNames.add(name); return name; } private int findInsertIndex(List decls, int currPos) { int nDecls= decls.size(); for (int i= 0; i < nDecls; i++) { ASTNode curr= (ASTNode) decls.get(i); if (curr instanceof MethodDeclaration && currPos < curr.getStartPosition() + curr.getLength()) { return i + 1; } } return nDecls; } private String getMethodName() { if (fNode instanceof MethodInvocation) { return ((MethodInvocation)fNode).getName().getIdentifier(); } else if (fNode instanceof SuperMethodInvocation) { return ((SuperMethodInvocation)fNode).getName().getIdentifier(); } else { return fSenderBinding.getName(); // name of the class } } private int evaluateModifiers() { if (fNode instanceof MethodInvocation) { int modifiers= 0; Expression expression= ((MethodInvocation)fNode).getExpression(); if (expression != null) { if (expression instanceof Name && ((Name) expression).resolveBinding().getKind() == IBinding.TYPE) { modifiers |= Modifier.STATIC; } } else if (ASTResolving.isInStaticContext(fNode)) { modifiers |= Modifier.STATIC; } if (fIsLocalChange) { modifiers |= Modifier.PRIVATE; } else if (!fSenderBinding.isInterface()) { modifiers |= Modifier.PUBLIC; } return modifiers; } return Modifier.PUBLIC; } private Type evaluateMethodType(AST ast) throws CoreException { ITypeBinding binding= ASTResolving.getTypeBinding(fNode); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newPrimitiveType(PrimitiveType.VOID); } private Type evaluateParameterType(AST ast, Expression expr) throws CoreException { ITypeBinding binding= ASTResolving.getTypeBinding(expr.resolveTypeBinding()); if (binding != null) { addImport(binding); return ASTResolving.getTypeFromTypeBinding(ast, binding); } return ast.newSimpleType(ast.newSimpleName("Object")); } public void apply(IDocument document) { try { CompilationUnitChange change= getCompilationUnitChange(); IEditorPart part= null; if (!fIsLocalChange) { change.setKeepExecutedTextEdits(true); part= EditorUtility.openInEditor(getCompilationUnit(), true); } super.apply(document); if (part instanceof ITextEditor) { TextRange range= change.getExecutedTextEdit(change.getEdit()).getTextRange(); ((ITextEditor) part).selectAndReveal(range.getOffset(), range.getLength()); } } catch (CoreException e) { JavaPlugin.log(e); } } }
23,479
Bug 23479 Initializers (static and non-static) should be displayed as private [render]
The java element label provider should be changed to render the private access icon rather than package access icons for initializers, since they're not accessible outside the class.
resolved fixed
62e6c4c
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-30T09:32:32Z
2002-09-12T14:13:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/viewsupport/JavaElementImageProvider.java
/* * (c) Copyright IBM Corp. 2000, 2001. * All Rights Reserved. */ package org.eclipse.jdt.internal.ui.viewsupport; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.util.Assert; import org.eclipse.ui.ISharedImages; import org.eclipse.ui.model.IWorkbenchAdapter; import org.eclipse.jdt.core.Flags; import org.eclipse.jdt.core.IField; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IMember; 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.ui.JavaElementImageDescriptor; 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.JavaUIMessages; /** * Default strategy of the Java plugin for the construction of Java element icons. */ public class JavaElementImageProvider { /** * Flags for the JavaImageLabelProvider: * Generate images with overlays. */ public final static int OVERLAY_ICONS= 0x1; /** * Generate small sized images. */ public final static int SMALL_ICONS= 0x2; /** * Use the 'light' style for rendering types. */ public final static int LIGHT_TYPE_ICONS= 0x4; public static final Point SMALL_SIZE= new Point(16, 16); public static final Point BIG_SIZE= new Point(22, 16); private static ImageDescriptor DESC_OBJ_PROJECT_CLOSED; private static ImageDescriptor DESC_OBJ_PROJECT; private static ImageDescriptor DESC_OBJ_FOLDER; { ISharedImages images= JavaPlugin.getDefault().getWorkbench().getSharedImages(); DESC_OBJ_PROJECT_CLOSED= images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT_CLOSED); DESC_OBJ_PROJECT= images.getImageDescriptor(ISharedImages.IMG_OBJ_PROJECT); DESC_OBJ_FOLDER= images.getImageDescriptor(ISharedImages.IMG_OBJ_FOLDER); } private ImageDescriptorRegistry fRegistry; public JavaElementImageProvider() { fRegistry= JavaPlugin.getImageDescriptorRegistry(); } /** * Returns the icon for a given element. The icon depends on the element type * and element properties. If configured, overlay icons are constructed for * <code>ISourceReference</code>s. * @param flags Flags as defined by the JavaImageLabelProvider */ public Image getImageLabel(Object element, int flags) { return getImageLabel(computeDescriptor(element, flags)); } private Image getImageLabel(ImageDescriptor descriptor){ if (descriptor == null) return null; return fRegistry.get(descriptor); } private ImageDescriptor computeDescriptor(Object element, int flags){ if (element instanceof IJavaElement) return getJavaImageDescriptor((IJavaElement) element, flags); else if (element instanceof IAdaptable) return getWorkbenchImageDescriptor((IAdaptable) element, flags); return null; } private static boolean showOverlayIcons(int flags) { return (flags & OVERLAY_ICONS) != 0; } private static boolean useSmallSize(int flags) { return (flags & SMALL_ICONS) != 0; } private static boolean useLightIcons(int flags) { return (flags & LIGHT_TYPE_ICONS) != 0; } /** * Returns an image descriptor for a java element. The descriptor includes overlays, if specified. */ public ImageDescriptor getJavaImageDescriptor(IJavaElement element, int flags) { int adornmentFlags= computeJavaAdornmentFlags(element, flags); Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(getBaseImageDescriptor(element, flags), adornmentFlags, size); } /** * Returns an image descriptor for a IAdaptable. The descriptor includes overlays, if specified (only error ticks apply). * Returns <code>null</code> if no image could be found. */ public ImageDescriptor getWorkbenchImageDescriptor(IAdaptable adaptable, int flags) { IWorkbenchAdapter wbAdapter= (IWorkbenchAdapter) adaptable.getAdapter(IWorkbenchAdapter.class); if (wbAdapter == null) { return null; } ImageDescriptor descriptor= wbAdapter.getImageDescriptor(adaptable); if (descriptor == null) { return null; } Point size= useSmallSize(flags) ? SMALL_SIZE : BIG_SIZE; return new JavaElementImageDescriptor(descriptor, 0, size); } // ---- Computation of base image key ------------------------------------------------- /** * Returns an image descriptor for a java element. This is the base image, no overlays. */ public ImageDescriptor getBaseImageDescriptor(IJavaElement element, int renderFlags) { try { switch (element.getElementType()) { case IJavaElement.INITIALIZER: case IJavaElement.METHOD: IMember member= (IMember) element; return getMethodImageDescriptor(member.getDeclaringType().isInterface(), member.getFlags()); case IJavaElement.FIELD: IField field= (IField) element; return getFieldImageDescriptor(field.getDeclaringType().isInterface(), field.getFlags()); case IJavaElement.PACKAGE_DECLARATION: return JavaPluginImages.DESC_OBJS_PACKDECL; case IJavaElement.IMPORT_DECLARATION: return JavaPluginImages.DESC_OBJS_IMPDECL; case IJavaElement.IMPORT_CONTAINER: return JavaPluginImages.DESC_OBJS_IMPCONT; case IJavaElement.TYPE: { IType type= (IType) element; boolean isInterface= type.isInterface(); if (useLightIcons(renderFlags)) { return isInterface ? JavaPluginImages.DESC_OBJS_INTERFACEALT : JavaPluginImages.DESC_OBJS_CLASSALT; } boolean isInner= type.getDeclaringType() != null; return getTypeImageDescriptor(isInterface, isInner, type.getFlags()); } case IJavaElement.PACKAGE_FRAGMENT_ROOT: { IPackageFragmentRoot root= (IPackageFragmentRoot) element; if (root.isArchive()) { IPath attach= root.getSourceAttachmentPath(); if (root.isExternal()) { if (attach == null) { return JavaPluginImages.DESC_OBJS_EXTJAR; } else { return JavaPluginImages.DESC_OBJS_EXTJAR_WSRC; } } else { if (attach == null) { return JavaPluginImages.DESC_OBJS_JAR; } else { return JavaPluginImages.DESC_OBJS_JAR_WSRC; } } } else { return JavaPluginImages.DESC_OBJS_PACKFRAG_ROOT; } } case IJavaElement.PACKAGE_FRAGMENT: IPackageFragment fragment= (IPackageFragment)element; boolean doesNotContainJavaElements= false; try { doesNotContainJavaElements= !fragment.hasChildren(); } catch(JavaModelException e) { return DESC_OBJ_FOLDER; } if (doesNotContainJavaElements && (fragment.getNonJavaResources().length >0)) return DESC_OBJ_FOLDER; else if (doesNotContainJavaElements) return JavaPluginImages.DESC_OBJS_EMPTY_PACKAGE; return JavaPluginImages.DESC_OBJS_PACKAGE; case IJavaElement.COMPILATION_UNIT: return JavaPluginImages.DESC_OBJS_CUNIT; case IJavaElement.CLASS_FILE: /* this is too expensive for large packages try { IClassFile cfile= (IClassFile)element; if (cfile.isClass()) return JavaPluginImages.IMG_OBJS_CFILECLASS; return JavaPluginImages.IMG_OBJS_CFILEINT; } catch(JavaModelException e) { // fall through; }*/ return JavaPluginImages.DESC_OBJS_CFILE; case IJavaElement.JAVA_PROJECT: IJavaProject jp= (IJavaProject)element; if (jp.getProject().isOpen()) { IProject project= jp.getProject(); IWorkbenchAdapter adapter= (IWorkbenchAdapter)project.getAdapter(IWorkbenchAdapter.class); if (adapter != null) { ImageDescriptor result= adapter.getImageDescriptor(project); if (result != null) return result; } return DESC_OBJ_PROJECT; } return DESC_OBJ_PROJECT_CLOSED; case IJavaElement.JAVA_MODEL: return JavaPluginImages.DESC_OBJS_JAVA_MODEL; } Assert.isTrue(false, JavaUIMessages.getString("JavaImageLabelprovider.assert.wrongImage")); //$NON-NLS-1$ return null; //$NON-NLS-1$ } catch (JavaModelException e) { if (!e.isDoesNotExist()) { JavaPlugin.log(e); } return JavaPluginImages.DESC_OBJS_GHOST; } } public void dispose() { } // ---- Methods to compute the adornments flags --------------------------------- private int computeJavaAdornmentFlags(IJavaElement element, int renderFlags) { int flags= 0; if (showOverlayIcons(renderFlags) && element instanceof IMember) { try { IMember member= (IMember) element; if (element.getElementType() == IJavaElement.METHOD && ((IMethod)element).isConstructor()) flags |= JavaElementImageDescriptor.CONSTRUCTOR; int modifiers= member.getFlags(); if (Flags.isAbstract(modifiers) && confirmAbstract(member)) flags |= JavaElementImageDescriptor.ABSTRACT; if (Flags.isFinal(modifiers) || isInterfaceField(member)) flags |= JavaElementImageDescriptor.FINAL; if (Flags.isSynchronized(modifiers) && confirmSynchronized(member)) flags |= JavaElementImageDescriptor.SYNCHRONIZED; if (Flags.isStatic(modifiers) || isInterfaceField(member)) flags |= JavaElementImageDescriptor.STATIC; if (member.getElementType() == IJavaElement.TYPE) { if (JavaModelUtil.hasMainMethod((IType) member)) { flags |= JavaElementImageDescriptor.RUNNABLE; } } } catch (JavaModelException e) { // do nothing. Can't compute runnable adornment or get flags } } return flags; } private static boolean confirmAbstract(IMember element) throws JavaModelException { // never show the abstract symbol on interfaces or members in interfaces if (element.getElementType() == IJavaElement.TYPE) { return ((IType) element).isClass(); } return element.getDeclaringType().isClass(); } private static boolean isInterfaceField(IMember element) throws JavaModelException { // always show the final && static symbol on interface fields if (element.getElementType() == IJavaElement.FIELD) { return element.getDeclaringType().isInterface(); } return false; } private static boolean confirmSynchronized(IJavaElement member) { // Synchronized types are allowed but meaningless. return member.getElementType() != IJavaElement.TYPE; } public static ImageDescriptor getMethodImageDescriptor(boolean isInInterface, int flags) { if (Flags.isPublic(flags) || isInInterface) return JavaPluginImages.DESC_MISC_PUBLIC; if (Flags.isProtected(flags)) return JavaPluginImages.DESC_MISC_PROTECTED; if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_MISC_PRIVATE; return JavaPluginImages.DESC_MISC_DEFAULT; } public static ImageDescriptor getFieldImageDescriptor(boolean isInInterface, int flags) { if (Flags.isPublic(flags) || isInInterface) return JavaPluginImages.DESC_FIELD_PUBLIC; if (Flags.isProtected(flags)) return JavaPluginImages.DESC_FIELD_PROTECTED; if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_FIELD_PRIVATE; return JavaPluginImages.DESC_FIELD_DEFAULT; } public static ImageDescriptor getTypeImageDescriptor(boolean isInterface, boolean isInner, int flags) { if (isInner) { if (isInterface) { return getInnerInterfaceImageDescriptor(flags); } else { return getInnerClassImageDescriptor(flags); } } else { if (isInterface) { return getInterfaceImageDescriptor(flags); } else { return getClassImageDescriptor(flags); } } } private static ImageDescriptor getClassImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_CLASS; else return JavaPluginImages.DESC_OBJS_CLASS_DEFAULT; } private static ImageDescriptor getInnerClassImageDescriptor(int flags) { if (Flags.isPublic(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PUBLIC; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_INNER_CLASS_PROTECTED; else return JavaPluginImages.DESC_OBJS_INNER_CLASS_DEFAULT; } private static ImageDescriptor getInterfaceImageDescriptor(int flags) { if (Flags.isPublic(flags) || Flags.isProtected(flags) || Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INTERFACE; else return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT; } private static ImageDescriptor getInnerInterfaceImageDescriptor(int flags) { if (Flags.isPublic(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PUBLIC; else if (Flags.isPrivate(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PRIVATE; else if (Flags.isProtected(flags)) return JavaPluginImages.DESC_OBJS_INNER_INTERFACE_PROTECTED; else return JavaPluginImages.DESC_OBJS_INTERFACE_DEFAULT; } }
22,624
Bug 22624 Rename CU quick fix: Exception when renaming to an existing CU:
20020820 Java Model Exception: Java Model Status [Name collision.] at org.eclipse.jdt.internal.core.MultiOperation.processElements (MultiOperation.java:207) at org.eclipse.jdt.internal.core.CopyResourceElementsOperation.processElements (CopyResourceElementsOperation.java:343) at org.eclipse.jdt.internal.core.MultiOperation.executeOperation (MultiOperation.java:98) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:305) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:513) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1361) at org.eclipse.jdt.internal.core.JavaModelManager.runOperation (JavaModelManager.java:1207) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:574) at org.eclipse.jdt.internal.core.JavaModel.rename(JavaModel.java:437) at org.eclipse.jdt.internal.core.CompilationUnit.rename (CompilationUnit.java:819) at org.eclipse.jdt.internal.corext.refactoring.changes.RenameCompilationUnitChange. doRename(RenameCompilationUnitChange.java:50) at org.eclipse.jdt.internal.corext.refactoring.AbstractJavaElementRenameChange.perf orm(AbstractJavaElementRenameChange.java:67) at org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal.apply (ChangeCorrectionProposal.java:59) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:232) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposal (CompletionProposalPopup.java:208) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$13 (CompletionProposalPopup.java:204) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$2.widgetDefaultSele cted(CompletionProposalPopup.java:177) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:94) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:827) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1529) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1291) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1177) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) !ENTRY org.eclipse.jdt.core 4 977 Aug 21, 2002 12:18:53.273 !MESSAGE Name collision. !ENTRY org.eclipse.jdt.ui 4 1 Aug 21, 2002 12:18:53.283 !MESSAGE Internal Error !STACK 0 ChangeAbortException: org.eclipse.jdt.internal.corext.refactoring.base.ChangeAbortException at org.eclipse.jdt.internal.ui.refactoring.changes.AbortChangeExceptionHandler.hand le(AbortChangeExceptionHandler.java:22) at org.eclipse.jdt.internal.corext.refactoring.base.Change.handleException (Change.java:99) at org.eclipse.jdt.internal.corext.refactoring.AbstractJavaElementRenameChange.perf orm(AbstractJavaElementRenameChange.java:72) at org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal.apply (ChangeCorrectionProposal.java:59) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:232) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposal (CompletionProposalPopup.java:208) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$13 (CompletionProposalPopup.java:204) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$2.widgetDefaultSele cted(CompletionProposalPopup.java:177) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:94) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:827) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1529) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1291) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1177) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24) Exception wrapped by ChangeAbortException: Java Model Exception: Java Model Status [Name collision.] at org.eclipse.jdt.internal.core.MultiOperation.processElements (MultiOperation.java:207) at org.eclipse.jdt.internal.core.CopyResourceElementsOperation.processElements (CopyResourceElementsOperation.java:343) at org.eclipse.jdt.internal.core.MultiOperation.executeOperation (MultiOperation.java:98) at org.eclipse.jdt.internal.core.JavaModelOperation.execute (JavaModelOperation.java:305) at org.eclipse.jdt.internal.core.JavaModelOperation.run (JavaModelOperation.java:513) at org.eclipse.core.internal.resources.Workspace.run (Workspace.java:1361) at org.eclipse.jdt.internal.core.JavaModelManager.runOperation (JavaModelManager.java:1207) at org.eclipse.jdt.internal.core.JavaElement.runOperation (JavaElement.java:574) at org.eclipse.jdt.internal.core.JavaModel.rename(JavaModel.java:437) at org.eclipse.jdt.internal.core.CompilationUnit.rename (CompilationUnit.java:819) at org.eclipse.jdt.internal.corext.refactoring.changes.RenameCompilationUnitChange. doRename(RenameCompilationUnitChange.java:50) at org.eclipse.jdt.internal.corext.refactoring.AbstractJavaElementRenameChange.perf orm(AbstractJavaElementRenameChange.java:67) at org.eclipse.jdt.internal.ui.text.correction.ChangeCorrectionProposal.apply (ChangeCorrectionProposal.java:59) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.insertProposal (CompletionProposalPopup.java:232) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.selectProposal (CompletionProposalPopup.java:208) at org.eclipse.jface.text.contentassist.CompletionProposalPopup.access$13 (CompletionProposalPopup.java:204) at org.eclipse.jface.text.contentassist.CompletionProposalPopup$2.widgetDefaultSele cted(CompletionProposalPopup.java:177) at org.eclipse.swt.widgets.TypedListener.handleEvent (TypedListener.java:94) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:77) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:827) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:1529) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:1291) at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:1177) at org.eclipse.ui.internal.Workbench.run(Workbench.java:1160) at org.eclipse.core.internal.boot.InternalBootLoader.run (InternalBootLoader.java:775) at org.eclipse.core.boot.BootLoader.run(BootLoader.java:432) at EclipseRuntimeLauncher.main(EclipseRuntimeLauncher.java:24)
resolved fixed
ff72001
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-30T10:31:29Z
2002-08-21T08:53:20Z
org.eclipse.jdt.ui/ui/org/eclipse/jdt/internal/ui/text/correction/ReorgCorrectionsSubProcessor.java
/******************************************************************************* * Copyright (c) 2000, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.ui.text.correction; import java.util.ArrayList; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IPackageDeclaration; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.internal.corext.refactoring.CompositeChange; import org.eclipse.jdt.internal.corext.refactoring.changes.CreatePackageChange; import org.eclipse.jdt.internal.corext.refactoring.changes.MoveCompilationUnitChange; import org.eclipse.jdt.internal.corext.refactoring.changes.RenameCompilationUnitChange; import org.eclipse.jdt.internal.corext.textmanipulation.TextBuffer; import org.eclipse.jdt.internal.corext.textmanipulation.TextRegion; import org.eclipse.jdt.internal.corext.util.JavaModelUtil; import org.eclipse.jdt.internal.ui.JavaPluginImages; public class ReorgCorrectionsSubProcessor { public static void getWrongTypeNameProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException { String[] args= problemPos.getArguments(); if (args.length == 2) { ICompilationUnit cu= problemPos.getCompilationUnit(); // rename type Path path= new Path(args[0]); String newName= path.removeFileExtension().lastSegment(); String label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.renametype.description", newName); //$NON-NLS-1$ proposals.add(new ReplaceCorrectionProposal(label, problemPos, newName, 1)); String newCUName= args[1] + ".java"; //$NON-NLS-1$ final RenameCompilationUnitChange change= new RenameCompilationUnitChange(cu, newCUName); label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.renamecu.description", newCUName); //$NON-NLS-1$ // rename cu proposals.add(new ChangeCorrectionProposal(label, change, 2, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_RENAME))); } } public static void getWrongPackageDeclNameProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException { String[] args= problemPos.getArguments(); if (args.length == 1) { ICompilationUnit cu= problemPos.getCompilationUnit(); // correct pack decl proposals.add(new CorrectPackageDeclarationProposal(problemPos, 1)); // move to pack IPackageFragment currPack= (IPackageFragment) cu.getParent(); IPackageDeclaration[] packDecls= cu.getPackageDeclarations(); String newPackName= packDecls.length > 0 ? packDecls[0].getElementName() : ""; //$NON-NLS-1$ IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(cu); IPackageFragment newPack= root.getPackageFragment(newPackName); String label; if (newPack.isDefaultPackage()) { label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.movecu.default.description", cu.getElementName()); //$NON-NLS-1$ } else { label= CorrectionMessages.getFormattedString("ReorgCorrectionsSubProcessor.movecu.description", new Object[] { cu.getElementName(), newPack.getElementName() }); //$NON-NLS-1$ } final CompositeChange composite= new CompositeChange(label); composite.add(new CreatePackageChange(newPack)); composite.add(new MoveCompilationUnitChange(cu, newPack)); proposals.add(new ChangeCorrectionProposal(label, composite, 2, JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_MOVE))); } } public static void removeImportStatementProposals(ProblemPosition problemPos, ArrayList proposals) throws CoreException { TextBuffer buffer= null; try { buffer= aquireTextBuffer(problemPos.getCompilationUnit()); int line= buffer.getLineOfOffset(problemPos.getOffset()); if (line != -1) { TextRegion region= buffer.getLineInformation(line); int start= region.getOffset(); int end= start + region.getLength(); if (line > 0) { region= buffer.getLineInformation(line - 1); start= region.getOffset() + region.getLength(); } String label= CorrectionMessages.getString("ReorgCorrectionsSubProcessor.unusedimport.description"); //$NON-NLS-1$ ReplaceCorrectionProposal proposal= new ReplaceCorrectionProposal(label, problemPos.getCompilationUnit(), start, end - start, "", 0); //$NON-NLS-1$ proposal.setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_DELETE_IMPORT)); proposals.add(proposal); } } finally { if (buffer != null) { TextBuffer.release(buffer); } } } private static TextBuffer aquireTextBuffer(ICompilationUnit cu) throws CoreException { if (cu.isWorkingCopy()) { cu= (ICompilationUnit) cu.getOriginalElement(); } IFile file= (IFile) cu.getUnderlyingResource(); return TextBuffer.acquire(file); } }
21,794
Bug 21794 organize impors: should not touch files if it does not modify them
2.0 select a package and run organize imports on it - every file is touched (cvs dirty flag appears) regardless if it was modified or not
resolved fixed
d0e17ae
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-30T14:48:12Z
2002-07-23T10:26:40Z
org.eclipse.jdt.ui/core
21,794
Bug 21794 organize impors: should not touch files if it does not modify them
2.0 select a package and run organize imports on it - every file is touched (cvs dirty flag appears) regardless if it was modified or not
resolved fixed
d0e17ae
JDT
https://github.com/eclipse-jdt/eclipse.jdt.ui
eclipse-jdt/eclipse.jdt.ui
java
null
null
null
2002-09-30T14:48:12Z
2002-07-23T10:26:40Z
extension/org/eclipse/jdt/internal/corext/codemanipulation/ImportsStructure.java